public static void HeavyChurn(Simulator sim, int time) { sim.Complete(); Dictionary<Node, Node> volatile_nodes = new Dictionary<Node, Node>(); int fifteen_mins = (int) ((new TimeSpan(0, 15, 0)).Ticks / TimeSpan.TicksPerMillisecond); int max = sim.StartingNetworkSize * 2; Random rand = new Random(); DateTime end = DateTime.UtcNow.AddSeconds(time); while(end > DateTime.UtcNow) { SimpleTimer.RunSteps(fifteen_mins); List<Node> to_remove = new List<Node>(); foreach(Node node in volatile_nodes.Keys) { double prob = rand.NextDouble(); if(prob <= .7) { continue; } // This is due to some bug that I can no longer remember // sim.RemoveNode(node, prob > .9); sim.RemoveNode(node, true); to_remove.Add(node); } foreach(Node node in to_remove) { volatile_nodes.Remove(node); } Console.WriteLine("Removed: {0} Nodes" , to_remove.Count); while(volatile_nodes.Count < max) { Node node = sim.AddNode(); volatile_nodes.Add(node, node); } } }
public override string Execute(Dictionary<string, string> parameters) { string path = parameters["templatepath"]; if (string.IsNullOrEmpty(path)) return ""; string filename = parameters["templatefile"]; if (string.IsNullOrEmpty(filename)) return ""; try { string ModelProvider = parameters["dataprovider"]; string ModelConstructor = parameters["datasource"]; var ModelParameters = new Dictionary<string, string>(parameters); ModelParameters.Remove("templatepath"); ModelParameters.Remove("templatefile"); ModelParameters.Remove("dataprovider"); ModelParameters.Remove("datasource"); var Model = DataSourceProvider.Instance(ModelProvider).Invoke(ModelConstructor, ModelParameters); return TemplateProvider.FindProviderAndExecute(path, filename, Dump(Model)); } catch (Exception ex) { return "Error : " + path + filename + " " + ex.Message; } }
/// <summary> /// Calculates an intercept course for "imminent threat" pirates /// </summary> /// <param name="currentItem"></param> /// <param name="dmID"></param> public override void Generate(T_Item currentItem, String dmID) { if (currentItem.Parameters.ThreatType == T_ThreatType.Nonimminent) return; Dictionary<T_Move, T_Reveal> dict = GetActionsAsDictionary(currentItem.Action); //This dictionary is a copy Dictionary<T_Move, T_Reveal> newDict = new Dictionary<T_Move,T_Reveal>(dict); //Find that pirate T_Move move = null; T_Reveal reveal = null; foreach (T_Move key in dict.Keys) { if (dict[key] == null) { if (ddd.GetSeamateObject(key.ID).Owner == "Pirate DM") { move = key; reveal = dict[key]; newDict.Remove(key); break; } } else { if (dict[key].Owner == "Pirate DM") { move = key; reveal = dict[key]; newDict.Remove(key); break; } } } if (move == null) return; move = SetToInterceptCourse(move, reveal, newDict); //Reset the pirate's move and reveal in dictionary. newDict[move] = reveal; //Translate dictionary back into action array. currentItem.Action = GetActionsFromDictionary(newDict); }
public static TermVector GetCentroid(IEnumerable<TermVector> vectors) { Dictionary<string, long> sum = new Dictionary<string, long>(); int vectorCount = 0; // Sum the lengths of dimensions foreach (TermVector vector in vectors) { vectorCount++; foreach (string term in vector.Terms) { long count = 0; sum.TryGetValue(term, out count); sum.Remove(term); sum.Add(term, count + vector.GetDimensionLength(term)); } } // Divide the dimensions Dictionary<string, int> centroid = new Dictionary<string, int>(); foreach (KeyValuePair<string, long> dimension in sum) { centroid.Add(dimension.Key, (int)(dimension.Value / vectorCount)); } return new TermVector(centroid); }
static GumpDefTranslator() { m_Translations = new Dictionary<int, Tuple<int, int>>(); StreamReader gumpDefFile = new StreamReader(FileManager.GetFile("gump.def")); string line; while ((line = gumpDefFile.ReadLine()) != null) { line = line.Trim(); if (line.Length <= 0) continue; if (line[0] == '#') continue; string[] defs = line.Replace('\t', ' ').Split(' '); if (defs.Length != 3) continue; int inGump = int.Parse(defs[0]); int outGump = int.Parse(defs[1].Replace("{", string.Empty).Replace("}", string.Empty)); int outHue = int.Parse(defs[2]); if (m_Translations.ContainsKey(inGump)) m_Translations.Remove(inGump); m_Translations.Add(inGump, new Tuple<int, int>(outGump, outHue)); } gumpDefFile.Close(); }
public bool PosTest2() { bool retVal = true; // Add your scenario description here TestLibrary.TestFramework.BeginScenario("PosTest2: Verify method IDictionaryRemove when the specified key is not exist."); try { IDictionary dictionary = new Dictionary<string, string>(); dictionary.Remove("txt"); if (dictionary.Contains("txt") == true) { TestLibrary.TestFramework.LogError("002.1", "Method IDictionary.GetEnumerator Err ."); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; }
private IDictionary<string, IList<Brief>> GetDataByGroupYear() { IDictionary<string, IList<Brief>> result = new Dictionary<string, IList<Brief>>(); SetConditions(string.Empty); m_Conditions.Add("Status", "1"); IList<Brief> dataList = m_FTISService.GetBriefList(m_Conditions); if (dataList != null && dataList.Count() > 0) { foreach (Brief data in dataList) { string key = data.AYear.Trim(); IList<Brief> groupDataList = new List<Brief>(); if (result.ContainsKey(key)) { groupDataList = result[key]; result.Remove(key); } groupDataList.Add(data); result.Add(key, groupDataList); } } return result; }
public static Dictionary<string, object> Dictionary(string[] keys, object[] values) { var table = new Dictionary<string, object>(); values = (object[]) values[0]; for (int i = 0; i < keys.Length; i++) { string name = keys[i].ToLowerInvariant(); object entry = i < values.Length ? values[i] : null; if (entry == null) { if (table.ContainsKey(name)) table.Remove(name); } else { if (table.ContainsKey(name)) table[name] = entry; else table.Add(name, entry); } } return table; }
public static List<GameObject> findMovableTiles(GameObject tile, int maxDist, Dictionary<terrainType,int> moveDict) { List<GameObject> openList = new List<GameObject>(); List<GameObject> closedList = new List<GameObject>(); List<GameObject> result = new List<GameObject>(); Dictionary <GameObject, int> gScore = new Dictionary<GameObject, int>(); GameObject currentNode; openList.Add(tile); result.Add(tile); gScore.Add (tile,0); while(openList.Count > 0){ currentNode = openList[0]; foreach(GameObject hex in currentNode.GetComponent<MapHex>().neighborList){ int tempG = (gScore[currentNode]+moveDict[hex.GetComponent<MapHex>().getTerrain()]); if(!openList.Contains(hex)&&!closedList.Contains(hex)&&tempG<=maxDist){ gScore.Add (hex,tempG); openList.Add (hex); } else if(tempG<gScore[hex]&&gScore.ContainsKey(hex)){ gScore.Remove (hex); gScore.Add (hex,tempG); } } closedList.Add(currentNode); openList.Remove(currentNode); if(gScore[currentNode]<=maxDist)result.Add(currentNode); } return result; }
void Update() { var remove_candidates = new Dictionary<ulong, Text>(name_dict_); // 削除候補辞書 var player_gos = GameObject.FindGameObjectsWithTag("Player"); // タグPlayerでリストアップ if (player_gos != null) { foreach (var player_go in player_gos) { var player = player_go.GetComponent<Player>(); if (player.sharedNod == null) continue; ulong id = player.sharedNod.getGlobalId(); // IDを取得 Text text; if (name_dict_.ContainsKey(id)) { // すでに存在していた text = name_dict_[id]; // 取得 remove_candidates.Remove(id); // 削除候補から消す } else { // 存在していなかった var go = Instantiate(namePrefab_) as GameObject; // 生成 text = go.GetComponent<Text>(); // 取得 go.transform.SetParent(canvas_); // 親を指定 name_dict_[id] = text; // 辞書に登録 } text.text = player.name_; // テキストに名前を入れる var screenPos = Camera.main.WorldToScreenPoint(player_go.transform.position); // 2D位置を取得 text.transform.position = screenPos; // 設定 } } // 消えたものを削除 foreach (KeyValuePair<ulong, Text> pair in remove_candidates) { name_dict_.Remove(pair.Key); // 辞書から削除 Destroy(pair.Value.gameObject); // オブジェクト破棄 } }
/* Find first character which is not repetitve in string * if string has length n, it may need n*n time O(n). * Let's find a better algorithm * First, make Hash table that saves the number of character appears in string * for each char * if, not saved value for the char, save 1 * else, value++; * Second, lookup character * for each char * if, the number of appears = 1, return char * else, 1 not exists, return null */ public static char FindFirstChar(string str) { Dictionary<char,int> table = new Dictionary<char, int>(); int length = str.Length; char c; int i; for (i = 0; i< length; i++) { c = str[i]; if (table.ContainsKey (c)) { int temp = table [c]; table.Remove (c); table.Add (c, temp+1); } else { table.Add (c, 1); } } for ( i = 0; i<length; i++) { c = str[i]; if (table [c] == 1) { return c; } } char Null = '\0'; return Null; }
public bool PosTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest2: The key to be remove is a custom class"); try { IDictionary iDictionary = new Dictionary<object,object>(); MyClass mc = new MyClass(); int value = TestLibrary.Generator.GetInt32(-55); iDictionary.Add(mc, value); iDictionary.Remove(mc); if (iDictionary.Contains(mc)) { TestLibrary.TestFramework.LogError("003", "The result is not the value as expected "); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("004", "Unexpected exception: " + e); retVal = false; } return retVal; }
public void WriteRuleRequestRecordLog(Dictionary<string, string> FailedTestResult) { System.IO.StreamWriter logStream = this.CreateTestResultFile(this.Site.Properties["Conformance_Response_Data_Path"], ".log"); if (logStream == null) return; try { IDictionaryEnumerator ruleRequestRecord = ((ConformanceDataService)dataService).RequestRecords; logStream.WriteLine("------conformance test result ( failed count {0} )------", FailedTestResult.Count); while (ruleRequestRecord.MoveNext()) { string rulename = (string)ruleRequestRecord.Key; if (FailedTestResult.ContainsKey(rulename)) { string result = string.Empty; List<string> reqeustRecords = (List<string>)ruleRequestRecord.Value; result += "\t" + reqeustRecords.Count.ToString(); foreach (string record in reqeustRecords) { result += "\t" + record; } logStream.WriteLine(string.Format("{0}\t{1}{2}", rulename, FailedTestResult[rulename], result)); FailedTestResult.Remove(rulename); } else { List<string> reqeustRecords = (List<string>)ruleRequestRecord.Value; logStream.WriteLine(string.Format("{0}\tsuccess\t{1}", rulename, reqeustRecords.Count)); } } if (FailedTestResult.Count != 0) { logStream.WriteLine("some rule's request not in ConformanceDataService.ruleRequestRecord"); } foreach (var ruleResult in FailedTestResult) { string rulename = ruleResult.Key; logStream.WriteLine(rulename + "\t" + ruleResult.Value); } logStream.WriteLine(); } catch (Exception ex) { logStream.WriteLine("Exception occur when write log"); logStream.WriteLine(ex); } finally { logStream.Close(); } }
/// <summary> /// Se charge d'initialiser la connection /// </summary> public Serveur() { chatServer = new TcpListener(9595); ServerUp = true; ClientList = new Dictionary<int, TcpClient>(); chatServer.Start(); Console.WriteLine("Server Up"); while (ServerUp) { TcpClient chatClient = null; chatClient = chatServer.AcceptTcpClient(); Console.WriteLine("You are now connected"); StreamReader reader = new StreamReader(chatClient.GetStream()); int id = Convert.ToInt32(reader.ReadLine()); Console.WriteLine("Id obtained: " + id); if (ClientList.ContainsKey(id)) { ClientList[id].Close(); ClientList.Remove(id); } ClientList.Add(id, chatClient); ClientManager manager = new ClientManager(this, chatClient, id); } }
public void Test3(int arg) { Dictionary<string, int> dictionary1 = new Dictionary<string, int>("aaa", 123, "xyz", true); string key = "blah"; int c = dictionary1.Count; int c2 = GetData2().Count; bool b = dictionary1.ContainsKey("aaa"); dictionary1.Remove("aaa"); dictionary1.Remove("Proxy-Connection"); dictionary1.Remove(key); dictionary1.Clear(); string[] keys = dictionary1.Keys; }
public void Remove() { IDictionary<string, string> dict = new Dictionary<string, string>(); dict.Add("Key", "Value"); dict = dict.ToReadOnlyDictionary(); Assert.Throws<NotSupportedException>(() => dict.Remove("Key")); }
static void Main(string[] args) { if (new List<string>(args).Contains("--RunDiagnostics")) { Console.Clear(); Dictionary<string, List<string>> diags = new Dictionary<string, List<string>>(); foreach (Type t in Utility.LocateTypeInstances(typeof(IDiagnosable))) { Object obj = null; foreach (MethodInfo mi in t.GetMethods(BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance)) { if (mi.GetCustomAttributes(typeof(DiagnosticFunctionAttribute), false).Length > 0) { DiagnosticFunctionAttribute att = ((DiagnosticFunctionAttribute)mi.GetCustomAttributes(typeof(DiagnosticFunctionAttribute), false)[0]); Delegate del = null; if (mi.IsStatic) { del = Delegate.CreateDelegate(typeof(DiagnosticFunctionAttribute.DiagnosticsDelegate), mi); } else { if (obj == null) obj = t.GetConstructor(Type.EmptyTypes).Invoke(null); del = DiagnosticFunctionAttribute.DiagnosticsDelegate.CreateDelegate(t, obj, mi.Name); } List<string> tmp = ((DiagnosticFunctionAttribute.DiagnosticsDelegate)del).Invoke(); if (tmp != null) { string name = att.GroupName; if (diags.ContainsKey(name)) { tmp.AddRange((List<string>)diags[name]); diags.Remove(name); diags.Add(name, tmp); } else diags.Add(name, tmp); } } } } Console.WriteLine("Diagnostics Results:"); foreach (string key in diags.Keys) { Console.WriteLine(key + ":"); foreach (string line in diags[key]) Console.WriteLine(string.Format("\t{0}", line)); } return; } Thread.CurrentThread.Name = "MainThread"; Console.TreatControlCAsInput = false; Console.CancelKeyPress += new ConsoleCancelEventHandler(Console_CancelKeyPress); _service = new ServerService(args); _service.WaitForExit(); }
void LoginCallback(FBResult result) { Debug.Log("FB UserID: " + FB.UserId); Dictionary<string, string> parms = new Dictionary<string,string>(); parms.Add("fields", "id,first_name,friends.limit(100).fields(first_name,id)"); FB.API("/me", Facebook.HttpMethod.GET, APICallback, parms); parms.Remove("fields"); parms.Add("fields", "score,user.limit(20)"); FB.API ("/app/scores", Facebook.HttpMethod.GET, ScoresCallback); }
/// <summary> /// UploadPicture method that does all the uploading work. /// </summary> /// <param name="stream">The <see cref="Stream"/> object containing the pphoto to be uploaded.</param> /// <param name="fileName">The filename of the file to upload. Used as the title if title is null.</param> /// <param name="title">The title of the photo (optional).</param> /// <param name="description">The description of the photograph (optional).</param> /// <param name="tags">The tags for the photograph (optional).</param> /// <param name="isPublic">false for private, true for public.</param> /// <param name="isFamily">true if visible to family.</param> /// <param name="isFriend">true if visible to friends only.</param> /// <param name="contentType">The content type of the photo, i.e. Photo, Screenshot or Other.</param> /// <param name="safetyLevel">The safety level of the photo, i.e. Safe, Moderate or Restricted.</param> /// <param name="hiddenFromSearch">Is the photo hidden from public searches.</param> /// <param name="callback">Callback method to call upon return of the response from Flickr.</param> public void UploadPictureAsync(Stream stream, string fileName, string title, string description, string tags, bool isPublic, bool isFamily, bool isFriend, ContentType contentType, SafetyLevel safetyLevel, HiddenFromSearch hiddenFromSearch, Action<FlickrResult<string>> callback) { CheckRequiresAuthentication(); Uri uploadUri = new Uri(UploadUrl); Dictionary<string, string> parameters = new Dictionary<string, string>(); if (title != null && title.Length > 0) { parameters.Add("title", title); } if (description != null && description.Length > 0) { parameters.Add("description", description); } if (tags != null && tags.Length > 0) { parameters.Add("tags", tags); } parameters.Add("is_public", isPublic ? "1" : "0"); parameters.Add("is_friend", isFriend ? "1" : "0"); parameters.Add("is_family", isFamily ? "1" : "0"); if (safetyLevel != SafetyLevel.None) { parameters.Add("safety_level", safetyLevel.ToString("D")); } if (contentType != ContentType.None) { parameters.Add("content_type", contentType.ToString("D")); } if (hiddenFromSearch != HiddenFromSearch.None) { parameters.Add("hidden", hiddenFromSearch.ToString("D")); } parameters.Add("api_key", apiKey); if (!String.IsNullOrEmpty(OAuthAccessToken)) { parameters.Remove("api_key"); OAuthGetBasicParameters(parameters); parameters.Add("oauth_token", OAuthAccessToken); string sig = OAuthCalculateSignature("POST", uploadUri.AbsoluteUri, parameters, OAuthAccessTokenSecret); parameters.Add("oauth_signature", sig); } else { parameters.Add("auth_token", apiToken); } UploadDataAsync(stream, fileName, uploadUri, parameters, callback); }
//Start from start, move to within distance of goal within max steps. public static HexPosition[] search(HexPosition start, HexPosition goal, int max, int distance = 0) { max += distance; //Now it's the maximum distance to the goal, instead of just the maximum number of steps. //HashSet<HexPosition> closedSet = new HashSet<HexPosition>(); // The set of nodes already evaluated. //HashSet<HexPosition> openSet = new HashSet<HexPosition>(start); // The set of tentative nodes to be evaluated, initially containing the start node Dictionary<HexPosition, HexPosition> cameFrom = new Dictionary<HexPosition, HexPosition>(); // The map of navigated nodes. Dictionary<HexPosition, int> gScore = new Dictionary<HexPosition, int>(); // Cost from start along best known path. Domain is the open and closed sets. Dictionary<HexPosition, int> fScore = new Dictionary<HexPosition, int>(); // Estimated total cost from start to goal through y. Domain is the open set. gScore.Add(start, 0); fScore.Add(start, start.dist(goal)); while (fScore.Count > 0) { HexPosition current = getMin(fScore); if (current.dist(goal) <= distance) { int length = 0; gScore.TryGetValue(current, out length); return reconstructPath(cameFrom, current, length + 1); } fScore.Remove(current); foreach (HexPosition neighbor in current.Neighbors) { if (neighbor.containsKey("Obstacle") || neighbor.containsKey("Unit")) { continue; //Make this more general. } if (gScore.ContainsKey(neighbor) && !fScore.ContainsKey(neighbor)) { continue; } int tentativeGScore = 0; gScore.TryGetValue(current, out tentativeGScore); ++tentativeGScore; if (tentativeGScore > max) { continue; } int neighborGScore = 0; gScore.TryGetValue(current, out neighborGScore); if (!fScore.ContainsKey(neighbor) || tentativeGScore < neighborGScore) { int newFScore = tentativeGScore + neighbor.dist(goal); if (newFScore > max) { continue; } cameFrom.Add(neighbor, current); gScore.Add(neighbor, tentativeGScore); fScore.Add(neighbor, newFScore); } } } return new HexPosition[0] { }; }
// Use this for initialization void Start() { GameObject[] gos = GameObject.FindObjectsOfType( typeof( GameObject ) ) as GameObject[]; #region Dictionary MyDictionary = new Dictionary<string,int>(); MyDictionary.Add("Zombies",10); //prints 10; Debug.Log ( MyDictionary["Zombies"] ); //int and object Dictionary<int, Object> obs = new Dictionary<int, Object>(); Object[] allObjects = GameObject.FindObjectsOfType( typeof( Object ) ) as Object[]; for( int i = 0; i < allObjects.Length; i++ ) { obs.Add( i, allObjects[i] ); Debug.Log( obs[i] ); } //lists GameObject names in the scene Dictionary<string, int> SceneDictionary = new Dictionary<string, int>(); foreach( GameObject go in gos ) { bool containsKey = SceneDictionary.ContainsKey(go.name); if( containsKey ) { SceneDictionary[go.name] += 1; } else { SceneDictionary.Add(go.name, 1); } } objectNames = new string[SceneDictionary.Keys.Count]; objectCounts = new int[SceneDictionary.Values.Count]; SceneDictionary.Keys.CopyTo(objectNames, 0); SceneDictionary.Values.CopyTo(objectCounts, 0); SceneDictionary.Remove("Main Camera"); #endregion #region Stack //create a new stack Stack objectStack = new Stack(); //assign objects to the stack using push foreach( GameObject go in gos ) { objectStack.Push( go ); } //initialize the class scope ObjectStack to view in the inspector panel ObjectStack = new GameObject[objectStack.Count]; //copy the stack to the array in Unity objectStack.CopyTo(ObjectStack, 0 ); #endregion }
public static TermVector operator -(TermVector left, TermVector right) { Dictionary<string, int> difference = new Dictionary<string, int>(left.vector); foreach (string term in right.Terms) { int length = 0; if (difference.TryGetValue(term, out length)) difference.Remove(term); difference.Add(term, length - right.GetDimensionLength(term)); } return new TermVector(difference); }
public Dictionary<int, string> DictionaryTst() { Dictionary<int, string> dic = new Dictionary<int, string>(); dic.Add(1, "first"); dic.Add(2, "second"); dic.Add(3, "thrid"); dic.Remove(2); dic.Add(4, "four"); return dic; }
/// <summary> /// Construct an object name with several key properties from a Dictionary. /// </summary> /// <param name="domain">The domain part of the object name.</param> /// <param name="properties">A hash table containing one or more key properties. The key of each entry /// in the table is the key of a key property in the object name. The associated value in the table is /// the associated value in the object name.</param> /// <exception cref="NetMX.MalformedObjectNameException">The domain contains an illegal character, or one of /// the keys or values in table contains an illegal character, or one of the values in table does not /// follow the rules for quoting.</exception> public ObjectName(string domain, IDictionary<string, string> properties) { _domain = domain; SetDomainPattern(); _properties = new Dictionary<string,string>(properties); if (_properties.ContainsKey("*")) { _properties.Remove("*"); _isPropertyPattern = true; } CreateCanonicalPropertyList(); _originalPropertyList = _canonicalPropertyList; }
public static TermVector operator +(TermVector left, TermVector right) { Dictionary<string, int> sum = new Dictionary<string, int>(left.vector); foreach (string term in right.Terms) { int length = 0; if (sum.TryGetValue(term, out length)) sum.Remove(term); sum.Add(term, length + right.GetDimensionLength(term)); } return new TermVector(sum); }
public static void ApplyPendingStoryMerges() { Helpers.RunSqlStatement(Name, "update ignore StoryMerges s1 join StoryMerges s2 on s2.StoryID1=s1.StoryID2 set s2.StoryID1=s1.StoryID1", false); //Get user-initiated merge actions. The actions are grouped as a user may have merged stories recursively. Dictionary<long, HashSet<long>> mergeGroups = new Dictionary<long, HashSet<long>>(); Helpers.RunSelect(Name, "select StoryID1, StoryID2, IP, UserID from StoryMerges where MergedAt is null order by StoryID2 desc;", mergeGroups, (values, reader) => { long keepID = reader.GetInt64("StoryID1"); long mergeID = reader.GetInt64("StoryID2"); if (mergeGroups.ContainsKey(mergeID)) { HashSet<long> tmp = mergeGroups[mergeID]; tmp.Add(mergeID); mergeGroups.Remove(mergeID); if (mergeGroups.ContainsKey(keepID)) mergeGroups[keepID].UnionWith(tmp); else mergeGroups.Add(keepID, tmp); } else if (mergeGroups.ContainsKey(keepID)) { mergeGroups[keepID].Add(mergeID); } else { mergeGroups.Add(keepID, new HashSet<long>()); mergeGroups[keepID].Add(mergeID); } long ip = reader.GetInt64("IP"); long userID = reader.GetInt64("UserID"); string sql = @"insert into StoryLog (IP, UserID, Timestamp, EventType, StoryAgeInSeconds, StoryID, MergedWithStoryID, TweetCount, RetweetCount, UserCount, TopUserCount) select " + ip + "," + userID + ", utc_timestamp(), 12, unix_timestamp(utc_timestamp())-unix_timestamp(StartTime), StoryID, " + keepID + @", TweetCount, RetweetCount, UserCount, TopUserCount from Story where StoryID = " + mergeID + ";"; Helpers.RunSqlStatement(Name, sql, false); } ); var mergeActions = mergeGroups.SelectMany(n => n.Value.Select(m => new MergeAction() { KeptStoryID = n.Key, MergedStoryID = m })); //Perform merge actions MergeStories(mergeActions, isAutomerge: false); //Clean old actions Helpers.RunSqlStatement(Name, "delete from StoryMerges where MergedAt is not null and MergedAt < (utc_timestamp() - interval 1 hour);", false); }
/* better algorithm * there are only three status ; not seen, seen once and seen multiple */ public static string FindFirstChar2(String str) { Dictionary<int, object> table = new Dictionary<int, object> (); object SeenOnce = new object (); object SeenMulti = new object (); object Seen; int length = str.Length; object value; for(int i = 0 ; i <length ; ) { int cp = Char.ConvertToUtf32(str, i); i += Char.IsSurrogatePair (str, i) ? 2 : 1; Console.Write("U+{0:X4}->{1}", cp, str[i-1]); table.TryGetValue(cp, out value); Seen = value; if (Seen == null) { table.Add (cp, SeenOnce); Console.WriteLine ("->fail"); } else { if (Seen.Equals( SeenOnce)) { table.Remove (cp); table.Add(cp, SeenMulti); Console.WriteLine ("->success"); } } // Console.WriteLine(table[0]); //String s = table[cp].ToString(); //Console.WriteLine (Seen); } for (int i=0; i< length;) { int cp = Char.ConvertToUtf32(str, i); i += Char.IsSurrogatePair (str, i) ? 2 : 1; if( SeenOnce.Equals( table[cp])) { return Char.ConvertFromUtf32(cp); } } return null; }
public FormPlugins() { InitializeComponent(); var plugins = new Dictionary<string, Tuple<string, List<FunctionBase>>>(PluginManager.Plugins); listViewFiles.BeginUpdate(); DirectoryInfo pluginDir = new DirectoryInfo(Gui.Scripting.PluginDirectory); foreach (var file in pluginDir.GetFiles("*.dll")) { ListViewItem fileItem = new ListViewItem(file.Name); listViewFiles.Items.Add(fileItem); string fileNameLower = file.Name.ToLowerInvariant(); if (plugins.ContainsKey(fileNameLower)) { fileItem.Checked = !PluginManager.DoNotLoad.Contains(fileNameLower); List<FunctionBase> functions = plugins[fileNameLower].Item2; fileItem.Tag = CreateFunctionItems(functions); plugins.Remove(fileNameLower); } else { fileItem.Font = new Font(fileItem.Font, FontStyle.Italic); } } foreach (var pair in plugins) { string fileName = pair.Value.Item1; ListViewItem fileItem = new ListViewItem(fileName); fileItem.Checked = !PluginManager.DoNotLoad.Contains(fileName.ToLowerInvariant()); fileItem.Tag = CreateFunctionItems(pair.Value.Item2); listViewFiles.Items.Add(fileItem); } listViewFiles.AutoResizeColumns(); listViewFiles.EndUpdate(); listViewFiles.ItemChecked += new ItemCheckedEventHandler(listViewFiles_ItemChecked); listViewFunctions.ListViewItemSorter = new FunctionSorter(); }
public static List<GameObject> findPath(GameObject nodeFrom, GameObject nodeTo, Dictionary<terrainType,int> moveDict) { List<GameObject> openList = new List<GameObject>(); List<GameObject> closedList = new List<GameObject>(); Dictionary<GameObject,GameObject> parentDict = new Dictionary<GameObject, GameObject>(); Dictionary<GameObject, int> fScore = new Dictionary<GameObject, int>(); Dictionary <GameObject, int> gScore = new Dictionary<GameObject, int>(); GameObject currentNode = nodeFrom; gScore.Add (currentNode,0); fScore.Add (currentNode,gScore[currentNode]+getHeuristic(nodeFrom,nodeTo)); openList.Add(currentNode); while(openList.Count >0){ currentNode = getLowest(openList,fScore); if(currentNode == nodeTo){ return (bakePath (nodeFrom, nodeTo, parentDict)); } openList.Remove (currentNode); closedList.Add (currentNode); foreach(GameObject hex in currentNode.GetComponent<MapHex>().neighborList){ int tempG = (gScore[currentNode]+moveDict[hex.GetComponent<MapHex>().getTerrain()]); if(!openList.Contains (hex) && !closedList.Contains(hex)){ openList.Add (hex); parentDict.Add (hex, currentNode); gScore.Add (hex,tempG); fScore.Add (hex,gScore[hex]+getHeuristic(hex,nodeTo)); } if(tempG<gScore[hex]){ if(parentDict.ContainsKey(hex))parentDict.Remove (hex); parentDict.Add (hex, currentNode); if(gScore.ContainsKey(hex))gScore.Remove (hex); gScore.Add (hex,tempG); if(fScore.ContainsKey(hex))fScore.Remove (hex); fScore.Add (hex,gScore[hex]+getHeuristic(hex,nodeTo)); } if(moveDict[hex.GetComponent<MapHex>().getTerrain()] >900){ openList.Remove(hex); closedList.Add (hex); } } } Debug.Log ("Path unreachable."); return null; }
public static IEnumerable<PrimeT> Generate () { yield return 2; yield return 3; var dct = new Dictionary<PrimeT, PrimeT> (); PrimeT bp = 3; PrimeT q = 9; IEnumerator<PrimeT> bps = null; checked { for (var n = (PrimeT) 5; ; n += 2) { if (n >= q) { // always equal or less... if (q <= 9) { bps = Generate ().GetEnumerator (); bps.MoveNext (); bps.MoveNext (); } // move to 3... bps.MoveNext (); var nbp = bps.Current; q = nbp * nbp; var adv = bp + bp; bp = nbp; dct.Add (n + adv, adv); } else { if (dct.ContainsKey (n)) { PrimeT nadv; dct.TryGetValue (n, out nadv); dct.Remove (n); var nc = n + nadv; while (dct.ContainsKey (nc)) { nc += nadv; } dct.Add (nc, nadv); } else { yield return n; } } } } }