static void Main(string[] args) { List<int> list = new List<int>(); int counter = 0; list.Add(5); list.Add(1); list.Add(12); list.Add(15); list.Add(5); list.Add(1); for(int i=0;i<list.Count;i++) { int number = list.ElementAt<int>(i); for(int temp=0;temp<list.Count;temp++) { if(number==list.ElementAt<int>(temp)) { counter++; } } Program.delete(list, counter, number); counter = 0; } if((list.Count%2)==1) { list.RemoveAt((list.Count / 2)); } Console.WriteLine("Here are the numbers that are left : "); for(int i=0;i<list.Count;i++) { Console.WriteLine(list.ElementAt(i)); } }
//计算上层第一个图的DLocation public static DLocation getUpLayerDLocation(List<PictureBoxInfo> downImageNameList, List<PictureBoxInfo> UpImageNameList,int coolingType) { double min = Int32.MaxValue; int flag = 0; for (int i = 0, j = 0, len1 = downImageNameList.Count; i < len1; i++) { double tempValue = Math.Abs(downImageNameList.ElementAt(i).DLocation.X - UpImageNameList.ElementAt(j).DLocation.X); if (min > tempValue) { min = tempValue; flag = i; } //方便到数据库中取数据时用,因为数据库中没有"virtureHRA" if (downImageNameList.ElementAt(i).name.Equals("virtualHRA")) { //PictureBoxInfo virtualHraBox = new PictureBoxInfo(); //virtualHraBox.name = "HRA"; //virtualHraBox.DLocation = downImageNameList.ElementAt(i).DLocation; //downImageNameList[i] = virtualHraBox; downImageNameList.ElementAt(i).name = "HRA"; } } //计算的是相对坐标,还没有加上下层的参照物坐标 List<ImageBlock> downLayerPartImageList = ImageBlockBLL.getImageBlocksByNames(downImageNameList, coolingType, flag); return new DLocation(getPartTotalLength(downLayerPartImageList, flag) + Math.Abs(downImageNameList.ElementAt(flag).DLocation.X - UpImageNameList.ElementAt(0).DLocation.X),downLayerPartImageList[downLayerPartImageList.Count-1].ImageWidth-6,0); }
static void Main(String[] args) { string[] setup = Console.ReadLine().Split(' '); long budget = long.Parse(setup[1]); string[] pricesInput = Console.ReadLine().Split(' '); List<long> prices = new List<long>(); for (int i = 0; i < pricesInput.Length; i++) { prices.Add(long.Parse(pricesInput[i])); } prices.Sort(); long count = 0; while (true) { if (budget - prices.ElementAt(0) >= 0) { budget -= prices.ElementAt(0); prices.RemoveAt(0); count++; } else { break; } } Console.WriteLine(count); }
public async Task GetUserClaims_Should_Retrieve_Correct_Claims_For_User() { string userName = "******"; string userId = "RavenUsers/1"; using (IDocumentStore store = CreateEmbeddableStore()) using (IAsyncDocumentSession ses = store.OpenAsyncSession()) { IUserClaimStore<RavenUser> userClaimStore = new RavenUserStore<RavenUser>(ses); IEnumerable<RavenUserClaim> claims = new List<RavenUserClaim> { new RavenUserClaim { ClaimType = "Scope", ClaimValue = "Read" }, new RavenUserClaim { ClaimType = "Scope", ClaimValue = "Write" } }; RavenUser user = new RavenUser { Id = userId, UserName = userName }; foreach (var claim in claims) { user.Claims.Add(claim); } await ses.StoreAsync(user); await ses.SaveChangesAsync(); IEnumerable<Claim> retrievedClaims = await userClaimStore.GetClaimsAsync(user); Assert.Equal(2, claims.Count()); Assert.Equal("Read", claims.ElementAt(0).ClaimValue); Assert.Equal("Write", claims.ElementAt(1).ClaimValue); } }
public IEnumerable<int> GetFibonacciNumbers(int input) { List<int> result = new List<int>(); int currentIndex = -1; if (input >= 0) { result.Add(0); currentIndex++; } if (input >= 1) { result.Add(1); currentIndex++; } while (currentIndex > -1 && result.ElementAt(currentIndex) < input) { var newValue = result.ElementAt(currentIndex - 1) + result.ElementAt(currentIndex); if (newValue > input) break; else { result.Add(newValue); currentIndex++; } } return result; }
public static double weekly() { double result = 0; try { List<String> list = DataManagement.readInfo(); List<double> numbers = new List<double>(); List<InfoClass> classList = new List<InfoClass>(); for (int i = 0; i < list.Count; i++) { String[] temp = list.ElementAt(i).Split('|'); InfoClass temp1 = new InfoClass(temp[0], temp[1], temp[2]); classList.Add(temp1); } for (int i = 0; i < classList.Count; i++) { DateTime time = DateTime.Parse(classList.ElementAt(i).Date); DateTime timeToday = DateTime.Now; DateTime timeMinusSeven = timeToday.AddDays(-7); if (timeToday >= time && time >= timeMinusSeven) { double temporary = double.Parse(classList.ElementAt(i).Price); result += temporary; } } }catch(FileNotFoundException ex) { throw; } return result; }
public void AddText(String s) { messages.Add(s); List<String> tokens = new List<String>(s.Split(' ')); if (StringOrDefault(tokens.ElementAt(0)) == "") return; // abort if it doesn't have anything Node lastNode = null; String[] currentWord = new String[ORDER]; for(int i = 0; i < tokens.Count - (ORDER - 1); i++) { for (int j = 0; j < ORDER; j++) currentWord[j] = StringOrDefault(tokens.ElementAt(i + j)); var currentNode = nodes.ContainsKey(currentWord) ? nodes[currentWord] : null; if (currentNode == null) { currentNode = new Node(currentWord); nodes.Add(currentWord, currentNode); } if (lastNode == null) starts.Add(currentNode); else AddPair(lastNode, currentNode); lastNode = new Node(currentNode.Value.Clone() as String[]); } }
public IList<long> Generate(long firstNumber, long lastNumber) { List<long> fibonacciSequence = null; if(_argumentValidator.FirstNumberIsValid(firstNumber)) { long previousNumber = 0; if(firstNumber != 0) { previousNumber = firstNumber - 1; } var currentNumber = firstNumber; fibonacciSequence = new List<long>{ previousNumber }; while (currentNumber <= lastNumber) { fibonacciSequence.Add(currentNumber); previousNumber = fibonacciSequence.ElementAt(fibonacciSequence.Count - 1); currentNumber = fibonacciSequence.ElementAt(fibonacciSequence.Count - 2) + previousNumber; } } return fibonacciSequence; }
void setCoolDowns(List<string> coolDownList) { this.skill.CoolDownLv1 = int.Parse(coolDownList.First()); this.skill.CoolDownLv2 = int.Parse(coolDownList.ElementAt(1)); this.skill.CoolDownLv3 = int.Parse(coolDownList.ElementAt(2)); this.skill.CoolDownLv4 = int.Parse(coolDownList.ElementAt(3)); }
void setManaCost(List<string> manaCostList) { this.skill.ManaCostLv1 = int.Parse(manaCostList.First()); this.skill.ManaCostLv2 = int.Parse(manaCostList.ElementAt(1)); this.skill.ManaCostLv3 = int.Parse(manaCostList.ElementAt(2)); this.skill.ManaCostLv4 = int.Parse(manaCostList.ElementAt(3)); }
static void Main(string[] args) { int a = int.Parse(Console.ReadLine()); List<string> list = new List<string>(); bool hasStuck = false; list.AddRange(Console.ReadLine().Split(' ').ToList()); for (int i = 0; i < list.Count; i++) { for (int j = 0; j < list.Count; j++) { for (int m = 0; m < list.Count; m++) { for (int n = 0; n < list.Count; n++) { string number1 = list.ElementAt(i); string number2 = list.ElementAt(j); string number3 = list.ElementAt(m); string number4 = list.ElementAt(n); if (areDistinct(number1, number2, number3, number4)) { if ((number1 + number2 == number3 + number4)) { hasStuck = true; Console.WriteLine("{0}|{1} == {2}|{3}", number1, number2, number3, number4); } } } } } } }
static void Main(string[] args) { Console.WriteLine("Enter desired text:"); List<string> text = new List<string>(); string addToText = Console.ReadLine(); Console.WriteLine("Enter desired word:"); string word = Console.ReadLine(); while(!addToText.Equals("")) { text.Add(addToText); addToText = Console.ReadLine(); } string separators = "[!.?]"; for (int i = 0; i < text.Count; i++) { if (text.ElementAt(i).Contains(word)) { String[] sentence = Regex.Split(text.ElementAt(i), separators, RegexOptions.IgnoreCase); for (int j = 0; j < sentence.Length; j++) { if (sentence[j].Contains(word)) { Console.WriteLine(sentence[j]); Console.WriteLine(); } } } } }
public MovingBlock(List<Block> list) { int x = 0; for (int i = 0; i < list.Count(); ++i) { Block block = list.ElementAt(i); if (block.type == "moving"&&!block.inlist) { x = block.cbox.X; this.cbox.X = block.cbox.X; this.cbox.Y = block.cbox.Y; blocks.Add(block); block.inlist = true; cbox = block.cbox; break; } } for (int j = 0; j < 10; ++j) { cbox.X = cbox.X + 48; for (int i = 0; i < list.Count(); ++i) { Block block = list.ElementAt(i); if (cbox.Intersects(block.cbox) &&block.type == "moving"&&!block.inlist) { blocks.Add(block); block.inlist = true; } } } this.cbox.Width = blocks.Count * 48; this.cbox.X = x; checkcbox = cbox; }
/// <summary> /// Método que obtiene los datos de los periodos lectivos /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public void _ObtenerDatos() { _listaSemestre = _controladorSistema.obtenerSemestres(); if ((_listaSemestre != null) && (_listaSemestre.Count != 0)) { _ddlNombre.Items.Add("Seleccionar"); for (int i = 0; i < _listaSemestre.Count; i++) //guardar { _ddlNombre.Items.Add(_listaSemestre.ElementAt(i).NombreSemestre.ToString()); _ddlId.Items.Add(_listaSemestre.ElementAt(i).IdSemestre.ToString()); _ddlFechaIni.Items.Add(_listaSemestre.ElementAt(i).FechaInicio.ToString()); _ddlFechaFin.Items.Add(_listaSemestre.ElementAt(i).FechaFinal.ToString()); _ddlActivo.Items.Add(_listaSemestre.ElementAt(i).Activo.ToString()); } } else if (_listaSemestre == null) //hubo algun error { _imgMensaje.ImageUrl = "../Imagenes/Error.png"; _lblMensaje.Text = "Hubo un error al obtener los datos de los períodos lectivos en el sistema"; _imgMensaje.Visible = true; _lblMensaje.Visible = true; } else // no hay datos { _imgMensaje.ImageUrl = "../Imagenes/Advertencia.png"; _lblMensaje.Text = "No hay períodos lectivos registrados en el sistema"; _imgMensaje.Visible = true; _lblMensaje.Visible = true; } }
public SkillEffectName InsertSkillEffectName(string name, string heroName, Skill skill, List<string> skillEffectValues) { SkillEffectName skillEffectName; Skill completeSkill = SkillCreator.SelectByName(skill.Name); bool exists = checkIfSkillNameExists(name, completeSkill, completeSkill.Description, out skillEffectName); if (!exists) { skillEffectName.Name = name.Trim(); skillEffectName.SkillId = completeSkill.ID; skillEffectName.ValueLv1 = int.Parse(skillEffectValues.First()); skillEffectName.ValueLv2 = int.Parse(skillEffectValues.ElementAt(1)); skillEffectName.ValueLv3 = int.Parse(skillEffectValues.ElementAt(2)); skillEffectName.ValueLv4 = int.Parse(skillEffectValues.ElementAt(3)); skillEffectName.ValueScepter = int.Parse(skillEffectValues.Last()); using (Dota2Entities ctx = new Dota2Entities()) { try { skillEffectName = ctx.SkillEffectName.Add(skillEffectName); ctx.SaveChanges(); Console.WriteLine("Skill " + name + " Created"); } catch (Exception e) { throw e; } } } return skillEffectName; }
public SupportingComTerminalExpression(List<TokenReader> tokenList) { FillSupportComNounList(); FillSupportComVerbList(); this.State = null; this.TokenList = tokenList; for (int i = 0; i < tokenList.Count; i++) { for (int j = 0; j < supportComNounList.Count; j++) { if (tokenList.ElementAt(i).Token == supportComNounList.ElementAt(j)) { Noun = new NounScriptTerminalExpression(supportComNounList.ElementAt(j)); //State = Noun.Name; break; } } } for (int i = 0; i < tokenList.Count; i++) { for (int j = 0; j < supportComVerbList.Count; j++) { if (tokenList.ElementAt(i).Token == supportComVerbList.ElementAt(j)) { Verb = new VerbScriptCommandExpression(supportComVerbList.ElementAt(j)); //State = Verb.Name; break; } } } }
/// <summary> /// Parses csv /// </summary> /// <param name="data">csv data</param> /// <returns>Header object</returns> public static Header Parse(List<List<string>> data) { var root = new Header { Name = "Root", Depth = -1, From = 0, To = data.ElementAt(0).Count - 1, }; for (var i = 0; i < HeaderRowCount; i++) { var row = data.ElementAt(i); Header current = null; for (var j = 1; j < row.Count; j++) { var value = row[j]; if (!string.IsNullOrWhiteSpace(value)) { current = new Header { Name = value, Depth = i, From = j, To = j, Parent = Header.GetParent(root, i, j) }; current.Parent.Children.Add(current); } else if (current != null) { var parentOfCurrent = Header.GetParent(root, current.Depth, current.From); if (current.To < parentOfCurrent.To) { current.To++; } } } } return root; }
static int GetMax(int bottomBox, Dictionary<int, List<int>> map, List<int[]> original) { if (map.ContainsKey(bottomBox)) return map[bottomBox].Count; int[] box1 = original.ElementAt(bottomBox); int secondBottomBox = -1; int max = -1; for (int i = 0; i < original.Count; i++) { if (i == bottomBox) continue; int[] box2 = original.ElementAt(i); if (!(box1[0] > box2[0] && box1[1] > box2[1] && box1[2] > box2[2])) continue; int lastStack = GetMax(i, map, original); if (lastStack > max) { secondBottomBox = i; max = lastStack; } } List<int> stack = new List<int>(); if (secondBottomBox != -1) { stack = new List<int>(map[secondBottomBox]); } stack.Add(bottomBox); map.Add(bottomBox, stack); return stack.Count; }
public void populate(List<LabelEntryBase> lebList, List<LabelInfo> liItem, int iOffset) { foreach (LabelEntryBase lebItem in lebList) { if (lebItem.iRepeat == 1) { LabelEntry leNew = new LabelEntry(); leNew.copy(lebItem); leNew.fill(liItem.ElementAt(iOffset)); leEntries.Add(leNew); } else { for (int iX = iOffset; iX < (lebItem.iRepeat + iOffset) && iX < liItem.Count(); iX++) { LabelEntry leNew = new LabelEntry(); leNew.copy(lebItem); leNew.adjust(iX - iOffset); leNew.fill(liItem.ElementAt(iX)); leEntries.Add(leNew); } } } }
private void DrawChartPadron() { try { List<List<double>> cuentasValues = new List<List<double>>(ConsultaDTO.GetAVGActivos()); chartConsulta.Titles["titleChartPadron"].Text = ConfigurationManager.AppSettings["ChartPadronTitle"]; string[] xValues = { ConfigurationManager.AppSettings["ChartPadronLegendClave"], ConfigurationManager.AppSettings["ChartPadronLegendCuenta"], ConfigurationManager.AppSettings["ChartPadronLegendSinTamitar"] }; chartConsulta.Series["seriePadron"].Points.DataBindXY(xValues, cuentasValues.ElementAt(0)); chartConsulta.Series["seriePadron"].Points[0].Color = Color.Yellow; chartConsulta.Series["seriePadron"].Points[1].Color = Color.CadetBlue; chartConsulta.Series["seriePadron"].Points[2].Color = Color.DarkSalmon; chartConsulta.Series["seriePadron"].ChartType = SeriesChartType.Pie; chartConsulta.Series["seriePadron"]["PieLabelStyle"] = "Outside"; chartConsulta.Series["seriePadron"].Label = "#PERCENT{P2}"; chartConsulta.Series["seriePadron"].LegendText = "#VALX"; chartConsulta.ChartAreas["chartAreaPadron"].Area3DStyle.Enable3D = true; chartConsulta.Legends["legendPadron"].Enabled = true; SetLegendsChartPadron(cuentasValues.ElementAt(0), cuentasValues.ElementAt(1)); } catch (Exception ex) { LogWriter log = new LogWriter(); log.WriteLog(ex.Message, "DrawChartPadron", Path.GetFileName(Request.PhysicalPath)); throw ex; } }
private bool AreInOrder(List<int> numbers) { for (int i = 0; i < numbers.Count() - 1; i++) if (numbers.ElementAt(i) > numbers.ElementAt(i + 1)) return false; return true; }
public ActionResult Index() { List<Interlocutor> Interlocutors = new List<Interlocutor>(); using (CommonContext ctx = new CommonContext()) { List<MessageRel> mr = (from items in ctx.MessageRels where items.Receiver == User.Identity.Name select items).ToList<MessageRel>(); List<CustomUserInfo> users = new List<CustomUserInfo>(); foreach (MessageRel item in mr) { CustomUserInfo user = (from us in ctx.CustomUserInfos where us.UserName == item.Sender select us).Single<CustomUserInfo>(); if (user != null) users.Add(user); } for (int i = 0; i < mr.Count; i++) { Interlocutor inter = new Interlocutor(); inter.Unread = mr.ElementAt<MessageRel>(i).Unread; inter.Name = users.ElementAt<CustomUserInfo>(i).Nickname; inter.UserName = users.ElementAt<CustomUserInfo>(i).UserName; inter.Image = users.ElementAt<CustomUserInfo>(i).Image; Interlocutors.Add(inter); } } ViewBag.IsUnread = IsUnread(); return View(Interlocutors); }
static void Main(string[] args) { List<UInt64> num = new List<UInt64>(); List<UInt64> den = new List<UInt64>(); UInt64[] ret = new UInt64[1]; int num_inputs = Convert.ToInt32(Console.ReadLine()); for (int i = 0; i < num_inputs; i++) { string s = Console.ReadLine(); num.Add(Convert.ToUInt64(s.Split('/')[0])); den.Add(Convert.ToUInt64(s.Split('/')[1])); } for (int i = 0; i < num.Count() - 1; i++) { if (i == 0) { ret = addfrac(num.ElementAt(0), den.ElementAt(0), num.ElementAt(1), den.ElementAt(1)); } else { ret = addfrac(ret.ElementAt(0), ret.ElementAt(1), num.ElementAt(i + 1), den.ElementAt(i + 1)); } } Console.WriteLine(ret[0]+"/"+ret[1]); Console.ReadLine(); }
static void Main(string[] args) { int n = int.Parse(Console.ReadLine()); List<int> list = new List<int>(); bool hasResult = false; for(int i = 0; i < n; i++) { list.Add(int.Parse(Console.ReadLine())); } for(int i = 0; i < list.Count - 1; i++) { for (int j = i+1; j<list.Count; j++) { for(int k = 0; k<list.Count; k++) { int number1 = list.ElementAt(i); int number2 = list.ElementAt(j); int result = list.ElementAt(k); if(number1 * number1 + number2 * number2 == result*result) { hasResult = true; Console.WriteLine("{0}*{0} + {1}*{1} = {2}*{2}", number1, number2, result); } } } } if(!hasResult) { Console.WriteLine("No"); } }
private List<frmNvoMat> listeFrmNvoMat; // la liste des formulaires pour ajouter un nouveau materiel #endregion Fields #region Constructors /// <summary> /// Constructeur du module de saisie d'un prêt /// </summary> public frmSaisie() { InitializeComponent(); this.listeFrmNvoMat = new List<frmNvoMat>(); this.listeFrmNvlLicDuree = new List<frmNvlLicDuree>(); this.listeFrmNvlLicVersion = new List<frmNvlLicVersion>(); Mysql m = new Mysql(); //on instancie une liste de personnes List<Personne> lesP = new List<Personne>(); //on la remplie à partir de la base de données lesP = m.getLesPersonne(); //puis on ajoute chaque personne dans la liste (nom + prenom de la personne) for (int i = 0; i < lesP.Count; i++) { this.listBox1.Items.Add(lesP.ElementAt(i).getNomPersonne() + " " + lesP.ElementAt(i).getPrenomPersonne()); } this.grpBoxMateriel.Hide(); this.grpBoxLicDuree.Hide(); this.grpBoxLicVersion.Hide(); insertNewFrmMat(); insertNewFrmLicDuree(); insertNewFrmLicVersion(); }
// POST: /Analytics/ByProjectChart public ActionResult ByProjectChart(ByProjectViewModel model) { //projectDb.Projects.Where(x => x.IsParent.Equals(true)).GroupBy(y => y.City).Select(y => new MyViewModel{Name = y.Key}) List<Project> projList = new List<Project>(); findSubProjects(model.ProjectName, projList); /* from student in db.Students group student by student.EnrollmentDate into dateGroup */ List<string> projNameList = new List<string>(); List<double> projFundList = new List<double>(); for(int i=0; i < projList.Count; i++){ projNameList.Add(projList.ElementAt(i).Name + " (Rs." + projList.ElementAt(i).TotalAllocatedAmount + ")"); projFundList.Add(projList.ElementAt(i).TotalAllocatedAmount); } Project parent = projController.FindProjectByName(model.ProjectName); if (parent != null) { var remaining = parent.TotalAllocatedAmount - parent.TotalSpentAmount; projNameList.Add(model.ProjectName + " (Rs." + remaining + ")"); projFundList.Add(remaining); } var xValue = projNameList.ToArray(); var yValue = projFundList.ToArray(); ViewBag.xCol = xValue; ViewBag.yCol = yValue; return PartialView(); //ByProjectChart }
static void Main(string[] args) { String sentence = "This is a simple text and it counts how many words there are in here and how often they are used"; String[] words = sentence.Split(' '); Dictionary<String,int> dict=new Dictionary<String,int>(); List<String> keys=new List<String>(); for(int i=0;i<words.Length;i++) { if(dict.ContainsKey(words[i])) { int value; if(dict.TryGetValue(words[i],out value)) { dict.Remove(words[i]); value++; dict.Add(words[i], value); } } else { dict.Add(words[i], 1); keys.Add(words[i]); } } for(int i=0;i<keys.Count;i++) { int value; dict.TryGetValue(keys.ElementAt(i),out value); Console.WriteLine(string.Format("The word is {0} .And it is seen {1} times in the sentece !", keys.ElementAt(i), value)); } }
private bool checkWaveGesture(List<KinectDataPoint> queue, int stepSize) { int minPoints = stepSize * 4 + 1; for (int i = 0; i < queue.Count - minPoints; ++i) { KinectDataPoint p1 = queue.ElementAt(i); KinectDataPoint p4 = queue.ElementAt(i + (3 * stepSize)); if (p1.TimeStamp.AddMilliseconds(maxWaveTime) < p4.TimeStamp) { break; } KinectDataPoint p2 = queue.ElementAt(i + stepSize); KinectDataPoint p3 = queue.ElementAt(i + (2 * stepSize)); double dist1 = p1.CalcScreenDistance(p2); double dist2 = p2.CalcScreenDistance(p3); double dist3 = p3.CalcScreenDistance(p4); double gitterPosA = p1.CalcDistance3D(p3); double gitterPosB = p2.CalcDistance3D(p4); if (dist1 > IConsts.GWaveMinLength && dist2 > IConsts.GWaveMinLength && dist3 > IConsts.GWaveMinLength && gitterPosA < IConsts.GWaveMaxGitter && gitterPosB < IConsts.GWaveMaxGitter) { return true; } } return false; }
static void Main(string[] args) { int N; string input; BigInteger S = 0; List<BigInteger> sequence=new List<BigInteger>(); sequence.Add(0); sequence.Add(1); sequence.Add(1); Console.WriteLine("This program calculates the sum of the first N members of the sequence of Fibonacci"); do { Console.Write("N = "); input = Console.ReadLine(); } while (!int.TryParse(input, out N)); for (int i = 3; i < N; i++) { sequence.Add(sequence.ElementAt(i-1)+sequence.ElementAt(i-2)); } for (int i = 0; i < N; i++) { S += sequence.ElementAt(i); } Console.WriteLine("S = {0}",S); }
public DB_Manager(String _Database) { this.Database = _Database; this.connectionInfo = new List<string>(); this.connectionInfo.Add("localhost"); this.connectionInfo.Add("enricolu"); this.connectionInfo.Add("111platform!"); this.connectionInfo.Add(Database); string dbHost = connectionInfo.ElementAt<string>(0); string dbUser = connectionInfo.ElementAt<string>(1); string dbPass = connectionInfo.ElementAt<string>(2); string dbName = connectionInfo.ElementAt<string>(3); string connStr = "server=" + dbHost + ";uid=" + dbUser + ";pwd=" + dbPass + ";database=" + dbName; ;// +";CharSet=utf8_general_ci";// +";CharSet=utf8mb4"; RepositoryConnection = new MySqlConnection(connStr); // 連線到資料庫 try { RepositoryConnection.Open(); } catch (MySql.Data.MySqlClient.MySqlException ex) { RepositoryConnection.Close(); RepositoryConnection = null; Console.WriteLine("錯啦 " + ex.ToString()); } setting = new DB_setting(); }
private void CreateFilterMenu() { var obj = originalData?.ElementAt(0); foreach (var prop in obj.GetType().GetProperties()) { FilterMenuItem.Items.Add(new MenuItem { Header = prop.Name, Command = new RelayCommand(param => { var popup = new PromptWindow(); popup.lblUnos.Content = $"Insert {prop.Name}"; popup.Owner = Window.GetWindow(this); if (popup.ShowDialog() != true) { return; } var unos = popup.txtUnos.Text; filterMode = true; filteredData = originalData.Where(item => Equals(prop.GetValue(item), unos)).ToList(); currentPage = 2; CurrentPage = 1; }) }); } }
public void SetProperties(List <object> props) { FilePath = (string)props?.ElementAt(0) ?? ""; StartRow = (int?)props?.ElementAt(1) ?? 0; EndRow = (int?)props?.ElementAt(2) ?? -1; StartCol = (int?)props?.ElementAt(3) ?? 0; EndCol = (int?)props?.ElementAt(4) ?? -1; SheetIndex = (int?)props?.ElementAt(5) ?? 0; IsTable = (bool?)props?.ElementAt(6) ?? true; //throw new NotImplementedException(); }
public static Record AddRecordImage(Album album, ApplicationUser user, Group group, List <byte[]> images, string text) { //var album = user.GetAlbums(album_id).FirstOrDefault(); if (album == null) { return(null); } if (user == null) { return(null); } if (images == null || images.Count < 1) { return(null); } var img = new Image() { Data = images?.ElementAt(0), UserId = user.Id }; Record record = null; using (ApplicationDbContext db = new ApplicationDbContext()) { db.ImagesSocial.Add(img); db.SaveChanges(); if (group == null) { record = new Record() { AlbumId = album.Id, UserId = user.Id, Description = text } } ; else { record = new Record() { AlbumId = album.Id, GroupId = group.Id, Description = text } }; db.Record.Add(record); db.SaveChanges(); img.RecordId = record.Id; record.ImageId = img.Id; db.SaveChanges(); } return(record); }
private PulsarAction AddActions(List <PulsarAction> actionsList, PulsarAction.ActionType actionType) { PulsarAction pulsarAction = null; switch (actionType) { case PulsarAction.ActionType.Single: pulsarAction = actionsList?.ElementAt(0); break; case PulsarAction.ActionType.Parallel: pulsarAction = AddActionParallel(actionsList); break; case PulsarAction.ActionType.Sequence: pulsarAction = AddActionSequence(actionsList); break; } _actions.Add(pulsarAction); return(pulsarAction); }
public T this[int n] { get { return(_points.ElementAt(n)); } set { _points[n] = value; } }
public BetaSeriesException(List <Error> errors) : base($"BetaSeries Error : {errors?.ElementAt(0)?.Text} (Code : {errors?.ElementAt(0)?.Code})") { BetaSeriesErrors.AddRange(errors); }
private void OnCollisionEnter2D(Collision2D col) { //Aqui se cambia el color de la luz que emite la pelota. GetComponentInChildren <Light>().light.color = getRandomColor(); //emitter.Emit(5); //Andamos manejando los puntos de colision, que se usaran para checar los ejes. //El limite de puntos esta definido arriba. ballPoints.Add(transform.position); if (ballPoints.Count == maxCollisions) { //Esta variable es usada para checar cuantas veces colisionamos en el eje de las X int maxBouncesX = 0; //Esta variable es usada para checar cuantas veces colisionamos en el eje de las Y int maxBouncesY = 0; //Vamos a checar por cada punto que agregamos a nuestra lista de colisiones, //cuantas veces estamos en el mismo eje. foreach (Vector2 point in ballPoints) { if (point.x >= transform.position.x - collisionSensitivity && point.x <= transform.position.x + collisionSensitivity) { maxBouncesX += 1; } if (point.y >= transform.position.y - collisionSensitivity && point.y <= transform.position.y + collisionSensitivity) { maxBouncesY += 1; } } //Ahora se va a añadir fuerza dependiendo de el eje en el que estamos atorados. //En este caso, el de las X if (maxBouncesX == maxCollisions) { rigidbody2D.AddForce(new Vector2(1, 0)); } //Ahora se va a añadir fuerza dependiendo de el eje en el que estamos atorados. //En este caso, el de las Y if (maxBouncesY == maxCollisions) { rigidbody2D.AddForce(new Vector2(0, 1)); } //Ahora vamos a ahorrar espacio en la lista, recorriendo todos los elementos. //Siempre tiene que ser de 3 puntos de largo. if (ballPoints.Count > 3) { for (int i = 1; i < ballPoints.Count; i++) { //Aqui estamos recorriendo los elementos hacia atras. ballPoints.Insert(i - 1, ballPoints.ElementAt(i)); } //Se quita el ultimo elemento, puesto que ya recorrimos la lista. //Esto nos dejara añadir un nuevo punto de collision cuando pase el evento. ballPoints.RemoveAt(ballPoints.Count - 1); } } // Si se llega a collisionar con la paleta if (col.gameObject.tag == "Player") { // Se calcula en que parte de la paleta le pegamos. float x = hitFactor(transform.position, col.transform.position, ((BoxCollider2D)col.collider).size.x); // Ya que calculamos la direccion, vamos a normalizar el vector. Vector2 dir = new Vector2(x, 1).normalized; // Se le añade el valor de velocidad junto con la direccion. // Tambien se multiplica el valor delta de la aplicacion. rigidbody2D.velocity = dir * ballSpeed; } }
public void GetPokemon(string json) { progressBar1.Value = 0; flowLayoutPanelPokemon.Controls.Clear(); List <Tuple <string, string, string> > pokeInfo = new List <Tuple <string, string, string> >();//name, url of image, tag List <string> pokeAdded = new List <string>(); var result = JsonConvert.DeserializeObject <Pokemon_Location.RootObject>(json); int noEncounters = result.pokemon_encounters.Count; progressBar1.Maximum = noEncounters; for (int poke = 0; poke < noEncounters; poke++) { if (!pokeAdded.Contains(result.pokemon_encounters.ElementAt(poke).pokemon.name)) { string pokeTag = result.pokemon_encounters.ElementAt(poke).pokemon.name; pokeAdded.Add(pokeTag); string pokeJson = ApiRequest(Convert.ToString(result.pokemon_encounters.ElementAt(poke).pokemon.url)); var pokeData = JsonConvert.DeserializeObject <Pokemon_Details.RootObject>(pokeJson); string imageUrl = pokeData.sprites.front_default; string pokeName = ""; if (pokemonCache.ContainsKey(pokeTag)) { pokeName = pokemonCache[pokeTag]; } else { string pokeNameJson = ApiRequest(pokeData.species.url); var pokeSpeciesData = JsonConvert.DeserializeObject <Pokemon_Species.RootObject>(pokeNameJson); for (int language = 0; language < pokeSpeciesData.names.Count; language++) { if (pokeSpeciesData.names.ElementAt(language).language.name == "en") { pokeName = pokeSpeciesData.names.ElementAt(language).name; pokemonCache.Add(pokeTag, pokeName); language = pokeSpeciesData.names.Count;//end for loop } } } pokeInfo.Add(new Tuple <string, string, string>(pokeName, imageUrl, pokeTag)); } progressBar1.Value = poke + 1; } for (int i = 0; i < pokeInfo.Count; i++) { PokemonPicture pp = new PokemonPicture(); flowLayoutPanelPokemon.Controls.Add(pp); pp.SetName(pokeInfo.ElementAt(i).Item1); pp.SetPicture(pokeInfo.ElementAt(i).Item2); pp.SetTag(pokeInfo.ElementAt(i).Item3); pp.MouseClick += new MouseEventHandler(PokemonPicture_Click); pp.Controls[0].MouseClick += new MouseEventHandler(PokemonPicture_Click); pp.Controls[1].MouseClick += new MouseEventHandler(PokemonPicture_Click); if (pokedexIndex.ContainsKey(pokeInfo.ElementAt(i).Item3)) { if (pokedex.Contains(Convert.ToString(pokedexIndex[pokeInfo.ElementAt(i).Item3]))) { pp.Disable(); } } } }
private string WriteRow(XElement row, List <int> columnWidths, bool writeLineEnd = true) { var sb = new StringBuilder(); var columnsExpected = columnWidths.Count; var index = 0; var elementIndex = 0; var cells = row.Elements().Where(e => e.Name == "cell"); while (index < columnsExpected) { int colSpan = 1; try { XElement cell = cells.ElementAt(elementIndex); var colspanAttr = cell.Attributes().FirstOrDefault(a => a.Name == "colspan"); if (!int.TryParse(colspanAttr?.Value ?? "1", out colSpan)) { colSpan = 1; } int width = 0; for (int i = 0; i < colSpan; i++) { width += columnWidths.ElementAt(index + i); } var lineWidth = Convert.ToInt32(Math.Floor(DEFAULT_FONT_WIDTH_IN_DOTS * width)); var align = EvaluateAlignment(cell.Attribute("align"), "left"); var cellText = ""; if (cell.Elements().Count() == 0) { cellText = WritePaddedText(cell.Value, width, align, false); } else { var childElement = cell.Elements().First(); if (childElement.Name == "text") { cellText = WritePaddedText(childElement.Value, width, align, false); } else if (childElement.Name == "b") { cellText = WriteB(childElement.Value, width, align); } else if (childElement.Name == "line") { cellText = WriteLine(lineWidth); } else if (childElement.Name == "textline") { cellText = WriteTextLine(width, childElement.Attribute("character")?.Value ?? "-"); } } if (cellText.Length < width) { cellText = cellText.PadRight(width); } sb.Append(cellText); } catch (ArgumentOutOfRangeException ex) { Debug.WriteLine($"Error parsing template: {ex}"); break; } index += colSpan; elementIndex++; } // In order to give more flexibility to layout, don't assume a line end must // be inserted at the end of each row. if (writeLineEnd) { sb.Append(CR); } return(sb.ToString()); }
static public async Task OnTick() { if (camera != null && World.RenderingCamera == camera) { if (!Game.PlayerPed.IsInVehicle()) { ResetCamera(); } else if (modelHashes.Contains(Game.PlayerPed.CurrentVehicle.Model.Hash)) { if (heliScaleform.IsLoaded) { heliScaleform.CallFunction("SET_ALT_FOV_HEADING", Game.PlayerPed.CurrentVehicle.Position.Z, camera.FieldOfView, camera.Rotation.Z); heliScaleform.Render2D(); } camera.Rotation = new Vector3(0.0f, 0.0f, CitizenFX.Core.Game.PlayerPed.CurrentVehicle.Rotation.Z); // Toggle NV/Infrared if (ControlHelper.IsControlJustPressed(Settings.Controls["Helicopter.ToggleVisionMode"])) { switch (currentCameraMode) { case CameraMode.None: currentCameraMode = CameraMode.FLIR; break; case CameraMode.FLIR: currentCameraMode = CameraMode.Nightvision; break; case CameraMode.Nightvision: currentCameraMode = CameraMode.None; break; } Game.ThermalVision = cameraModeMap[currentCameraMode][0]; Game.Nightvision = cameraModeMap[currentCameraMode][1]; } // Change locked target // TODO: Only part left to test else if (ControlHelper.IsControlJustPressed(Settings.Controls["Helicopter.SwitchTarget"])) { try { if (currentLock == null || currentLock == playerList.Last()) { currentLock = playerList.First(); } else { currentLock = playerList.SkipWhile(p => p != currentLock).Skip(1).First(); } } catch (Exception ex) { Log.ToChat($"[HELICAM] {ex.GetType().ToString()} thrown"); } } // Change zoom else if (ControlHelper.IsControlJustPressed(Settings.Controls["Helicopter.ToggleZoom"])) { camera.FieldOfView = cameraZoom.ElementAt(currentCameraZoomIndex); currentCameraZoomIndex = (currentCameraZoomIndex + 1) % (cameraZoom.Count() - 1); } if (ControlHelper.IsControlJustPressed(Settings.Controls["Helicopter.ToggleCamera"])) { ResetCamera(); } } } else if (Game.PlayerPed.IsInVehicle() && modelHashes.Contains(Game.PlayerPed.CurrentVehicle.Model.Hash)) { if (ControlHelper.IsControlJustPressed(Settings.Controls["Helicopter.ToggleCamera"])) { camera = World.CreateCamera(Game.PlayerPed.CurrentVehicle.Position, Game.PlayerPed.CurrentVehicle.Rotation, 75f); camera.AttachTo(Game.PlayerPed.CurrentVehicle, cameraOffset); World.RenderingCamera = camera; Function.Call(Hash.SET_CAM_INHERIT_ROLL_VEHICLE, camera, true); heliScaleform = new Scaleform("HELI_CAM"); while (!heliScaleform.IsLoaded) { await BaseScript.Delay(0); } Function.Call(Hash.SET_TIMECYCLE_MODIFIER, "heliGunCam"); Function.Call(Hash.SET_TIMECYCLE_MODIFIER_STRENGTH, 0.3); heliScaleform.CallFunction("SET_CAM_LOGO", 1); } else if (ControlHelper.IsControlJustPressed(Settings.Controls["Helicopter.Rappel"])) { Log.ToChat("Trying to rappel"); Function.Call(Hash.TASK_RAPPEL_FROM_HELI, Game.PlayerPed.Handle, 0x41200000); } else if (ControlHelper.IsControlJustPressed(Settings.Controls["Helicopter.ToggleSearchLight"])) { Game.PlayerPed.CurrentVehicle.IsSearchLightOn = !Game.PlayerPed.CurrentVehicle.IsSearchLightOn; } } }
public void Export() { string path = HostingEnvironment.MapPath("/excel/DK/SuCoThietBi.xlsx"); FileInfo file = new FileInfo(path); using (ExcelPackage excelPackage = new ExcelPackage(file)) { ExcelWorkbook excelWorkbook = excelPackage.Workbook; ExcelWorksheet excelWorksheet = excelWorkbook.Worksheets.First(); using (QuangHanhManufacturingEntities db = new QuangHanhManufacturingEntities()) { var type = new[] { "month", "quarter", "year" }.Contains(Request["type"]) ? Request["type"] : "month"; if (int.TryParse(Request["year"], out int year)) { year = int.Parse(Request["year"]); } else { year = DateTime.Now.Year; } if (int.TryParse(Request["month"], out int month)) { month = int.Parse(Request["month"]); } else { month = DateTime.Now.Month; } if (int.TryParse(Request["quarter"], out int quarter)) { quarter = int.Parse(Request["quarter"]); } else { quarter = 1; } var sql = @"select d.department_id, department_name, (case when total is null then 0 else total end) as total, (case when diff is null then 0 else diff end) as diff from Department d left join (select department_id, COUNT(*) as total, SUM(DATEDIFF(SECOND, start_time, end_time)) as diff from Incident where year(start_time) = " + year; switch (type) { case "month": sql += " and month(start_time) = " + month; break; case "quarter": sql += " and month(start_time) between " + (quarter * 3 - 2) + " and " + (quarter * 3); break; default: break; } sql += @" group by department_id ) as i on d.department_id = i.department_id where d.department_type like N'%phân xưởng%'"; List <Report> content = db.Database.SqlQuery <Report>(sql).ToList(); for (int i = 3; i < content.Count + 3; i++) { excelWorksheet.Cells[i, 1].Value = content.ElementAt(i - 3).department_name; excelWorksheet.Cells[i, 2].Value = content.ElementAt(i - 3).total; excelWorksheet.Cells[i, 3].Value = content.ElementAt(i - 3).stringdiff(); } Response.Clear(); Response.AddHeader("content-disposition", "attachment; filename=LeadsExport.xlsx"); Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; Response.BinaryWrite(excelPackage.GetAsByteArray()); Response.End(); //excelPackage.SaveAs(new FileInfo(HostingEnvironment.MapPath(saveAsPath))); } } //return Json(new { success = true, location = saveAsPath }, JsonRequestBehavior.AllowGet); }
static void Main(string[] args) { //prendo i file json utili alla scansione delle sequenze allineate var path = Directory.GetCurrentDirectory(); // i file gff dell'annotazione genica sono stati convertiti in json tramite un tool recuperabile sul web var path1 = Path.Combine(Directory.GetCurrentDirectory(), "gene-annotation.json"); //il file json delle sequenze allineate si può recuperare rapidamente da Jalview tramite Output to textbox var path2 = Path.Combine(Directory.GetCurrentDirectory(), "alligned-sequences.json"); string file2 = File.ReadAllText(path1); //deserializzo il file dell'annotazione genica GenesList genesList = new GenesList(); genesList = JsonConvert.DeserializeObject <GenesList>(file2); string file3 = File.ReadAllText(path2); //deserializzo file di sequenze allineate SequencesList list = new SequencesList(); list = JsonConvert.DeserializeObject <SequencesList>(file3); //creo l'oggetto delle variazioni da stampare in output DifferenceOutput o = new DifferenceOutput(); o.DifferenceLists = new List <DifferenceList>(); Console.WriteLine("numero sequenze presenti: " + list.Seqs.Count); Sequence reference = new Sequence(); //trova la sequenza reference for (int i = 0; i < list.Seqs.Count; i++) { if (list.Seqs.ElementAt(i).Name == "hCoV-19/Wuhan/IPBCAMS-WH-01/2019|EPI_ISL_402123|2019-12-24/1-29899") { reference = list.Seqs.ElementAt(i); } else if (list.Seqs.ElementAt(i).Name == "NC_045512.2/1-29903") { reference = list.Seqs.ElementAt(i); } } //per ogni sequenza allineata calcola le differenze con la ref for (int i = 0; i < list.Seqs.Count; i++) { DifferenceList diffs = new DifferenceList(); diffs.Seq1 = reference; diffs.Seq2 = list.Seqs.ElementAt(i); //calcola le differenze tra ref e seq 2 DifferenceCalculator(diffs); //aggiunge le differenze tra le due sequenze alla lista di differenze globali o.DifferenceLists.Add(diffs); Console.WriteLine("measuring differences of sequence: " + i); if (diffs.Differences.Count > 0) { Console.WriteLine("La sequenza " + diffs.Seq2.Name + " possiede: " + diffs.Differences.Count + " variazioni rispetto alla ref"); for (int j = 0; j < diffs.Differences.Count; j++) { Console.WriteLine(diffs.Differences.ElementAt(j).Newletter + " al posto di " + diffs.Differences.ElementAt(j).Oldletter + " in posizione " + diffs.Differences.ElementAt(j).Position + " rispetto alla sequenza " + diffs.Seq1.Name + " che è la sequenza di REF"); } } } GenesList geneswithcds = new GenesList(); geneswithcds.geneslist = new List <Gene>(); //trova i geni con cds nel file gene-annotation for (int w = 0; w < genesList.geneslist.Count(); w++) { if (genesList.geneslist.ElementAt(w).type == "CDS") { geneswithcds.geneslist.Add(genesList.geneslist.ElementAt(w)); } } //crea la matrice matrix = new int[o.DifferenceLists.Count + 1, geneswithcds.geneslist.Count + 1]; //scrive i geni corrispondenti se presente il file gene-annotation if (path1 != null) { //per ogni lista di differenza tra sequenze for (int j = 1; j < o.DifferenceLists.Count; j++) { indice++; //per ogni differenza tra due sequenze for (int k = 0; k < o.DifferenceLists.ElementAt(j).Differences.Count; k++) { //per ogni gene presente nel file gene-annotation int cont = 0; for (int w = 0; w < geneswithcds.geneslist.Count(); w++) { if (geneswithcds.geneslist.ElementAt(w).type == "CDS") { //posizione globale d'inizio del gene int start = geneswithcds.geneslist.ElementAt(w).start; //posizione globale di fine del gene int end = geneswithcds.geneslist.ElementAt(w).end; //posizione globale della differenza tra due sequenze int position = o.DifferenceLists.ElementAt(j).Differences.ElementAt(k).Position; //posizione relativa all'interno del gene int relpos = position - start; //se la posizione rientra nel range del gene allora salvo il gene associato alla differenza if ((position >= start) && (position <= end)) { o.DifferenceLists.ElementAt(j).Differences.ElementAt(k).Gene = geneswithcds.geneslist.ElementAt(w).gene; o.DifferenceLists.ElementAt(j).Differences.ElementAt(k).Startcds = geneswithcds.geneslist.ElementAt(w).start; o.DifferenceLists.ElementAt(j).Differences.ElementAt(k).Endcds = geneswithcds.geneslist.ElementAt(w).end; int fine = (3 - ((end - start) % 3)); //posizione fine del gene if (fine == 3) { fine = 0; //controllo geni divisibili per 3 (altrimenti non determinabile) } String geneRef = o.DifferenceLists.ElementAt(j).Seq1.Seq.Substring(start, end - start + fine); o.DifferenceLists.ElementAt(j).Differences.ElementAt(k).Genseq = geneRef; String geneCurSeq = o.DifferenceLists.ElementAt(j).Seq2.Seq.Substring(start, end - start + fine); List <Codon> oldcodons = new List <Codon>(); List <Codon> newcodons = new List <Codon>(); //divido il gene in triplette e le inserisco in una lista for (int t = 0; t < end - start + fine; t += 3) { Codon old = new Codon(); Codon nuovo = new Codon(); old.Triplet = geneRef[t].ToString() + geneRef[t + 1] + geneRef[t + 2]; //calcolo l'amminoacido associato alla vecchia tripletta old.Aminoacid = getAminoacid(old.Triplet); old.Start = t + 1; old.End = t + 3; oldcodons.Add(old); nuovo.Triplet = geneCurSeq[t].ToString() + geneCurSeq[t + 1] + geneCurSeq[t + 2]; //calcolo l'amminoacido associato alla nuova tripletta nuovo.Aminoacid = getAminoacid(nuovo.Triplet); //t+1 perché parte da 0 mentre nel file le sequenze partono da 1 nuovo.Start = t + 1; nuovo.End = t + +3; newcodons.Add(nuovo); //vengono recuperati gli amminoacidi per la posizione corrente (ogni 3 basi) } // prendo la tripletta della reference associata alla differenza for (int r = 0; r < oldcodons.Count; r++) { if (relpos >= oldcodons.ElementAt(r).Start&& relpos <= oldcodons.ElementAt(r).End) { o.DifferenceLists.ElementAt(j).Differences.ElementAt(k).Oldcodon = oldcodons.ElementAt(r); } } //prendo la tripletta della seconda sequenza associata alla differenza for (int s = 0; s < newcodons.Count; s++) { if (relpos >= newcodons.ElementAt(s).Start&& relpos <= newcodons.ElementAt(s).End) { o.DifferenceLists.ElementAt(j).Differences.ElementAt(k).Newcodon = newcodons.ElementAt(s); if (o.DifferenceLists.ElementAt(j).Differences.ElementAt(k).Oldcodon.Aminoacid != o.DifferenceLists.ElementAt(j).Differences.ElementAt(k).Newcodon.Aminoacid) { //inserisce 1 nella matrice quando trova una tripletta mutata matrix[indice, cont] = 1; Console.WriteLine(o.DifferenceLists.ElementAt(j).Differences.ElementAt(k).Newcodon.Aminoacid + " al posto di " + o.DifferenceLists.ElementAt(j).Differences.ElementAt(k).Oldcodon.Aminoacid + " nella sequenza " + o.DifferenceLists.ElementAt(j).Seq2.Name + " in posizione " + o.DifferenceLists.ElementAt(j).Differences.ElementAt(k).Position); } } } } } cont++; } Console.WriteLine("writing genes part: " + j); } } } //costruisce la matrice createMatrix(o, geneswithcds); //serializzo l'oggetto con le differenze string diffJSON = JsonConvert.SerializeObject(o); var path3 = Path.Combine(Directory.GetCurrentDirectory(), "differences.json"); System.IO.File.WriteAllText(path3, diffJSON); }
static void Menu() { Console.Clear(); Console.ForegroundColor = ConsoleColor.Cyan; Console.WriteLine("\t _ _ _ _ ____ _ \r\n\t | \\ | (_) |_ _ __ ___ / ___|_ __ __ _ ___| | ___ __ \r\n\t | \\| | | __| '__/ _ \\ | | | '__/ _` |/ __| |/ / '__|\r\n\t | |\\ | | |_| | | (_) | | |___| | | (_| | (__| <| | \r\n\t |_| \\_|_|\\__|_| \\___/ \\____|_| \\__,_|\\___|_|\\_\\_| \r\n\t By Sheepy and Technic \r\n"); Console.WriteLine(); Console.ForegroundColor = ConsoleColor.White; Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("[1] Generate Nitro Codes"); Console.WriteLine("[2] Check Nitro Codes"); Console.ForegroundColor = ConsoleColor.White; Console.Write("# "); int selection = Convert.ToInt32(Console.ReadLine()); if (selection == 1) { Console.Write("Enter amount of codes: "); int code_count = Convert.ToInt32(Console.ReadLine()); List <string> generated_codes = Generate.generate(code_count); Console.Write("Save Codes as: "); string filename = Console.ReadLine(); if (!filename.Contains(".txt")) { filename += ".txt"; } try { using (TextWriter tw = new StreamWriter(filename)) { foreach (String s in generated_codes) { tw.WriteLine(s); } } Console.WriteLine("Codes saved as " + filename); } catch (Exception e) { Console.WriteLine(e.Message); Console.ReadLine(); return; } } else if (selection == 2) { Console.Write("Enter the file with the codes: "); string filename = Console.ReadLine(); if (!filename.Contains(".txt")) { filename += ".txt"; } try { foreach (string line in File.ReadLines(filename)) { Codes.Add(line.Replace("\n", "")); } } catch (Exception e) { Console.WriteLine(e.Message); Console.ReadLine(); return; } Console.Write("Enter thread count: "); int thread_count = Convert.ToInt32(Console.ReadLine()); Console.Write("Enter the file with the Proxies: "); string proxyfile = Console.ReadLine(); if (!proxyfile.Contains(".txt")) { proxyfile += ".txt"; } Console.Write("Enter proxy type (https/socks4/socks5): "); string proxyType = Console.ReadLine(); if (proxyType.ToLower() == "https") { proxytype = ProxyType.HTTP; } else if (proxyType.ToLower() == "socks4") { proxytype = ProxyType.Socks4; } else { proxytype = ProxyType.Socks5; } List <Thread> threads = new List <Thread>(); int i = 0; Console.Write("Start at line : "); i = Convert.ToInt32(Console.ReadLine()); var watch = System.Diagnostics.Stopwatch.StartNew(); for (int l = 0; l < thread_count; l++)//SETTINGS { Thread t = new Thread(delegate() { while (i != Codes.Count() - 1) { string combo; lock (_lock) { combo = Codes.ElementAt(i); i++; } //Console.WriteLine("Checking " + combo); bool ok = false; while (!ok) { if (Proxies.Count() < thread_count) { Proxies = Load(proxyfile); } try { string proxyaddy = Proxies.ElementAt(rnd.Next(0, Proxies.Count() - 1)); ok = Checkcode(combo, proxyaddy); } catch (Exception e) { //Console.WriteLine(e.Message); } Console.Title = "Nitro Cracker by Sheepy and Technic | Checked " + Checked_C + "/" + Codes.Count() + " CPM [" + CPM + "]"; } long elapsedMs = watch.ElapsedMilliseconds; //if (Last_200_times.Count() < 200) // Last_200_times.Add(elapsedMs); //else //{ // Last_200_times.RemoveAt(0); // Last_200_times.Add(elapsedMs); //} CPM = (int)(Checked_C * 60000 / elapsedMs); if (Proxies.Count() < thread_count) { Proxies = Load(proxyfile); } try { } catch (Exception e) { Console.WriteLine(e.Message); } Console.Title = "Nitro Cracker by Sheepy and Technic | Checked " + Checked_C + "/" + Codes.Count() + " CPM [" + CPM + "]"; } }); t.Start(); threads.Add(t); Thread.Sleep(100); } foreach (Thread thread in threads.ToList()) { thread.Join(); threads.Remove(thread); } } }
/* [Output("Roller")] * public OutArgument<string> Roller { get; set; } * * [Output("Licens")] * public OutArgument<string> Licens { get; set; }*/ public void Execute(IServiceProvider serviceProvider) { // Obtain the execution context from the service provider. IPluginExecutionContext context = (IPluginExecutionContext) serviceProvider.GetService(typeof(IPluginExecutionContext));; // Obtain the organization service reference. IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService (typeof(IOrganizationServiceFactory)); IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId); var SystemUser = service.Retrieve(context.PrimaryEntityName, context.PrimaryEntityId, new ColumnSet(true)); // make query for roles var query = new QueryExpression(); query.EntityName = "role"; query.ColumnSet = new ColumnSet(true); // link entity - fra rolle til rolle relation LinkEntity role = new LinkEntity(); role.LinkFromEntityName = "role"; role.LinkFromAttributeName = "roleid"; role.LinkToEntityName = "systemuserroles"; role.LinkToAttributeName = "roleid"; // fra rolle relation til bruger LinkEntity userRoles = new LinkEntity(); userRoles.LinkFromEntityName = "systemuserroles"; userRoles.LinkFromAttributeName = "systemuserid"; userRoles.LinkToEntityName = "systemuser"; userRoles.LinkToAttributeName = "systemuserid"; // lav condition til query ConditionExpression conditionExpression = new ConditionExpression(); conditionExpression.AttributeName = "systemuserid"; conditionExpression.Operator = ConditionOperator.Equal; conditionExpression.Values.Add(SystemUser.Id); userRoles.LinkCriteria = new FilterExpression(); userRoles.LinkCriteria.Conditions.Add(conditionExpression); // link entiterne sammen role.LinkEntities.Add(userRoles); query.LinkEntities.Add(role); // definer regler! var sales = new List <string> { "Lead", "Opportunity", "Goal", "Contract", "Quote", "Order", "Invoice", "Competitor", "Campaign", "List", "cdi_" }; // CLICKDIMENSION // få alle roller fra user var UserRoles = service.RetrieveMultiple(query).Entities; List <string> allRolesList = new List <string>(); foreach (var Role in UserRoles) { allRolesList.AddRange(getMasterRole(Role.GetAttributeValue <string>("name"), service, true)); } // få alle roller fra team var TeamRoles = GetRolesFromTeam(SystemUser, service); foreach (var teamRole in TeamRoles) { allRolesList.AddRange(getMasterRole(teamRole, service, false)); } // fjern dupletter var allRolesListDistinct = allRolesList.Distinct(); var allRolesListDistinctList = allRolesListDistinct.ToList(); // returner en streng. var returnString = new StringBuilder(); var salesString = new StringBuilder(); var customEntitiesString = new StringBuilder(); var salesCounter = 0; var customEntityCounter = 0; var customEntities = new List <string>(); var salesEntities = new List <string>(); string[] seperator = { "_" }; // tjek om der er roller der matcher med sales -> stor licens! foreach (var privilege in allRolesListDistinctList) { for (int i = 0; i < sales.Count; i++) { var salesSplit = privilege.Split(seperator, StringSplitOptions.RemoveEmptyEntries); var salesLastMember = salesSplit.Length - 1; var salesName = salesSplit.GetValue(salesLastMember).ToString(); // "SalesProcess" bliver ekskluderet - det er en adgang til BPF if (privilege.Contains(sales.ElementAt(i)) && !privilege.Contains("SalesProcess") && !salesEntities.Contains(salesName)) { salesEntities.Add(salesName); salesCounter = salesCounter + 1; salesString.AppendLine(privilege); } } if ((privilege.Contains("sdu_") || privilege.Contains("mp_") || privilege.Contains("nn_") || privilege.Contains("alumne_")) && !privilege.Contains("bpf_")) { var entitySplit = privilege.Split(seperator, StringSplitOptions.RemoveEmptyEntries); var entityLastMember = entitySplit.Length - 1; var entityName = entitySplit.GetValue(entityLastMember).ToString(); if (!customEntities.Contains(entityName)) { customEntities.Add(entityName); customEntityCounter = 1 + customEntityCounter; customEntitiesString.AppendLine(privilege); } else { continue; } } } Entity systemUser = new Entity("systemuser"); systemUser.Id = SystemUser.Id; systemUser["sdu_aktivtjek"] = CheckLastLoginDate(service, SystemUser.Id); if (salesCounter > 0 || customEntityCounter > 15) { systemUser["sdu_rolletype"] = "Sales"; } else { systemUser["sdu_rolletype"] = "Team Member"; } returnString.AppendLine("- SALES: " + salesCounter.ToString()); returnString.AppendLine("- Custom Entities: " + customEntityCounter.ToString()); returnString.AppendLine(""); returnString.AppendLine("Sales: "); returnString.AppendLine(salesString.ToString()); returnString.AppendLine(""); returnString.AppendLine("Custom Entities: "); returnString.AppendLine(customEntitiesString.ToString()); systemUser["sdu_rettigheder"] = returnString.ToString(); service.Update(systemUser); }
void BallsNextStep() { if (gameOver) { return; } if (_listCellEmpty.Count != 0) { _listCellEmpty.Clear(); } ForMyFor(mcWhatToDo.SelectEmptyCells); if (_listCellEmpty.Count == 0) { gameOver = true;; } _listColorNext.Clear(); int r; int i; { r = _glRand.Next(0, _countColorBalls); _listColorNext.Add((BallColor)r); i = 1; while (i != _countNextBalls) { r = _glRand.Next(0, _countColorBalls); if (!_listColorNext.Contains((BallColor)r)) { _listColorNext.Add((BallColor)r); i++; } } } { //if (_listBallsNext.Count != 0) { _listBallsNext.Clear(); } r = _glRand.Next(0, _listCellEmpty.Count - 1); _listBallsNext.Add(_listCellEmpty.ElementAt(r)); i = 1; while (i != _countNextBalls) { r = _glRand.Next(0, _listCellEmpty.Count - 1); if (!_listBallsNext.Contains(_listCellEmpty.ElementAt(r))) { _listBallsNext.Add(_listCellEmpty.ElementAt(r)); i++; } } _listCellEmpty.Clear(); _NBallOne = _listBallsNext[0]; _NBallTwo = _listBallsNext[1]; _NBallThree = _listBallsNext[2]; } { i = 0; foreach (var item in _listBallsNext) { _grid[(int)item.Y, (int)item.X]._cellBall._BallSetLittleHW(); _grid[(int)item.Y, (int)item.X]._cellCurrentColor = _listColorNext[i]; _grid[(int)item.Y, (int)item.X]._cellBall._BallChangeColor(_listColorNext[i]); if (i == 0) { _MW.BallNextColor1.Fill = _grid[(int)item.Y, (int)item.X]._cellBall.Ball.Fill; } if (i == 1) { _MW.BallNextColor2.Fill = _grid[(int)item.Y, (int)item.X]._cellBall.Ball.Fill; } if (i == 2) { _MW.BallNextColor3.Fill = _grid[(int)item.Y, (int)item.X]._cellBall.Ball.Fill; } i++; } } _ballsCount += 3; }
public IReproductores Buscar(int indice) { return(lista.ElementAt(indice)); }
public override async System.Threading.Tasks.Task ExecuteAsync(List <string> command, List <BaseMessage> originMessage, MessageSourceType sourceType, UserInfo qq, Group group, GroupMember member) { var fromQQ = 0L; var toGroup = 0L; //var message = ""; if (sourceType != MessageSourceType.Group) { return; } var sourceMessageId = (originMessage?.FirstOrDefault() as SourceMessage)?.Id ?? default; var messages = new List <BaseMessage>(); messages.Add(new QuoteMessage(toGroup, fromQQ, sourceMessageId)); fromQQ = member.QQ; toGroup = member.GroupNumber; var permit = member.PermitType; if (originMessage.Count <= 2) { if (command[0].Equals("on", StringComparison.CurrentCultureIgnoreCase)) { if (permit == PermitType.None) { MessageManager.SendTextMessage(MessageSourceType.Group, "只有群主或管理员才有权限开启色图鉴定功能", fromQQ, toGroup); return; } UpdateGroupHentaiCheckConfig(toGroup, true); MessageManager.SendTextMessage(MessageSourceType.Group, "色图鉴定已开启", fromQQ, toGroup); return; } else if (command[0].Equals("off", StringComparison.CurrentCultureIgnoreCase)) { if (permit == PermitType.None) { MessageManager.SendTextMessage(MessageSourceType.Group, "只有群主或管理员才有权限关闭色图鉴定功能", fromQQ, toGroup); return; } UpdateGroupHentaiCheckConfig(toGroup, false); MessageManager.SendTextMessage(MessageSourceType.Group, "色图鉴定已关闭", fromQQ, toGroup); return; } else if (!GroupHentaiCheckConfig.TryGetValue(toGroup, out var config)) { MessageManager.SendTextMessage(MessageSourceType.Group, "当前群尚未色图鉴定功能", fromQQ, toGroup); return; } else { messages.Add(new TextMessage("图呢?")); MessageManager.SendMessage(sourceType, messages, fromQQ, toGroup); return; } } else { if (!(originMessage?.ElementAt(2) is ImageMessage im)) { messages.Add(new TextMessage("图呢?")); MessageManager.SendMessage(sourceType, messages, fromQQ, toGroup); return; } var imageUrl = im.Url; if (string.IsNullOrWhiteSpace(imageUrl)) { MessageManager.SendTextMessage(MessageSourceType.Group, "图片上传失败惹", fromQQ, toGroup); return; } var client = new RestClient(); client.Timeout = -1; var imageDownloadRequest = new RestRequest(imageUrl, Method.GET); var imgRes = await client.ExecuteAsync(imageDownloadRequest); if (!imgRes.IsSuccessful) { MessageManager.SendTextMessage(sourceType, "请求失败了QAQ", fromQQ, toGroup); return; } var savedPath = Path.Combine(Config.TempPath, Guid.NewGuid() + ".png"); var uploadRequest = new RestRequest("https://checkimage.querydata.org/api", Method.POST) { AlwaysMultipartFormData = true }; uploadRequest.AddFileBytes("image", imgRes.RawBytes, savedPath, contentType: imgRes.ContentType); var res = await client.ExecuteAsync(uploadRequest); if (!res.IsSuccessful) { MessageManager.SendTextMessage(sourceType, "请求失败了QAQ", fromQQ, toGroup); return; } var strContent = res.Content; var jsonRes = Newtonsoft.Json.JsonConvert.DeserializeAnonymousType(strContent, new List <HentaiCheckModel>()); if (jsonRes == null || !jsonRes.Any()) { MessageManager.SendTextMessage(sourceType, "请求失败了QAQ", fromQQ, toGroup); return; } var messageText = "没鉴定出来><"; var result = jsonRes.OrderByDescending(p => p.Probability).FirstOrDefault(); switch (result?.ClassName) { case "Drawing": case "Neutral": messageText = "这不是挺健全的嘛"; break; case "Hentai": messageText = "色疯辣!"; break; case "Sexy": messageText = "我超,太烧啦!"; break; case "P**n": messageText = "你完了,我这就叫狗管理来抓你"; break; } messages.Add(new TextMessage(messageText)); MessageManager.SendMessage(sourceType, messages, fromQQ, toGroup); } }
private static void InitialiserDatas() { ListeAuteurs.Add(new Auteur("GROUSSARD", "Thierry")); ListeAuteurs.Add(new Auteur("GABILLAUD", "Jérôme")); ListeAuteurs.Add(new Auteur("HUGON", "Jérôme")); ListeAuteurs.Add(new Auteur("ALESSANDRI", "Olivier")); ListeAuteurs.Add(new Auteur("de QUAJOUX", "Benoit")); ListeLivres.Add(new Livre(1, "C# 4", "Les fondamentaux du langage", ListeAuteurs.ElementAt(0), 533)); ListeLivres.Add(new Livre(2, "VB.NET", "Les fondamentaux du langage", ListeAuteurs.ElementAt(0), 539)); ListeLivres.Add(new Livre(3, "SQL Server 2008", "SQL, Transact SQL", ListeAuteurs.ElementAt(1), 311)); ListeLivres.Add(new Livre(4, "ASP.NET 4.0 et C#", "Sous visual studio 2010", ListeAuteurs.ElementAt(3), 544)); ListeLivres.Add(new Livre(5, "C# 4", "Développez des applications windows avec visual studio 2010", ListeAuteurs.ElementAt(2), 452)); ListeLivres.Add(new Livre(6, "Java 7", "les fondamentaux du langage", ListeAuteurs.ElementAt(0), 416)); ListeLivres.Add(new Livre(7, "SQL et Algèbre relationnelle", "Notions de base", ListeAuteurs.ElementAt(1), 216)); ListeAuteurs.ElementAt(0).addFacture(new Facture(3500, ListeAuteurs.ElementAt(0))); ListeAuteurs.ElementAt(0).addFacture(new Facture(3200, ListeAuteurs.ElementAt(0))); ListeAuteurs.ElementAt(1).addFacture(new Facture(4000, ListeAuteurs.ElementAt(1))); ListeAuteurs.ElementAt(2).addFacture(new Facture(4200, ListeAuteurs.ElementAt(2))); ListeAuteurs.ElementAt(3).addFacture(new Facture(3700, ListeAuteurs.ElementAt(3))); }
static string Pivot() { var matrix = new List <List <string> >(); var answer = new StringBuilder(); int pCol, pRow; foreach (var r in Clipboard.GetText().Split('\n')) { var temp = new List <string>(); foreach (var k in r.Split('\t')) { temp.Add(k); } matrix.Add(temp); } Console.WriteLine("Enter pivot position: "); var s = Console.ReadLine().Split(' '); pRow = int.Parse(s[0]); //Row of pivot pCol = int.Parse(s[1]); //Column of pivot var pivot = matrix.ElementAt(pRow).ElementAt(pCol); //Obtains pivot number //Iterate through rest of matrix for (int i = 0; i < matrix.Count; i++) { for (int j = 0; j < matrix[i].Count; j++) { if (i != pRow && j != pCol) { matrix[i][j] = Pivotear(pivot, matrix[i][j], matrix[pRow][j], matrix[i][pCol]); } } } //Iterates through row of pivot and divides by pivot var pivotRow = matrix.ElementAt(pRow); for (int i = 0; i < pivotRow.Count; i++) { pivotRow[i] = Operar(pivotRow[i], pivot, '/'); } //Column of pivot (except row of pivot) is set to 0 for (int i = 0; i < matrix.Count; i++) { for (int j = 0; j < matrix[i].Count; j++) { if (j == pCol && i != pRow) { matrix[i][j] = "0"; } } } foreach (var row in matrix) { for (int i = 0; i < row.Count; i++) { answer.Append(row[i].ToString()); answer.Append(i == row.Count - 1 ? "\n" : "\t"); } } return(answer.ToString()); }
public SM_ISelectable GetFirstSelected() { return(_selected.Count == 0 ? null : _selected.ElementAt(0)); }
public static Task GenerateXLSRegistrationIsValid(List <RegistrationInterview> registrationInterviews, string filePath) { return(Task.Run(() => { using (ExcelPackage pck = new ExcelPackage()) { //Create the worksheet ExcelWorksheet ws = pck.Workbook.Worksheets.Add(DateTime.Now.Date.ToString()); ws.Cells[2, 1].Value = "DANH SÁCH ỨNG VIÊN CÓ HỒ SƠ HỢP LỆ SAU KHI ĐÃ RÀ XOÁT"; ws.Cells["A2:I2"].Merge = true; ws.Cells[3, 1].Value = registrationInterviews.ElementAt(0).ManagementUnit.FullName; ws.Cells["A3:I3"].Merge = true; ws.Cells[4, 1].Value = "Tính tới ngày " + DateTime.Now.Day + "/" + DateTime.Now.Month + "/" + DateTime.Now.Year; ws.Cells["A4:I4"].Merge = true; ws.Cells[6, 1].Value = "STT"; ws.Cells[6, 2].Value = "HỌ VÀ TÊN LÓT"; ws.Cells[6, 3].Value = "TÊN"; ws.Cells[6, 4].Value = "NGÀY SINH"; ws.Cells[6, 5].Value = "GIỚI TÍNH"; ws.Cells[6, 6].Value = "SỐ CMND"; ws.Cells[6, 7].Value = "NƠI Ở HIỆN NAY"; ws.Cells[6, 8].Value = "HÔ KHẨU THƯỞNG TRÚ"; ws.Cells[6, 9].Value = "SỐ ĐIỆN THOẠI"; ws.Cells[6, 10].Value = "EMAIL"; ws.Cells[6, 11].Value = "TRƯỜNG ĐÀO TẠO"; ws.Cells[6, 12].Value = "TRƯỜNG NÀY Ở"; ws.Cells[6, 13].Value = "TỐT NGHIỆP"; ws.Cells[6, 14].Value = "HỆ ĐÀO TẠO"; ws.Cells[6, 15].Value = "NĂM TỐT NGHIỆP"; ws.Cells[6, 16].Value = "KIỂU ĐÀO TẠO"; ws.Cells[6, 17].Value = "ĐIỂM TB"; ws.Cells[6, 18].Value = "ĐIỂM ĐỒ ÁN"; ws.Cells[6, 19].Value = "CHỨNG CHỈ NVSP"; ws.Cells[6, 20].Value = "MÔN ĐĂNG KÍ"; ws.Cells[6, 21].Value = "BẬC"; ws.Cells[6, 22].Value = "TIN HỌC"; ws.Cells[6, 23].Value = "NGOẠI NGỮ"; ws.Cells[6, 24].Value = "LÀM VIỆC TRONG NGÀNH"; ws.Cells[6, 25].Value = "NĂM VÀO NGÀNH"; ws.Cells[6, 26].Value = "MÃ NGẠCH"; ws.Cells[6, 27].Value = "HỆ SỐ LƯƠNG"; ws.Cells[6, 28].Value = "MỐC NÂNG LƯƠNG LẦN SAU"; ws.Cells[6, 29].Value = "NGƯỜI RA XOÁT"; for (int i = 0; i < registrationInterviews.Count(); i++) { ws.Cells[i + 7, 1].Value = i + 1; ws.Cells[i + 7, 2].Value = registrationInterviews.ElementAt(i).CandidateLastName; ws.Cells[i + 7, 3].Value = registrationInterviews.ElementAt(i).CandidateFirstName; ws.Cells[i + 7, 4].Value = registrationInterviews.ElementAt(i).DOB.Value.Day + "/" + registrationInterviews.ElementAt(i).DOB.Value.Month + "/" + registrationInterviews.ElementAt(i).DOB.Value.Year; ws.Cells[i + 7, 5].Value = registrationInterviews.ElementAt(i).IsMale == true ? "Nam" : "Nữ"; ws.Cells[i + 7, 6].Value = registrationInterviews.ElementAt(i).IdentifyCard; ws.Cells[i + 7, 7].Value = registrationInterviews.ElementAt(i).CurrentLivingAddress.HouseNumber + "," + registrationInterviews.ElementAt(i).CurrentLivingAddress.Ward.Type + " " + registrationInterviews.ElementAt(i).CurrentLivingAddress.Ward.Name + ", " + registrationInterviews.ElementAt(i).CurrentLivingAddress.Ward.District.Type + " " + registrationInterviews.ElementAt(i).CurrentLivingAddress.Ward.District.Name; ws.Cells[i + 7, 8].Value = registrationInterviews.ElementAt(i).HouseHold.HouseNumber + "," + registrationInterviews.ElementAt(i).HouseHold.Ward.Type + " " + registrationInterviews.ElementAt(i).HouseHold.Ward.Name + ", " + registrationInterviews.ElementAt(i).HouseHold.Ward.District.Type + " " + registrationInterviews.ElementAt(i).HouseHold.Ward.District.Name + ", " + registrationInterviews.ElementAt(i).HouseHold.Ward.District.Province.Type + " " + registrationInterviews.ElementAt(i).HouseHold.Ward.District.Province.Name; ws.Cells[i + 7, 9].Value = registrationInterviews.ElementAt(i).PhoneNumber; ws.Cells[i + 7, 10].Value = registrationInterviews.ElementAt(i).Email; ws.Cells[i + 7, 11].Value = registrationInterviews.ElementAt(i).UniversityName; ws.Cells[i + 7, 12].Value = registrationInterviews.ElementAt(i).Province.Type + " " + registrationInterviews.ElementAt(i).Province.Name; ws.Cells[i + 7, 13].Value = registrationInterviews.ElementAt(i).GraduationClassfication.Name; ws.Cells[i + 7, 14].Value = registrationInterviews.ElementAt(i).TrainningCategory.Name; ws.Cells[i + 7, 15].Value = registrationInterviews.ElementAt(i).GraduatedAtYear; ws.Cells[i + 7, 16].Value = registrationInterviews.ElementAt(i).IsNienChe == true ? "Niên chế" : "Tín chỉ"; ws.Cells[i + 7, 17].Value = registrationInterviews.ElementAt(i).GPA; ws.Cells[i + 7, 18].Value = registrationInterviews.ElementAt(i).CaptionProjectPoint; ws.Cells[i + 7, 19].Value = registrationInterviews.ElementAt(i).IsHadNghiepVuSupham == true ? "Đã có" : "Chưa có"; ws.Cells[i + 7, 20].Value = registrationInterviews.ElementAt(i).Subject.PositionInterview.Name + " " + registrationInterviews.ElementAt(i).Subject.Name; ws.Cells[i + 7, 21].Value = registrationInterviews.ElementAt(i).SchoolDegree.Notation; ws.Cells[i + 7, 22].Value = registrationInterviews.ElementAt(i).InfomationTechnologyDegree.Name; ws.Cells[i + 7, 23].Value = registrationInterviews.ElementAt(i).ForeignLanguageCertification.Name; ws.Cells[i + 7, 24].Value = registrationInterviews.ElementAt(i).StatusWorikingInEducation.Name; ws.Cells[i + 7, 25].Value = registrationInterviews.ElementAt(i).NamVaoNghanh; ws.Cells[i + 7, 26].Value = registrationInterviews.ElementAt(i).MaNgach; ws.Cells[i + 7, 27].Value = registrationInterviews.ElementAt(i).HeSoLuong; ws.Cells[i + 7, 28].Value = registrationInterviews.ElementAt(i).MocNangLuongLansau; ws.Cells[i + 7, 29].Value = registrationInterviews.ElementAt(i).Account1.LastName + " " + registrationInterviews.ElementAt(i).Account1.FirstName; } using (ExcelRange rng = ws.Cells["A2:I2"]) { rng.Style.Font.Bold = true; rng.Style.Font.Size = 18; rng.Style.HorizontalAlignment = ExcelHorizontalAlignment.Center; rng.Style.Font.Color.SetColor(Color.Red); } using (ExcelRange rng = ws.Cells["A3:I3"]) { rng.Style.Font.Bold = true; rng.Style.Font.Size = 14; rng.Style.HorizontalAlignment = ExcelHorizontalAlignment.Center; rng.Style.Font.Color.SetColor(Color.Red); } using (ExcelRange rng = ws.Cells["A4:I4"]) { rng.Style.Font.Bold = true; rng.Style.Font.Size = 14; rng.Style.HorizontalAlignment = ExcelHorizontalAlignment.Center; rng.Style.Font.Color.SetColor(Color.Red); } using (ExcelRange rng = ws.Cells["A6:AC6"]) { rng.Style.Font.Bold = true; rng.Style.Fill.PatternType = ExcelFillStyle.Solid; //Set Pattern for the background to Solid rng.Style.Fill.BackgroundColor.SetColor(Color.SkyBlue); //Set color to blue rng.Style.Font.Color.SetColor(Color.Black); rng.AutoFitColumns(); } pck.SaveAs(new FileInfo(filePath)); } })); }
private void btnIniciar_Click(object sender, EventArgs e) { if (!trd.IsAlive) { if (rbManual.Checked) { string strMsg = ""; string[] tempo = mskTempo.Text.Split(':'); if (string.IsNullOrWhiteSpace(tempo[0]) && string.IsNullOrWhiteSpace(tempo[1])) { strMsg += "Informe o Tempo!\n"; } if (string.IsNullOrWhiteSpace(cbbPotencia.SelectedItem.ToString())) { strMsg += "Informe a potência!"; } if (string.IsNullOrEmpty(strMsg)) { trd.Abort(); cbbPotencia.ValueMember = "10"; Aquecimento(mskTempo.Text, Convert.ToInt32(cbbPotencia.Text), "."); } else { MessageBox.Show(strMsg + ""); } } else { if (rbProgramas.Checked) { if (cbbProgramas.Text != "") { Aquecimento(mskTempoPrograma.Text, Convert.ToInt32(cbbPotenciaPrograma.Text), listPrograma.ElementAt(cbbProgramas.SelectedIndex).Carcter.ToString()); } else { MessageBox.Show("Escolha um programa!", "Micro-ondas", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } } else { int cont = 0; if (mskTempoArq.Text != "") { Aquecimento(mskTempoArq.Text, Convert.ToInt32(cbbPotenciaArq.Text), charAtual); cont = 1; } else { MessageBox.Show("Escolha um arquivo válido!", "Micro-ondas", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } } } } else { pausado = false; } }
public async Task GetOwnRecipientsQueryHandler_CorrectlyMapsTargets() { // Arrange GetOwnRecipientsQuery.Handler handler = new GetOwnRecipientsQuery.Handler(_unitOfWorkMock.Object, _userProviderMock.Object); // Act List <RecipientResource> recipients = (await handler.Handle(new GetOwnRecipientsQuery())).ToList(); // Assert Assert.Equal(3, recipients.Count); Assert.Null(recipients.ElementAt(0).TargetGroup); Assert.NotNull(recipients.ElementAt(0).TargetUser); Assert.Equal(2, recipients.ElementAt(0).TargetUser.UserId); Assert.Equal("user2", recipients.ElementAt(0).TargetUser.UserName); Assert.Null(recipients.ElementAt(1).TargetGroup); Assert.NotNull(recipients.ElementAt(1).TargetUser); Assert.Equal(3, recipients.ElementAt(1).TargetUser.UserId); Assert.Equal("user3", recipients.ElementAt(1).TargetUser.UserName); Assert.Null(recipients.ElementAt(2).TargetUser); Assert.NotNull(recipients.ElementAt(2).TargetGroup); Assert.Equal(1, recipients.ElementAt(2).TargetGroup.GroupId); Assert.Equal("group1", recipients.ElementAt(2).TargetGroup.Name); }
private void selectitem(object sender, SelectionChangedEventArgs e) { MessageBoxResult result = MessageBox.Show("Recruit This Employee?", "Are you sure?", MessageBoxButton.YesNo, MessageBoxImage.Question, MessageBoxResult.No); switch (result) { case MessageBoxResult.Yes: MessageBox.Show("Employee Recruited!"); DataTable dt5 = new DataTable(); dt5 = connect.executeQuery("select * from employee where division = '" + candidatedivision.ElementAt(datagrid.SelectedIndex).ToString() + "'"); if (candidatedivision.ElementAt(datagrid.SelectedIndex).Equals("Teller")) { connect.executeUpdate("insert into employee values ('T00" + (dt5.Rows.Count + 1) + "','" + candidatename.ElementAt(datagrid.SelectedIndex) + "','Teller','password',4000000,0,0,'Active')"); } else if (candidatedivision.ElementAt(datagrid.SelectedIndex).Equals("Customer Service")) { connect.executeUpdate("insert into employee values ('CS00" + (dt5.Rows.Count + 1) + "','" + candidatename.ElementAt(datagrid.SelectedIndex) + "','Customer Service','password',5000000,0,0,'Active')"); } else if (candidatedivision.ElementAt(datagrid.SelectedIndex).Equals("Human Resource")) { connect.executeUpdate("insert into employee values ('HRM00" + (dt5.Rows.Count + 1) + "','" + candidatename.ElementAt(datagrid.SelectedIndex) + "','Human Resource','password',6000000,0,0,'Active')"); } else if (candidatedivision.ElementAt(datagrid.SelectedIndex).Equals("Security & Maintenance")) { connect.executeUpdate("insert into employee values ('SM00" + (dt5.Rows.Count + 1) + "','" + candidatename.ElementAt(datagrid.SelectedIndex) + "','Security & Maintenance','password',5500000,0,0,'Active')"); } else if (candidatedivision.ElementAt(datagrid.SelectedIndex).Equals("Finance")) { connect.executeUpdate("insert into employee values ('F00" + (dt5.Rows.Count + 1) + "','" + candidatename.ElementAt(datagrid.SelectedIndex) + "','Finance','password',5000000,0,0,'Active')"); } else if (candidatedivision.ElementAt(datagrid.SelectedIndex).Equals("Manager")) { connect.executeUpdate("insert into employee values ('M00" + (dt5.Rows.Count + 1) + "','" + candidatename.ElementAt(datagrid.SelectedIndex) + "','Manager','password',20000000,0,0,'Active')"); } connect.executeUpdate("delete from candidate where id = '" + candidateid.ElementAt(datagrid.SelectedIndex) + "'"); Window a = new HRMManageEmployee(employee); a.Show(); this.Close(); break; case MessageBoxResult.No: break; } }
private void GetFormData() { string maNgonNgu = lstSourceNgonNgu.ElementAt(cmbNgonNgu.SelectedIndex).KeywordStrings.First(); string maDonVi = string.Empty; string tenPhongGiaoDich = string.Empty; if (lstSourcePhongGD_Select.Count > 0) { maDonVi = lstSourcePhongGD_Select.ElementAt(cmbPhongGD.SelectedIndex).KeywordStrings.First(); tenPhongGiaoDich = lstSourcePhongGD_Select.ElementAt(cmbPhongGD.SelectedIndex).DisplayName; } else { maDonVi = lstSourceChiNhanh.ElementAt(cmbChiNhanh.SelectedIndex).KeywordStrings.First(); } DateTime ngayBaoCao = new DateTime(); if (raddtNgayBaoCao.Value is DateTime) { ngayBaoCao = (DateTime)raddtNgayBaoCao.Value; } DateTime tuNgay = new DateTime(); if (raddtTuNgay.Value is DateTime) { tuNgay = (DateTime)raddtTuNgay.Value; } DateTime denNgay = new DateTime(); if (raddtDenNgay.Value is DateTime) { denNgay = (DateTime)raddtDenNgay.Value; } string maLoaiTien = lstSourceLoaiTien.ElementAt(cmbLoaiTien.SelectedIndex).KeywordStrings.First(); List <string> lstDanhSach = new List <string>(); string soTaiKhoan = ""; if (grSoTienGuiDS.SelectedItems.Count > 0) { for (int i = 0; i < grSoTienGuiDS.SelectedItems.Count; i++) { //DataRowView dr = (DataRowView)grSoTienGuiDS.SelectedItems[i]; DataRow dr = (DataRow)grSoTienGuiDS.SelectedItems[i]; lstDanhSach.Add(dr["SO_TAI_KHOAN"].ToString()); soTaiKhoan = soTaiKhoan + dr["SO_TAI_KHOAN"].ToString() + "#"; } } if (soTaiKhoan != "") { soTaiKhoan = soTaiKhoan.Substring(0, soTaiKhoan.Length - 1); } string maDinhDang = lstSourceDinhDang.ElementAt(cmbDinhDang.SelectedIndex).KeywordStrings.First(); string maChiNhanh = lstSourceChiNhanh.ElementAt(cmbChiNhanh.SelectedIndex).KeywordStrings.First(); string tenChiNhanh = lstSourceChiNhanh.ElementAt(cmbChiNhanh.SelectedIndex).DisplayName; //Lấy giá trị MaChiNhanh = maChiNhanh; TenChiNhanh = tenChiNhanh; MaPhongGiaoDich = maDonVi; TenPhongGiaoDich = tenPhongGiaoDich; TuNgay = tuNgay.ToString("yyyyMMdd"); DenNgay = denNgay.ToString("yyyyMMdd"); NgayBaoCao = ngayBaoCao.ToString("yyyyMMdd"); MaLoaiTien = maLoaiTien; MaNgonNgu = maNgonNgu; MaDinhDang = maDinhDang; MaNguoiLap = Presentation.Process.Common.ClientInformation.TenDangNhap; TenNguoiLap = Presentation.Process.Common.ClientInformation.HoTen; SoTaiKhoan = soTaiKhoan; }
private void Dibuja_Tabla(List <Libro> librosAPintarList) { for (int i = 0; i < librosAPintarList.Count() + 1; i++) { tablaLibros.Rows.Add(new TableRow()); for (int k = 0; k < 6; k++) { tablaLibros.Rows[i].Cells.Add(new TableCell()); if (i == 0) { switch (k) { case 0: tablaLibros.Rows[i].Cells[k].Text = "Referencia"; break; case 1: tablaLibros.Rows[i].Cells[k].Text = "Titulo"; break; case 2: tablaLibros.Rows[i].Cells[k].Text = "Autor"; break; case 3: tablaLibros.Rows[i].Cells[k].Text = "Unidades"; break; case 4: tablaLibros.Rows[i].Cells[k].Text = "Precio"; break; } } else { Libro libro = librosAPintarList.ElementAt(i - 1); switch (k) { case 0: tablaLibros.Rows[i].Cells[k].Text = libro.isbn10.ToString(); break; case 1: tablaLibros.Rows[i].Cells[k].Text = libro.titulo; break; case 2: tablaLibros.Rows[i].Cells[k].Text = libro.autor; break; case 3: tablaLibros.Rows[i].Cells[k].Text = recuperaCantidad(libro.isbn10.ToString()).ToString(); break; case 4: tablaLibros.Rows[i].Cells[k].Text = libro.precio.ToString() + "euros"; break; } } } } //pintarTotales(); }
public static double CompareMobisigFeatureBased(string aFolder, int aNrOfTrainingSamples, ref StreamWriter aSWriter) { List <Signature> lSignatures = SignatureFileUtils.GetAllSignaturesFromFolder(aFolder); List <Signature> lTemplate = lSignatures.Skip(20).Take(aNrOfTrainingSamples).ToList(); List <Signature> lOriginalSignatures = lSignatures.Skip(20 + aNrOfTrainingSamples).Take(25 - aNrOfTrainingSamples).ToList(); List <Signature> lImpostorSignatures = lSignatures.Take(15).ToList(); //retrieve feature set List <SignatureFeatures> lFeaturesTemplate = new List <SignatureFeatures>(); List <SignatureFeatures> lFeaturesOriginal = new List <SignatureFeatures>(); List <SignatureFeatures> lFeaturesImpostor = new List <SignatureFeatures>(); for (int i = 0; i < lTemplate.Count; ++i) { var lElement = lTemplate.ElementAt(i); var lNewElement = SignatureUtils.SignatureUtils.CalculateCharacteristics(lElement); lNewElement = SignatureUtils.SignatureUtils.StandardizeSignature(lNewElement); lTemplate.RemoveAt(i); lTemplate.Insert(i, lNewElement); lFeaturesTemplate.Add(FeatureCalculator.CalculateFeatures(lElement)); } for (int i = 0; i < lOriginalSignatures.Count; ++i) { var lElement = lOriginalSignatures.ElementAt(i); var lNewElement = SignatureUtils.SignatureUtils.CalculateCharacteristics(lElement); lNewElement = SignatureUtils.SignatureUtils.StandardizeSignature(lNewElement); lOriginalSignatures.RemoveAt(i); lOriginalSignatures.Insert(i, lNewElement); lFeaturesOriginal.Add(FeatureCalculator.CalculateFeatures(lElement)); } for (int i = 0; i < lImpostorSignatures.Count; ++i) { var lElement = lImpostorSignatures.ElementAt(i); var lNewElement = SignatureUtils.SignatureUtils.CalculateCharacteristics(lElement); lNewElement = SignatureUtils.SignatureUtils.StandardizeSignature(lNewElement); lImpostorSignatures.RemoveAt(i); lImpostorSignatures.Insert(i, lNewElement); lFeaturesImpostor.Add(FeatureCalculator.CalculateFeatures(lElement)); } EuclideanDetector lEuclideanDetector = new EuclideanDetector(lFeaturesTemplate); //aDetector.CalculateScores() List <double> lOriginalScores = lEuclideanDetector.CompareToTemplate(lFeaturesOriginal); List <double> lImpostorScores = lEuclideanDetector.CompareToTemplate(lFeaturesImpostor); ErrorCalculation lError = ErrorCalculationFactory.GetDScoreErrorCalculator(); lError.CalculateErrors(lOriginalScores, lImpostorScores, 100); //var lFARList = lError.GetFARList(); //var lFRRList = lError.GetFRRList(); //var lTresholdList = lError.GetThresholdList(); //for(int i = 0; i < lFARList.Count; ++i) //{ // aSWriter.WriteLine(lFARList.ElementAt(i) + "," + lFRRList.ElementAt(i) + ", " + lTresholdList.ElementAt(i)); //} aSWriter.WriteLine(lError.GetERR()); return(lError.GetERR()); }
public World generateWorld(Texture2D floorTex, List <EnemyConfig> enemyConfigs, int tileSize, int difficulty) { rooms = new List <Room>(); spawns = new List <SpawnFlag>(); int enemyDifficultyCap = difficulty / 5; int healthPotions = difficulty / 30; List <EnemyConfig> availableEnemies = enemyConfigs.FindAll(x => x.difficulty <= difficulty); List <EnemyConfig> chosenEnemies = new List <EnemyConfig>(); while (enemyDifficultyCap > 0 && availableEnemies.Count > 0) { EnemyConfig choosenEnemy = availableEnemies[random.Next(0, availableEnemies.Count)]; chosenEnemies.Add(choosenEnemy); enemyDifficultyCap -= choosenEnemy.difficulty; availableEnemies = enemyConfigs.FindAll(x => x.difficulty <= difficulty); } maxRooms = (int)(difficulty / 5) + 3; int width = (maxRooms * maxRoomWidth * 2) + (maxRooms * maxHallLength); int height = (maxRooms * maxRoomHeight * 2) + (maxRooms * maxHallLength); newWorld = new World(floorTex, tileSize); tileMap = new int[height, width]; collisionMap = new bool[height, width]; //remainingEnemies = numEnemies; for (int i = 0; i < tileMap.GetLength(0); i++) { tileMap[i, 0] = -1; tileMap[i, width - 1] = -1; } for (int i = 0; i < tileMap.GetLength(1); i++) { tileMap[0, i] = -1; tileMap[height - 1, i] = -1; } Rectangle validWorldSpace = new Rectangle(1, 1, width - 1, height - 1); Point coors = chooseRoomSite(tileMap, validWorldSpace); Room firstRoom = placeRoom(tileMap, collisionMap, coors.X, coors.Y); firstRoom.startRoom = true; firstRoom.isOptional = false; firstRoom.depth = 0; Point spawnPos = new Point(coors.X, coors.Y); SpawnFlag playerSpawn = new SpawnFlag("player", spawnPos, (int)SPAWNTYPES.ACTOR); spawns.Add(playerSpawn); newWorld.setSpawnTile(spawnPos); //tileMap[coors.Y, coors.X] = 14; rooms.Add(firstRoom); int roomIndex = 0; int numRooms = 1; Room curRoom = rooms.ElementAt(roomIndex); while (numRooms < maxRooms) { int[] hallCoors; //Console.WriteLine("Current room index" + roomIndex); //Console.WriteLine("Room#" + numRooms); //if(numRooms > 1) // hallCoors = chooseHallSite(tileMap, curRoom.dimensions); //else hallCoors = chooseHallSite(tileMap, curRoom.dimensions); if (hallCoors[0] == -1) { //Console.WriteLine("Couldn't find a good hall site"); if (roomIndex == 0) { roomIndex = random.Next(0, rooms.Count); } else { roomIndex--; } curRoom = rooms.ElementAt(roomIndex); } else { if (random.Next(0, 4) == 0) { Room splitRoom = placeRoom(tileMap, collisionMap, hallCoors[4], hallCoors[5]); splitRoom.hallEntrance = new Point(hallCoors[0], hallCoors[1]); splitRoom.parent = curRoom; curRoom.children.Add(splitRoom); splitRoom.depth = splitRoom.parent.depth + 1; splitRoom.isOptional = true; rooms.Add(splitRoom); } else { Room tempRoom = curRoom; curRoom = placeRoom(tileMap, collisionMap, hallCoors[4], hallCoors[5]); curRoom.hallEntrance = new Point(hallCoors[0], hallCoors[1]); curRoom.roomCenter = new Point(hallCoors[0], hallCoors[1]); curRoom.parent = tempRoom; tempRoom.children.Add(curRoom); curRoom.depth = curRoom.parent.depth + 1; curRoom.isOptional = true; rooms.Add(curRoom); //curRoom.parentRoom = rooms.ElementAt(roomIndex); } placeHall(tileMap, collisionMap, hallCoors[0], hallCoors[1], hallCoors[2], hallCoors[3]); roomIndex++; numRooms++; } } Room room = rooms.ElementAt(rooms.Count - 1); tileMap[room.dimensions.Y + room.dimensions.Height / 2, room.dimensions.X + room.dimensions.Width / 2] = 15; room.isLeaf = true; room = room.parent; while (room.parent != null) { room.isOptional = false; room.isLeaf = true; room = room.parent; } foreach (EnemyConfig tempConfig in chosenEnemies) { room = rooms.ElementAt(random.Next(1, rooms.Count - 2)); placeEnemy(collisionMap, room, spawns, tempConfig.enemyClass); } List <Room> possibleLockedRooms = rooms.FindAll(x => !x.isOptional && !x.startRoom && x.depth > 1); if (possibleLockedRooms.Count > 0) { Room lockedRoom = possibleLockedRooms[random.Next(0, possibleLockedRooms.Count - 1)]; //tileMap[lockedRoom.hallEntrance.Y, lockedRoom.hallEntrance.X] = 15; SpawnFlag lockedDoorFlag; if (floorTex.Name == "hellTiles") { lockedDoorFlag = new SpawnFlag("Big_Door", lockedRoom.hallEntrance, (int)SPAWNTYPES.DOOR); } else { lockedDoorFlag = new SpawnFlag("Generic_Door", lockedRoom.hallEntrance, (int)SPAWNTYPES.DOOR); } spawns.Add(lockedDoorFlag); List <Room> possibleKeyRooms = new List <Room>(rooms); possibleKeyRooms = partitionPastRoom(possibleKeyRooms, lockedRoom); Room keyRoom; if (possibleKeyRooms.FindAll(x => x.isLeaf).Count > 0) { List <Room> keyRooms = possibleKeyRooms.FindAll(x => x.isLeaf); keyRoom = keyRooms[random.Next(0, keyRooms.Count - 1)]; } else { keyRoom = possibleKeyRooms[random.Next(0, possibleKeyRooms.Count - 1)]; } if (keyRoom.spawns.Count > 0) { SpawnFlag tempEnemyConfig = keyRoom.spawns[random.Next(0, keyRoom.spawns.Count - 1)]; tempEnemyConfig.hasKey = true; } else { placeKey(collisionMap, keyRoom); } } List <Room> possiblePotionRooms = rooms; while (healthPotions > 0) { Room potionRoom = possiblePotionRooms[random.Next(0, possiblePotionRooms.Count - 1)]; placePotion(collisionMap, potionRoom, spawns, "Weak_Potion"); healthPotions--; } //Set room list here newWorld.setTileMap(tileMap, collisionMap); newWorld.setSpawns(spawns); return(newWorld); }
private static void DeleteUser(List <Object[]> TableField) { db = RefreshDB(); db.UserTBs.Remove(db.UserTBs.FirstOrDefault(Item => Item.UserID == TableField.ElementAt(0)[0].ToString())); db.SaveChangesAsync(); }
public Student getStudent(int rollNo) => students?.ElementAt(rollNo);