protected virtual async Task <string> RequestPostAsync(int pageNumber) { var requestRegistration = new CancellationTokenRegistration(); try { string url = "https://www.tumblr.com/search/" + Blog.Name + "/post_page/" + pageNumber; string referer = @"https://www.tumblr.com/search/" + Blog.Name; var headers = new Dictionary <string, string> { { "X-tumblr-form-key", tumblrKey }, { "DNT", "1" } }; HttpWebRequest request = WebRequestFactory.CreatePostXhrReqeust(url, referer, headers); CookieService.GetUriCookie(request.CookieContainer, new Uri("https://www.tumblr.com/")); //Example request body, searching for cars: //q=cars&sort=top&post_view=masonry&blogs_before=8&num_blogs_shown=8&num_posts_shown=20&before=24&blog_page=2&safe_mode=true&post_page=2&filter_nsfw=true&filter_post_type=&next_ad_offset=0&ad_placement_id=0&more_posts=true string requestBody = "q=" + Blog.Name + "&sort=top&post_view=masonry&num_posts_shown=" + ((pageNumber - 1) * Blog.PageSize) + "&before=" + ((pageNumber - 1) * Blog.PageSize) + "&safe_mode=false&post_page=" + pageNumber + "&filter_nsfw=false&filter_post_type=&next_ad_offset=0&ad_placement_id=0&more_posts=true"; await WebRequestFactory.PerformPostXHRReqeustAsync(request, requestBody); requestRegistration = Ct.Register(() => request.Abort()); return(await WebRequestFactory.ReadReqestToEndAsync(request)); } finally { requestRegistration.Dispose(); } }
private async Task <string> GetGuestToken() { if (guestToken == null) { var requestRegistration = new CancellationTokenRegistration(); try { string url = await GetApiUrl(Blog.Url, 0, "", 0); if (ShellService.Settings.LimitConnectionsApi) { CrawlerService.TimeconstraintApi.Acquire(); } var headers = new Dictionary <string, string>(); headers.Add("Origin", "https://twitter.com"); headers.Add("Authorization", "Bearer " + BearerToken); HttpWebRequest request = WebRequestFactory.CreatePostRequest(url, "https://twitter.com", headers); CookieService.GetUriCookie(request.CookieContainer, new Uri("https://twitter.com")); requestRegistration = Ct.Register(() => request.Abort()); var content = await WebRequestFactory.ReadRequestToEndAsync(request); guestToken = ((JValue)((JObject)JsonConvert.DeserializeObject(content))["guest_token"]).Value <string>(); } catch (Exception e) { Logger.Error("GetGuestToken: {0}", e); } finally { requestRegistration.Dispose(); } } return(guestToken); }
public void SendStyle(EStyle Style) { if (Style == EStyle.Blue) { Icon = Assets.Musix_Icon_Blue; } else if (Style == EStyle.Color) { Icon = Assets.Musix_Icon_Rainbow; } foreach (Control Ct in Controls) { if (typeof(IStyleableControl).IsAssignableFrom(Ct.GetType())) { IStyleableControl styleableControl = Ct as IStyleableControl; styleableControl.SendStyle(Style); } } foreach (Control Ct in PNContent.Controls) { if (typeof(IStyleableControl).IsAssignableFrom(Ct.GetType())) { IStyleableControl styleableControl = Ct as IStyleableControl; styleableControl.SendStyle(Style); } } }
protected async Task <string> RequestApiDataAsync(string url, string bearerToken, Dictionary <string, string> headers = null, IEnumerable <string> cookieHosts = null) { var requestRegistration = new CancellationTokenRegistration(); try { HttpWebRequest request = WebRequestFactory.CreateGetRequest(url, string.Empty, headers); cookieHosts = cookieHosts ?? new List <string>(); foreach (string cookieHost in cookieHosts) { CookieService.GetUriCookie(request.CookieContainer, new Uri(cookieHost)); } request.PreAuthenticate = true; request.Headers.Add("Authorization", "Bearer " + bearerToken); request.Accept = "application/json"; requestRegistration = Ct.Register(() => request.Abort()); return(await WebRequestFactory.ReadRequestToEndAsync(request)); } finally { requestRegistration.Dispose(); } }
private void Form1_Load(object sender, EventArgs e) { this.ContextMenuStrip = Program.AddNewUserControlCMS; Program.LabelControlCMS = LabelContextMenuStrip1; foreach (Control Ctrl in this.Controls) { if (Ctrl.GetType().ToString() == "System.Windows.Forms.Panel") { Ctrl.ContextMenuStrip = Program.AddNewUserControlCMS; foreach (Control Ct in Ctrl.Controls) { if (Ct.GetType().ToString() == "System.Windows.Forms.Panel") { Ct.ContextMenuStrip = Program.AddNewUserControlCMS; } } } } Menus.InitAddUserControls(ref ArticlecontextMenuStrip1); Left_panel.Controls.RemoveByKey("UCref"); RightSubPanel.Controls.RemoveByKey("UCref"); RightSubPanel.Controls.Clear(); reclamaPanel.Controls.Clear(); UCFunctions.AddUC(this); //Left_panel.Controls.Add(new AuthenticationUserControl(new List<string>()) { Location = new Point(0,0), Dock = DockStyle.Top , Name = "qq"}); GC.Collect(); GC.WaitForPendingFinalizers(); arts.Clear(); //textBox_password.UseSystemPasswordChar = true; // button_add_reklama.Visible = false; lable_name_of_polzovatel.Text = Users.CURRENT_USER; AdmButton.Visible = IS_ADMIN; AutButton.Visible = IS_AUTHOR; button2.Visible = false; if (IS_ADMIN) { button2.Visible = true; } /* #region Advertising * * reclamaPanel.Controls.Clear(); * AdsUserControl recl = new AdsUserControl(new List<string>() { "5", "20" }); * reclamaPanel.Controls.Add(recl); * #endregion*/ textBox_search.Text = LAST_SEARCH; Search_Click(sender, e); popularArticlesLabel.ContextMenuStrip = Program.LabelControlCMS; }
// Recherche de l'arrete sur laquelle est contrainte la platine. private Edge ArretePlatine(List <Mate2> listeContraintes, Feature planContrainte, Face2 f_Dessus) { Mate2 Contrainte = null; foreach (Mate2 Ct in listeContraintes) { foreach (MateEntity2 Ent in Ct.eListeDesEntitesDeContrainte()) { // Si l'entite est un plan if (Ent.ReferenceType2 == (int)swSelectType_e.swSelDATUMPLANES) { RefPlane P = Ent.Reference; Feature F = (Feature)P; // On vérifie que le plan a le même nom que le plan contrainte if (planContrainte.Name == F.Name) { Contrainte = Ct; break; } } } if (Contrainte.IsRef()) { break; } } foreach (MateEntity2 Ent in Contrainte.eListeDesEntitesDeContrainte()) { // On récupère la face associée à la contrainte if (Ent.ReferenceType2 == (int)swSelectType_e.swSelFACES) { Face2 F = Ent.Reference; // Liste des arrêtes communes, normalement, il n'y en a qu'une List <Edge> L = F.eListeDesArretesCommunes(f_Dessus); // On renvoi la première if (L.Count > 0) { return(L[0]); } } } return(null); }
/// <summary> /// Returns true if OrderChangeMessage instances are equal /// </summary> /// <param name="other">Instance of OrderChangeMessage to be compared</param> /// <returns>Boolean</returns> public bool Equals(OrderChangeMessage other) { // credit: http://stackoverflow.com/a/10454552/677735 if (other == null) { return(false); } return((Op == other.Op || Op != null && Op.Equals(other.Op)) && (Id == other.Id || Id != null && Id.Equals(other.Id)) && (Ct == other.Ct || Ct != null && Ct.Equals(other.Ct)) && (Clk == other.Clk || Clk != null && Clk.Equals(other.Clk)) && (HeartbeatMs == other.HeartbeatMs || HeartbeatMs != null && HeartbeatMs.Equals(other.HeartbeatMs)) && (Pt == other.Pt || Pt != null && Pt.Equals(other.Pt)) && (Oc == other.Oc || Oc != null && Oc.SequenceEqual(other.Oc)) && (InitialClk == other.InitialClk || InitialClk != null && InitialClk.Equals(other.InitialClk)) && (ConflateMs == other.ConflateMs || ConflateMs != null && ConflateMs.Equals(other.ConflateMs)) && (SegmentType == other.SegmentType || SegmentType != null && SegmentType.Equals(other.SegmentType))); }
protected async Task <string> RequestDataAsync(string url, Dictionary <string, string> headers = null, IEnumerable <string> cookieHosts = null) { var requestRegistration = new CancellationTokenRegistration(); try { int redirects = 0; ResponseDetails responseDetails; do { HttpWebRequest request = WebRequestFactory.CreateGetRequest(url, string.Empty, headers, false); cookieHosts = cookieHosts ?? new List <string>(); foreach (string cookieHost in cookieHosts) { CookieService.GetUriCookie(request.CookieContainer, new Uri(cookieHost)); } requestRegistration = Ct.Register(() => request.Abort()); responseDetails = await WebRequestFactory.ReadRequestToEnd2Async(request); if (responseDetails.HttpStatusCode == HttpStatusCode.Found) { url = request.RequestUri.GetLeftPart(UriPartial.Authority) + responseDetails.RedirectUrl; } } while (responseDetails.HttpStatusCode == HttpStatusCode.Found && redirects++ < 5); if (responseDetails.HttpStatusCode == HttpStatusCode.Found) { throw new WebException("Too many automatic redirections were attempted.", WebExceptionStatus.ProtocolError); } return(responseDetails.Response); } finally { requestRegistration.Dispose(); } }
protected async Task <string> RequestDataAsync(string url, Dictionary <string, string> headers = null, IEnumerable <string> cookieHosts = null) { var requestRegistration = new CancellationTokenRegistration(); try { HttpWebRequest request = WebRequestFactory.CreateGetReqeust(url, string.Empty, headers); cookieHosts = cookieHosts ?? new List <string>(); foreach (string cookieHost in cookieHosts) { CookieService.GetUriCookie(request.CookieContainer, new Uri(cookieHost)); } requestRegistration = Ct.Register(() => request.Abort()); return(await WebRequestFactory.ReadReqestToEndAsync(request)); } finally { requestRegistration.Dispose(); } }
protected virtual async Task <string> RequestDataAsync(string limit, string offset) { var requestRegistration = new CancellationTokenRegistration(); try { string url = @"https://www.tumblr.com/svc/indash_blog?tumblelog_name_or_id=" + Blog.Name + @"&post_id=&limit=" + limit + "&offset=" + offset + "&should_bypass_safemode=true"; string referer = @"https://www.tumblr.com/dashboard/blog/" + Blog.Name; var headers = new Dictionary <string, string> { { "X-tumblr-form-key", tumblrKey } }; HttpWebRequest request = WebRequestFactory.CreateGetXhrRequest(url, referer, headers); CookieService.GetUriCookie(request.CookieContainer, new Uri("https://www.tumblr.com/")); CookieService.GetUriCookie(request.CookieContainer, new Uri("https://" + Blog.Name.Replace("+", "-") + ".tumblr.com")); requestRegistration = Ct.Register(() => request.Abort()); return(await WebRequestFactory.ReadRequestToEndAsync(request)); } finally { requestRegistration.Dispose(); } }
private void btnEdit_Click(object sender, EventArgs e) { var selectedRow = dgvQuestions.CurrentRow; if (selectedRow == null) { MessageBox.Show(@"未选中任何行!"); return; } var index = selectedRow.Index; var cells = dgvQuestions.Rows[index].Cells; var model = new Ct((int)cells["id"].Value, cells["tg"].Value.ToString(), cells["a"].Value.ToString(), cells["b"].Value.ToString(), cells["c"].Value.ToString(), cells["d"].Value.ToString(), cells["da"].Value.ToString()); var child = new AddOrEditForm(model) { StartPosition = FormStartPosition.CenterParent, Text = @"修改" }; child.ReloadDgv += Child_ReloadDgv; child.ShowDialog(this); }
/// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { // credit: http://stackoverflow.com/a/263416/677735 unchecked // Overflow is fine, just wrap { var hash = 41; // Suitable nullity checks etc, of course :) if (Op != null) { hash = hash * 59 + Op.GetHashCode(); } if (Id != null) { hash = hash * 59 + Id.GetHashCode(); } if (Ct != null) { hash = hash * 59 + Ct.GetHashCode(); } if (Clk != null) { hash = hash * 59 + Clk.GetHashCode(); } if (HeartbeatMs != null) { hash = hash * 59 + HeartbeatMs.GetHashCode(); } if (Pt != null) { hash = hash * 59 + Pt.GetHashCode(); } if (Oc != null) { hash = hash * 59 + Oc.GetHashCode(); } if (InitialClk != null) { hash = hash * 59 + InitialClk.GetHashCode(); } if (ConflateMs != null) { hash = hash * 59 + ConflateMs.GetHashCode(); } if (SegmentType != null) { hash = hash * 59 + SegmentType.GetHashCode(); } return(hash); } }
private new void WriteValues(string p_SubKeyName, ref Generic.SortedList <string, string> p_KeyValuePairs, bool p_CheckForCurrentProfileStore) { // Write all key values to an XML file // SubKey has to be absolute from the profile store root XmlWriterSettings WriterSettings; string FName; int Ct; swSupport.Reset(); swSupport.Start(); // Start timing this call TL.LogMessage(" WriteValues", " SubKeyName: " + p_SubKeyName); if (Strings.Left(p_SubKeyName, 1) != @"\") { p_SubKeyName = @"\" + p_SubKeyName; } try { Ct = 0; foreach (Generic.KeyValuePair <string, string> kvp in p_KeyValuePairs) { Ct += 1; TL.LogMessage(" WriteValues List", " " + Ct.ToString() + " " + kvp.Key + " = " + kvp.Value); } WriterSettings = new XmlWriterSettings(); WriterSettings.Indent = true; FName = FileStore.FullPath(p_SubKeyName + @"\" + VALUES_FILENAME_NEW); XmlWriter Writer; FileStream FStream; FStream = new FileStream(FName, FileMode.Create, FileAccess.Write, FileShare.None, 2048, FileOptions.WriteThrough); Writer = XmlWriter.Create(FStream, WriterSettings); // Writer = XmlWriter.Create(FName, WriterSettings) using (Writer) { Writer.WriteStartDocument(); Writer.WriteStartElement(PROFILE_NAME); // Write the profile element Writer.WriteStartElement(DEFAULT_ELEMENT_NAME); // Write the default element Writer.WriteAttributeString(VALUE_ATTRIBUTE_NAME, p_KeyValuePairs.Item(COLLECTION_DEFAULT_VALUE_NAME)); // Write the default value Writer.WriteEndElement(); Ct = 0; foreach (Generic.KeyValuePair <string, string> kvp in p_KeyValuePairs) // Write each named value in turn { Ct += 1; TL.LogMessage(" Writing Value", " " + Ct.ToString() + " " + kvp.Key + " = " + kvp.Value); if (kvp.Value == null) { TL.LogMessage(" Writing Value", " WARNING - Suppplied Value is Nothing not empty string"); } switch (kvp.Key) { case object _ when COLLECTION_DEFAULT_VALUE_NAME // Ignore the default value entry : { break; } default: { Writer.WriteStartElement(VALUE_ELEMENT_NAME); // Write the element name Writer.WriteAttributeString(NAME_ATTRIBUTE_NAME, kvp.Key); // Write the name attribute Writer.WriteAttributeString(VALUE_ATTRIBUTE_NAME, kvp.Value); // Write the value attribute Writer.WriteEndElement(); // Close this element break; } } } Writer.WriteEndElement(); // Flush and close the writer object to complete writing of the XML file. Writer.Close(); // Actualy write the XML to a file } try { FStream.Flush(); FStream.Close(); FStream.Dispose(); FStream = null; } catch (Exception ex) { }// Ensure no error occur from this tidying up Writer = null; try // New file successfully created so now rename the current file to original and rename the new file to current { if (p_CheckForCurrentProfileStore) { FileStore.Rename(p_SubKeyName + @"\" + VALUES_FILENAME, p_SubKeyName + @"\" + VALUES_FILENAME_ORIGINAL); } try { FileStore.Rename(p_SubKeyName + @"\" + VALUES_FILENAME_NEW, p_SubKeyName + @"\" + VALUES_FILENAME); } catch (Exception ex2) { // Attempt to rename new file as current failed so try and restore the original file TL.Enabled = true; TL.LogMessage("XMLAccess:WriteValues", "Unable to rename new profile file to current - " + p_SubKeyName + @"\" + VALUES_FILENAME_NEW + "to " + p_SubKeyName + @"\" + VALUES_FILENAME + " " + ex2.ToString()); try { FileStore.Rename(p_SubKeyName + @"\" + VALUES_FILENAME_ORIGINAL, p_SubKeyName + @"\" + VALUES_FILENAME); } catch (Exception ex3) { // Restoration also failed so no clear recovery from this point TL.Enabled = true; TL.LogMessage("XMLAccess:WriteValues", "Unable to rename original profile file to current - " + p_SubKeyName + @"\" + VALUES_FILENAME_ORIGINAL + "to " + p_SubKeyName + @"\" + VALUES_FILENAME + " " + ex3.ToString()); } } } catch (Exception ex1) { // No clear remedial action as the current file rename failed so just leave as is TL.Enabled = true; TL.LogMessage("XMLAccess:WriteValues", "Unable to rename current profile file to original - " + p_SubKeyName + @"\" + VALUES_FILENAME + "to " + p_SubKeyName + @"\" + VALUES_FILENAME_ORIGINAL + " " + ex1.ToString()); } WriterSettings = null; swSupport.Stop(); TL.LogMessage(" WriteValues", " Created cache entry " + p_SubKeyName + " - " + swSupport.ElapsedMilliseconds + " milliseconds"); } catch (Exception ex) { TL.LogMessageCrLf(" WriteValues", " Exception " + p_SubKeyName + " " + ex.ToString()); Interaction.MsgBox("XMLAccess:Writevalues " + p_SubKeyName + " " + ex.ToString()); } }
protected async Task <string> RequestDataAsync(string url, Dictionary <string, string> headers = null, IEnumerable <string> cookieHosts = null) { var requestRegistration = new CancellationTokenRegistration(); try { int redirects = 0; ResponseDetails responseDetails; do { HttpWebRequest request = WebRequestFactory.CreateGetRequest(url, string.Empty, headers, false); cookieHosts = cookieHosts ?? new List <string>(); foreach (string cookieHost in cookieHosts) { CookieService.GetUriCookie(request.CookieContainer, new Uri(cookieHost)); } requestRegistration = Ct.Register(() => request.Abort()); responseDetails = await WebRequestFactory.ReadRequestToEnd2Async(request); url = responseDetails.RedirectUrl ?? url; if (responseDetails.HttpStatusCode == HttpStatusCode.Found) { if (url.Contains("privacy/consent")) { var ex = new Exception("Acceptance of privacy consent needed!"); ShellService.ShowError(new TumblrPrivacyConsentException(ex), Resources.ConfirmationTumblrPrivacyConsentNeeded); throw ex; } if (!url.StartsWith("http", StringComparison.InvariantCultureIgnoreCase)) { url = request.RequestUri.GetLeftPart(UriPartial.Authority) + url; } } if (responseDetails.HttpStatusCode == HttpStatusCode.Moved) { Uri uri = new Uri(url); if (!uri.Authority.Contains(".tumblr.")) { Blog.Url = uri.GetLeftPart(UriPartial.Authority); } } } while ((responseDetails.HttpStatusCode == HttpStatusCode.Found || responseDetails.HttpStatusCode == HttpStatusCode.Moved) && redirects++ < 5); if (responseDetails.HttpStatusCode == HttpStatusCode.Found) { throw new WebException("Too many automatic redirections were attempted.", WebExceptionStatus.ProtocolError); } return(responseDetails.Response); } catch (Exception e) { Logger.Error("AbstractCrawler.RequestDataAsync: {0}", e); throw; } finally { requestRegistration.Dispose(); } }
protected string RetrieveOriginalImageUrl(string url, int width, int height, bool isInline) { if (width > height) { (width, height) = (height, width); } if (ShellService.Settings.ImageSize != "best" || !isInline && !url.Contains("/s1280x1920/") || (width <= 1280 && height <= 1920) || isInline && !new Regex(@"\/s[\d]{2,4}x[\d]{2,4}\/").IsMatch(url)) { return(url); } if (isInline) { var re = new Regex(@"\/s[\d]{2,4}x[\d]{2,4}\/"); url = re.Replace(url, "/s2048x3072/"); } else { url = url.Replace("/s1280x1920/", (width <= 2048 && height <= 3072) ? "/s2048x3072/" : "/s99999x99999/"); } string pageContent = ""; int errCnt = 0; Exception lastError = null; do { try { HttpWebRequest request = WebRequestFactory.CreateGetRequest(url, "", new Dictionary <string, string>() { { "Accept-Language", "en-US" }, { "Accept-Encoding", "gzip, deflate" } }, false); request.Accept = "text/html, application/xhtml+xml, */*"; request.UserAgent = ShellService.Settings.UserAgent; request.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip; using (Ct.Register(() => request.Abort())) { pageContent = WebRequestFactory.ReadRequestToEndAsync(request).GetAwaiter().GetResult(); } errCnt = 9; } catch (WebException we) { if (we.Status == WebExceptionStatus.RequestCanceled) { throw new NullReferenceException("RetrieveOriginalImageUrl request cancelled"); } if (we.Response != null && ((HttpWebResponse)we.Response).StatusCode == HttpStatusCode.NotFound) { return(url); } } catch (Exception e) { errCnt++; Logger.Error("AbstractTumblrCrawler:RetrieveOriginalImageUrl: {0}", e); lastError = e; if (errCnt < 3) { Thread.Sleep(errCnt * 10000); } } } while (errCnt < 3); if (errCnt == 3) { ShellService.ShowError(lastError, Resources.PostNotParsable, Blog.Name); throw new NullReferenceException("RetrieveOriginalImageUrl download", lastError); } try { var extracted = extractJsonFromPage.Match(pageContent).Groups[1].Value; extracted = new Regex("/.*/").Replace(extracted, "\"\""); ImageResponse imgRsp = DeserializeImageResponse(extracted); int maxWidth = imgRsp.Images.Max(x => x.Width); Image img = imgRsp.Images.FirstOrDefault(x => x.Width == maxWidth); return(string.IsNullOrEmpty(img?.MediaKey) ? url : img.Url); } catch (Exception ex) { Logger.Error("AbstractTumblrCrawler:RetrieveOriginalImageUrl: {0}", ex); ShellService.ShowError(ex, Resources.PostNotParsable, Blog.Name); throw new NullReferenceException("RetrieveOriginalImageUrl parsing", ex); } }
public event Reload ReloadDgv;//定义刷新父页面 dataGridView 的事件 public AddOrEditForm(Ct model = null) { _model = model; InitializeComponent(); }
public Control(long mindimlevel, long maxlumen, string colorgamuttype, List <List <double> > colorgamut, Ct ct) => (Mindimlevel, Maxlumen, Colorgamuttype, Colorgamut, Ct) = (mindimlevel, maxlumen, colorgamuttype, colorgamut, ct);
//% The main file for running the wind farm controll and wake simulation. // It is not completely done yet. Further updates will come // Currently there are only 4 turbines, for test purposes. But is should be // easily updated to a larger number of turbines. // Similarly there is a lot of room for speed optimizations, even though it // now runs slowly with only 4 turbines // 19/07-13 MS public static double[][] Simulation(WakeFarmControlConfig config) { var parm = new WindTurbineParameters(); ILMatFile env; ILMatFile wt; ILArray <int> idx; ILArray <double> ee; double Ki; double Kp; int PC_MaxPit; int PC_MinPit; double VS_CtInSp; double VS_RtGnSp; double VS_Rgn2K; double omega0; double beta0; double power0; ILArray <double> x; ILArray <double> u0; ILArray <double> u; ILArray <double> Mg_old; ILArray <double> P_ref; ILArray <double> Pa; ILArray <double> Power; ILArray <double> Ct; ILArray <double> P_ref_new; ILArray <double> v_nac; double alpha; double Mg_max_rate; ILArray <double> e; ILArray <double> Mg; ILArray <double> beta; ILArray <double> Cp; ILArray <double> Omega; ILArray <double> out_; if (config.NTurbines == 0) { return(null); } // Wind farm properties //turbine properties env = wt = new ILMatFile(config.NREL5MW_MatFile); //Load parameters from the NREL 5MW turbine parm.N = config.NTurbines; // number of turbines in farm parm.rho = (double)env.GetArray <double>("env_rho"); //air density parm.radius = ((double)(wt.GetArray <double>("wt_rotor_radius"))) * ILMath.ones(1, config.NTurbines); // rotor radius (NREL5MW) parm.rated = 5e6 * ILMath.ones(1, config.NTurbines); //rated power (NREL5MW) parm.ratedSpeed = (double)wt.GetArray <double>("wt_rotor_ratedspeed"); //rated rotor speed idx = ILMath.empty <int>(); ILMath.max(wt.GetArray <double>("wt_cp_table")[ILMath.full], idx); //Find index for max Cp; parm.Cp = ILMath.ones(1, config.NTurbines) * wt.GetArray <double>("wt_cp_table").GetValue(idx.ToArray()); //Set power coefficent to maximum value in the cp table parm.Ct = ILMath.ones(1, config.NTurbines) * wt.GetArray <double>("wt_ct_table").GetValue(idx.ToArray()); //Set power coefficent to maximum value in the ct table // NOTE: controller parameters should be imported from the wt....struct in //Pitch control ee = 0; //blade pitch integrator Ki = 0.008068634 * 360 / 2 / ILMath.pi; // integral gain (NREL5MW) Kp = 0.01882681 * 360 / 2 / ILMath.pi; // proportional gain (NREL5MW) PC_MaxPit = 90; PC_MinPit = 0; //region control NREL VS_CtInSp = 70.16224; VS_RtGnSp = 121.6805; VS_Rgn2K = 2.332287; // load initial wind data var wind = new ILMatFile(config.Wind_MatFile); //% Set initial conditions omega0 = 1.267; //Rotation speed beta0 = 0; //Pitch var timeLine = (int)config.TimeLine(); power0 = parm.rated.GetValue(0); //Power production x = (omega0 * ILMath.ones(parm.N, 1)).Concat((wind.GetArray <double>("wind").GetValue(0, 1) * ILMath.ones(parm.N, 1)), 1); u0 = (beta0 * ILMath.ones(parm.N, 1)).Concat((power0 * ILMath.ones(parm.N, 1)), 1); u = u0.C; Mg_old = u[ILMath.full, 1]; P_ref = ILMath.zeros(parm.N, (int)config.TimeLine()); //Initialize matrix to save the power production history for each turbine Pa = P_ref.C; //Initialize available power matrix Power = P_ref.C; Ct = parm.Ct.C; //Initialize Ct - is this correct? Ct[timeLine - 1, ILMath.full] = Ct[0, ILMath.full]; P_ref_new = power0 * ILMath.ones(config.NTurbines, 1); v_nac = ILMath.zeros(Ct.Size[1], timeLine); Mg = ILMath.zeros(u.Size[0], timeLine); beta = ILMath.zeros(u.Size[0], timeLine); Omega = ILMath.zeros(Ct.Size[1], timeLine); Cp = ILMath.zeros(timeLine, parm.Cp.Size[1]); var turbineModel = new TurbineDrivetrainModel(); //% Simulate wind farm operation //var timeLine = (int) config.TimeLine(); for (var i = 2; i <= timeLine; i++) //At each sample time(DT) from Tstart to Tend { //Calculate the wake using the current Ct values { ILArray <double> out_v_nac; WakeCalculation.Calculate((Ct[i - 1 - 1, ILMath.full]), i, wind, out out_v_nac); v_nac[ILMath.full, i - 1] = out_v_nac; } x[ILMath.full, 1] = v_nac[ILMath.full, i - 1]; //Farm control //Calculate the power distribution references for each turbine if (config.EnablePowerDistribution) { ILArray <double> out_Pa; PowerDistributionControl.DistributePower(v_nac[ILMath.full, i - 1], config.Pdemand, Power[ILMath.full, i - 1 - 1], parm, out P_ref_new, out out_Pa); Pa[ILMath.full, i - 1] = out_Pa; } //Hold the demand for some seconds if (ILMath.mod(i, ILMath.round(config.PRefSampleTime / config.DT)) == 2) //??? { P_ref[ILMath.full, i - 1] = P_ref_new; } else { if (config.PowerRefInterpolation) { alpha = 0.01; P_ref[ILMath.full, i - 1] = (1 - alpha) * P_ref[ILMath.full, i - 1 - 1] + (alpha) * P_ref_new; } else { P_ref[ILMath.full, i - 1] = P_ref_new; } } //Calculate control for each individual turbine - should be moved to the //turbine (drivetrain) model. //Torque controller for (var j = 1; j <= parm.N; j++) { if ((x.GetValue(j - 1, 0) * 97 >= VS_RtGnSp) || (u.GetValue(j - 1, 0) >= 1)) // We are in region 3 - power is constant { u.SetValue(P_ref.GetValue(j - 1, i - 1) / x.GetValue(j - 1, 0), j - 1, 1); } else if (x.GetValue(j - 1, 0) * 97 <= VS_CtInSp) //! We are in region 1 - torque is zero { u.SetValue(0.0, j - 1, 1); } else //! We are in region 2 - optimal torque is proportional to the square of the generator speed { u.SetValue(97 * VS_Rgn2K * x.GetValue(j - 1, 0) * x.GetValue(j - 1, 0) * Math.Pow(97, 2), j - 1, 1); } } //Rate limit torque change // u(:,2) - Mg_old; Mg_max_rate = 1e6 * config.DT; u[ILMath.full, 1] = ILMath.sign(u[ILMath.full, 1] - Mg_old) * ILMath.min(ILMath.abs(u[ILMath.full, 1] - Mg_old), Mg_max_rate) + Mg_old; //Pitch controller e = 97 * (omega0 * ILMath.ones(parm.N, 1) - x[ILMath.full, 0]); ee = ee - config.DT * e; ee = ILMath.min(ILMath.max(ee, PC_MinPit / Ki), PC_MaxPit / Ki); u[ILMath.full, 0] = -Kp * config.DT * e + Ki * ee; for (var j = 1; j <= parm.N; j++) { u.SetValue(Math.Min(Math.Max(u.GetValue(j - 1, 0), PC_MinPit), PC_MaxPit), j - 1, 0); } if (!config.EnableTurbineDynamics) { u = u0; } Mg[ILMath.full, i - 1] = u[ILMath.full, 1]; Mg_old = Mg[ILMath.full, i - 1]; beta[ILMath.full, i - 1] = u[ILMath.full, 0]; //Set pitch //Turbine dynamics - can be simplified if (config.EnableTurbineDynamics) { for (var j = 1; j <= parm.N; j++) { double out_x; double out_Ct; double out_Cp; turbineModel.Model(x[j - 1, ILMath.full], u[j - 1, ILMath.full], wt, env, config.DT, out out_x, out out_Ct, out out_Cp); x.SetValue(out_x, j - 1, 0); Ct.SetValue(out_Ct, i - 1, j - 1); Cp.SetValue(out_Cp, i - 1, j - 1); } } else { Ct[i - 1, ILMath.full] = parm.Ct; Cp[i - 1, ILMath.full] = parm.Cp; x[ILMath.full, 0] = parm.ratedSpeed;//Rotational speed } Omega[ILMath.full, i - 1] = x[ILMath.full, 0]; Power[ILMath.full, i - 1] = Omega[ILMath.full, i - 1] * Mg[ILMath.full, i - 1]; } //% Save output data out_ = (config.DT * (ILMath.counter(0, 1, config.TimeLine()))); out_ = out_.Concat(v_nac.T, 1); out_ = out_.Concat(Omega.T, 1); out_ = out_.Concat(beta.T, 1); out_ = out_.Concat(P_ref.T, 1); out_ = out_.Concat(Ct, 1); out_ = out_.Concat(Cp, 1); out_ = out_.Concat(Pa.T, 1); out_ = out_.Concat(Mg.T, 1); out_ = out_.Concat(Power.T, 1); //Ttotal power demand var l = config.NTurbines * 3 + 1; var r = l + config.NTurbines - 1; out_ = out_.Concat(ILMath.sum(out_[ILMath.full, ILMath.r(l, r)], 1) / 1e6, 1); // P_ref sum l = config.NTurbines * 6 + 1; r = l + config.NTurbines - 1; out_ = out_.Concat(ILMath.sum(out_[ILMath.full, ILMath.r(l, r)], 1) / 1e6, 1); // Pa sum. 'Power Demand' out_ = out_.Concat(ILMath.sum(Power).T / 1e6, 1); // 'Actual Production' //Ttotal power demand out_ = out_.Concat(ILMath.sum(P_ref.T, 1), 1); // 'Demand' out_ = out_.Concat(ILMath.sum(Pa.T, 1), 1); // 'Available' out_ = out_.Concat(ILMath.sum(Mg * Omega).T, 1); // 'Actual' //Total power produced out_ = out_.Concat((Mg * Omega).T, 1); var out_doubleArray = new double[out_.Size[0]][]; for (int i = 0; i <= out_doubleArray.GetLength(0) - 1; i++) { out_doubleArray[i] = new double[out_.Size[1]]; for (int j = 0; j <= out_doubleArray[i].GetLength(0) - 1; j++) { out_doubleArray[i][j] = out_.GetValue(i, j); } } return(out_doubleArray); }