void ServerConsole() { var stringMatch = new Regex(@"\""(?<text>.*?)\""|(?<text>\w+)", RegexOptions.Compiled); var commands = new Dictionary<string, Action<string[]>>() { ["shutdown"] = this.Shutdown, ["quit"] = this.Shutdown, ["save"] = this.Save, }; while(true) { string line = Console.ReadLine(); var matches = stringMatch.Matches(line); var command = matches.Cast<Match>().Take(1).Select(x => x.Groups["text"].Value).First().ToLower(); var args = matches.Cast<Match>().Skip(1).Select(x => x.Groups["text"].Value).ToArray(); if(commands.ContainsKey(command)) { commands[command](args); } else { Console.WriteLine("Command ´{0}´ not found.", command); } } }
public static void Main(string[] args) { Dictionary<string, Action> options = new Dictionary<string, Action>() { { "interfaces", PrintNetworkInterfaces }, { "interfaceproperties", PrintNetworkInterfaceProperties }, { "interfacestatistics", PrintNetworkInterfaceStatistics }, { "ipv4", PrintIpv4Statistics }, { "ipv6", PrintIpv6Statistics }, { "icmp4", PrintIcmp4Statistics }, { "icmp6", PrintIcmp6Statistics }, { "udp4", PrintUdp4Statistics }, { "udp6", PrintUdp6Statistics }, { "tcp4", PrintTcp4Statistics }, { "tcp6", PrintTcp6Statistics }, { "connections", PrintSocketConnections }, { "networkchange", NetworkChangeTest }, { "ipglobal", PrintIPGlobals } }; string selection = (args?.Length >= 1) ? args[0] : null; if (selection == null || !options.Keys.Contains(selection)) { Console.WriteLine("Options: " + Environment.NewLine + string.Join(Environment.NewLine, options.Keys.Select(s => $"* {s}"))); } else { options[selection](); } }
public string InvokeOutputMethod(string method, string param) { Dictionary<string, Func<string>> dictMethod = new Dictionary<string, Func<string>>() { {"GetCellText",()=>GetCellText(Convert.ToInt32(param.Split('|')[0]),Convert.ToInt32(param.Split('|')[1]))} }; return dictMethod[method](); }
public string InvokeOutputMethod(string method, string param) { Dictionary<string, Func<string>> dictMethod = new Dictionary<string, Func<string>>() { {"IsChecked",()=>IsChecked()?"1":"0"} }; return dictMethod[method](); }
public void Configuration(IAppBuilder app) { app.Use(async (ctx, next) => { var actions = new Dictionary<string, Func<IAsyncDocumentSession, Task>> { {"GET", async session => { var url = await session.LoadAsync<Url>(ctx.Request.Path.Value.Substring(1)); if (url != null) { ctx.Response.StatusCode = (int) HttpStatusCode.MovedPermanently; ctx.Response.Headers["Location"] = url.Location; } else ctx.Response.StatusCode = (int)HttpStatusCode.NotFound; }}, {"POST", async session => { var random = new Random(); var hash = string.Join("", Enumerable.Range(0, 7).Select(_ => Chars[random.Next(Chars.Length)])); await session.StoreAsync(new Url {Id = hash, Location = ctx.Request.Query["path"]}); await session.SaveChangesAsync(); ctx.Response.StatusCode = (int)HttpStatusCode.Created; await ctx.Response.WriteAsync(hash); }} }; using (var session = DocumentStore.OpenAsyncSession()) await actions[ctx.Request.Method](session); }); }
public string InvokeOutputMethod(string method, string param) { Dictionary<string, Func<string>> dictMethod = new Dictionary<string, Func<string>>() { {"GetText",()=>GetText()} }; return dictMethod[method](); }
/// <summary> /// Initialize the QvFacebookConnection. /// </summary> public override void Init() { QvxLog.Log(QvxLogFacility.Application, QvxLogSeverity.Notice, "Init()"); // Log in to facebook LoginToFacebook(); MTables = new List<QvxTable>(); // Create all supported tables var tableDictionary = new Dictionary<FacebookMetadataTag, Func<FacebookMetadataTag, QvxTable>> { { FacebookMetadataTag.friends, x => CreatePersonsTable(x) }, { FacebookMetadataTag.family, x => CreatePersonsTable(x) }, { FacebookMetadataTag.movies, x => CreateEntertainmentTable(x) }, { FacebookMetadataTag.television, x => CreateEntertainmentTable(x) }, { FacebookMetadataTag.likes, x => CreateEntertainmentTable(x) }, { FacebookMetadataTag.books, x => CreateEntertainmentTable(x) }, { FacebookMetadataTag.music, x => CreateEntertainmentTable(x) }, { FacebookMetadataTag.games, x => CreateEntertainmentTable(x) }, }; if (tableDictionary.Keys.Count != Enum.GetNames(typeof(FacebookMetadataTag)).Length) { QvxLog.Log(QvxLogFacility.Application, QvxLogSeverity.Warning, "Init() - Mismatch between the number of supported metadata tags and tables"); } foreach (var key in tableDictionary.Keys) { MTables.Add(tableDictionary[key](key)); } }
public static void ClientHandler(TcpClient client) { var d = new Dictionary<string, ProcessCommand>() { { "cat", CatFile }, { "clx", CalcClx }, { "erf", CalcErf }, { "sz", FileSize }, { "info", GetInfo } }; while (client.Connected) { using (var streamReader = new StreamReader(client.GetStream())) using (var streamWriter = new StreamWriter(client.GetStream())) { var cmd = streamReader.ReadLine().Split(" ".ToCharArray(), 2); try { d[cmd[0]](cmd[1], streamWriter); } catch { streamWriter.WriteLine("Error :("); } streamWriter.Flush(); } } client.Close(); }
static void Main(string[] args) { var names = Regex.Split(Console.ReadLine(), "\\s+").ToList(); var predicates = new Dictionary<string, Func<string, string, bool>> { { "StartsWith", (name, substring) => name.StartsWith(substring) }, { "EndsWith", (name, substring) => name.EndsWith(substring) }, { "Length", (name, length) => name.Length.ToString().Equals(length) } }; string command; while ((command = Console.ReadLine()) != "Party!") { if (names.Count == 0) { break; } var parameters = Regex.Split(command, "\\s+"); var action = parameters[0]; var condition = parameters[1]; var conditionOperator = parameters[2]; var filteredNames = new List<string>(); foreach (string name in names) { if (predicates[condition](name, conditionOperator)) { switch (action) { case "Double": filteredNames.Add(name); filteredNames.Add(name); break; case "Remove": // Not adding jack. break; default: throw new NotImplementedException(); } } else { filteredNames.Add(name); } } names = filteredNames.ToList(); } if (names.Count != 0) { Console.WriteLine($"{string.Join(", ", names)} are going to the party!"); } else { Console.WriteLine("Nobody is going to the party!"); } }
public static void FromFile(string csvPath, string jsonPath, Dictionary<string, string> propertyMapper, Dictionary<string, Func<string, dynamic>> customValueMappers, Func<Dictionary<string, dynamic>, bool> excludeEntryPredicate) { string[] lines = File.ReadAllLines(csvPath); if (lines.Length == 0) { return; } string[] properties = ParseProperties(lines[0], propertyMapper); List<Dictionary<string, dynamic>> jsonPayload = new List<Dictionary<string, dynamic>>(lines.Length - 1); foreach (string line in lines.Skip(1)) { Dictionary<string, dynamic> entry = new Dictionary<string, dynamic>(); int propertyIndex = 0; foreach (string value in CleanCsvEntry(SplitCsvLine(line))) { string property = properties[propertyIndex]; entry[property] = customValueMappers.ContainsKey(property) ? customValueMappers[property](value) : ParseValue(value); propertyIndex++; } if (excludeEntryPredicate != null && excludeEntryPredicate(entry)) { continue; } jsonPayload.Add(entry); } File.WriteAllText(jsonPath, JsonConvert.SerializeObject(jsonPayload, Formatting.Indented)); }
public void FireStateEvent(Dictionary<int, StateListenerEvent> vDic, int vStateType, object vObj) { if(vDic.ContainsKey(vStateType)) vDic[vStateType](vObj); }
public void Run(IBus bus, TextWriter w) { _c.Add(bus.Subscribe<MessageA>(OnMessageA)); _c.Add(bus.Subscribe<MessageB>(OnMessageB)); _c.Add(bus.Subscribe<MessageC>(OnMessageC)); var r = new Random(); var dict = new Dictionary<int, Func<object>> { {0, () => new MessageA()}, {1, () => new MessageB()}, {2, () => new MessageC()}, }; int count = 0; var sw = Stopwatch.StartNew(); while (count < 100000) { bus.Publish(dict[r.Next(0, 3)]()); count++; } w.WriteLine("Through {0}", sw.ElapsedMilliseconds); while (_aCount != MessageA.Count && _bCount != MessageB.Count && _cCount != MessageC.Count) { WriteInfo(w); Thread.Sleep(1000); } WriteInfo(w); }
public void Run(IBus bus, TextWriter w) { c.Add(bus.Subscribe<MessageA>(onMessageA)); c.Add(bus.Subscribe<MessageB>(onMessageB)); c.Add(bus.Subscribe<MessageC>(onMessageC)); var r = new Random(); var dict = new Dictionary<int, Func<object>> { {0, () => new MessageA()}, {1, () => new MessageB()}, {2, () => new MessageC()}, }; int count = 0; var sw = Stopwatch.StartNew(); while (count < 100000) { bus.Publish(dict[r.Next(0, 3)]()); count++; } w.WriteLine("Through {0}", sw.ElapsedMilliseconds); count = 0; while (count < 10) { w.WriteLine("From MsgA:{0}({1}), B:{2}({3}), C:{4}({5})", aCount, MessageA.Count, bCount, MessageB.Count, cCount, MessageC.Count); Thread.Sleep(1000); count++; } }
//private void PrepareLiveDataVector() //{ // if ((model == (StaticString.beforeBlank + Database.GetText("QM125T-8H", "QingQi"))) || // (model == (StaticString.beforeBlank + Database.GetText("QM250GY", "QingQi"))) || // (model == (StaticString.beforeBlank + Database.GetText("QM250T", "QingQi")))) // { // Manager.LiveDataVector = Database.GetLiveData("Synerject"); // } // else if ((model == (StaticString.beforeBlank + Database.GetText("QM200GY-F", "QingQi"))) || // (model == (StaticString.beforeBlank + Database.GetText("QM200-3D", "QingQi"))) || // (model == (StaticString.beforeBlank + Database.GetText("QM200J-3L", "QingQi")))) // { // Manager.LiveDataVector = Database.GetLiveData("Mikuni"); // } // else // { // Manager.LiveDataVector = Database.GetLiveData("Visteon"); // } //} protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); // Create your application here Window.SetFlags(WindowManagerFlags.KeepScreenOn, WindowManagerFlags.KeepScreenOn); List<string> arrays = new List<string>(); arrays.Add(StaticString.beforeBlank + Database.GetText("Dynamic Data Stream", "System")); arrays.Add(StaticString.beforeBlank + Database.GetText("Static Data Stream", "System")); funcs = new Dictionary<string, Func>(); funcs.Add(Database.GetText("Dynamic Data Stream", "System"), () => { //PrepareLiveDataVector(); Intent intent = new Intent(this, typeof(DataStreamActivity)); intent.PutExtra("Model", model); StartActivity(intent); }); funcs.Add(Database.GetText("Static Data Stream", "System"), () => { //PrepareLiveDataVector(); Intent intent = new Intent(this, typeof(StaticDataStreamActivity)); intent.PutExtra("Model", model); StartActivity(intent); }); ListAdapter = new ArrayAdapter<string>(this, Android.Resource.Layout.SimpleListItem1, arrays); ListView.ItemClick += (sender, e) => { string test = ((TextView)e.View).Text; funcs[test.TrimStart(' ')](); }; }
public static RuleRewriter Create(Type type, ISettings settings, Func<SemanticModel> semanticModel) { // A dictionary of all recognised constructor parameters. Dictionary<Type, Func<object>> parameterTypes = new Dictionary<Type, Func<object>> { { typeof(ISettings), () => settings }, { typeof(SemanticModel), semanticModel }, }; // Get a list of the type's constructors together with the constructor parameters types, // ordered by number of parameters descending. var ctors = (from c in type.GetConstructors() select new { ConstructorInfo = c, Parameters = c.GetParameters() }).OrderByDescending(x => x.Parameters.Length).ToArray(); // Get the first constructor in which we recognise all parameter types. var ctor = ctors.FirstOrDefault(x => x.Parameters.All(p => parameterTypes.Keys.Contains(p.ParameterType))); object[] parameters = ctor.Parameters.Select(x => parameterTypes[x.ParameterType]()).ToArray(); return (RuleRewriter)ctor.ConstructorInfo.Invoke(parameters); }
public AutoRedirectTests() { var responders = new Dictionary<string, Action<IOwinContext>> { { "/redirect-absolute-302", context => { context.Response.StatusCode = 302; context.Response.ReasonPhrase = "Found"; context.Response.Headers.Add("Location", new [] { "http://localhost/redirect" }); } }, { "/redirect-relative", context => { context.Response.StatusCode = 302; context.Response.ReasonPhrase = "Found"; context.Response.Headers.Add("Location", new [] { "redirect" }); } }, { "/redirect-absolute-301", context => { context.Response.StatusCode = 301; context.Response.ReasonPhrase = "Moved Permanently"; context.Response.Headers.Add("Location", new [] { "http://localhost/redirect" }); } }, { "/redirect-absolute-303", context => { context.Response.StatusCode = 303; context.Response.ReasonPhrase = "See Other"; context.Response.Headers.Add("Location", new [] { "http://localhost/redirect" }); } }, { "/redirect-absolute-307", context => { context.Response.StatusCode = 307; context.Response.ReasonPhrase = "Temporary Redirect"; context.Response.Headers.Add("Location", new [] { "http://localhost/redirect" }); } }, { "/redirect-loop", context => { context.Response.StatusCode = 302; context.Response.ReasonPhrase = "Found"; context.Response.Headers.Add("Location", new[] { "http://localhost/redirect-loop" }); } }, { "/redirect", context => context.Response.StatusCode = 200 } }; AppFunc appFunc = env => { var context = new OwinContext(env); responders[context.Request.Path.Value](context); return Task.FromResult((object)null); }; _handler = new OwinHttpMessageHandler(appFunc) { AllowAutoRedirect = true }; }
public void InvokeMethod(string method, string param) { Dictionary<string, Action> dictMethod = new Dictionary<string, Action>() { {"Click",()=>Click()} }; dictMethod[method](); }
public void InvokeMethod(string method, string param) { Dictionary<string, Action> dictMethod = new Dictionary<string, Action>() { {"ClickCell",()=>ClickCell(Convert.ToInt32(param.Split('|')[0]),Convert.ToInt32(param.Split('|')[1]),Convert.ToInt32(param.Split('|')[2]))} }; dictMethod[method](); }
public static void UnitTest_Action() { Dictionary<short, Action> dic = new Dictionary<short, Action>(); //short k = 0; //dic[k] = () => { Logger.Log("0"); }; dic[(short)0] = () => { Logger.Log("0"); }; dic[(short)0](); }
public void InvokeMethod(string method, string param) { Dictionary<string, Action> dictMethod = new Dictionary<string, Action>() { {"Select",()=>Select(param)} }; dictMethod[method](); }
public void InvokeMethod(string method, string param) { Dictionary<string, Action> dictMethod = new Dictionary<string, Action>() { {"Change",()=>Change(param=="0"?false:true)} }; dictMethod[method](); }
public static void TestUseCase() { var namedCallbacks = new Dictionary<string, Speak>(); namedCallbacks.Add("Shout", message => message.Length); namedCallbacks.Add("Whisper", message => message.Length); Assert.AreEqual(namedCallbacks["Shout"]("HELLO!"), 6, "Bridge696 HELLO!"); Assert.AreEqual(namedCallbacks["Whisper"]("HELLO"), 5, "Bridge696 HELLO"); }
fpv(Y a){try{ Action J=()=>{FormBorderStyle=(FormBorderStyle)(T=4-(X)(WindowState=2-WindowState)*2);BackColor=T!=0?Color.White:Color.Black;},j=()=>K("FPV by kasthack v 0.9.1.\r\nKeys:\r\nD/S/v/>/Num6/Num2/Space - next photo;\r\nA/W/^/</Num8/Num4 - previous photo;\r\nHome/H - first pic in folder\r\nEnd/E - last pic\r\nF11/Alt+Enter - fullscreen;\r\nEsc - exit fullscreen;\r\nEsc-Esc/Q - exit FPV;\r\nF1/?- show this message.","FPV:Help",0,64),k=()=>{if(K("Do U really want to delete"+G[B]+"?","Deleting",4,32)==6)try{File.Delete(G[B]);I(0);}catch{}},g=()=>A=true,h=()=>I(1),i=()=>I(-1),l=()=>I((B=0)-1),m=()=>I(B=0); H=new Dictionary<X,Action>{{68,h},{83,h},{40,h},{39,h},{98,h},{102,h},{32,h},{65,i},{87,i},{38,i},{37,i},{104,i},{100,i},{36,m},{72,m},{35,l},{69,l},{112,j},{191,j},{46,k},{81,Application.Exit},{82,()=>I(E.Next())},{27,()=>H[(X)WindowState==2?122:81]()},{122,()=>H[-1]()},{13,()=>{if(!A)I(1);else H[-1]();}},{-1,J},{262144,g},{18,g},{111,j}}; Controls.Add(F=new PictureBox{BorderStyle=0});F.SizeMode+=4;F.Dock+=5;F.MouseDoubleClick+=(x,y)=>J(); KeyUp+=(_,e)=>A&=!((T=(X)e.KeyCode)==65||T==18); KeyDown+=(c,b)=>{if(H.TryGetValue((X)b.KeyCode,out i))i();}; MouseWheel+=(_,e)=>I(e.Delta>0?-1:1); G=Directory.GetFiles(D=(V=Path.GetDirectoryName(a))==""?".":V);} catch{H[111]();T=9;return;} B=Array.IndexOf(G,a);I(0);}}
public static void Main (string[] args) { Dictionary<string, TestDel> dict = new Dictionary<string, TestDel> (); dict["a"] = delegate (int b) { return b; }; System.Console.WriteLine (dict["a"] (2)); }
public static object Dispatch(StageParams config, Dictionary<string, StageAction> mapping) { string[] subMapping = config.map.Split(new char[] { ':' }, 2); config.map = subMapping[1]; string key = subMapping[0]; if (mapping.ContainsKey(key)) return mapping[key](config); throw new Exception("Unknow mapping key: " + key); }
private void CreateBrowser() { //Создаем массив обработчиков доступных для вызова из js handlers = new Dictionary<string, Action<NameValueCollection>> { { "callfromjs", nv => CallJs("showMessage", new object[] { nv["msg"] + " Ответ из С#" }) } }; browser = new WebView (); browser.NavigationRequested += (sender, args) => { var url = new Uri(args.Request.Uri); if (url.Scheme != "mp") { //mp - myprotocol. //Обрабатываем вызовы только нашего специального протокола. //Переходы по обычным ссылкам работают как и прежде return; } var parameters = System.Web.HttpUtility.ParseQueryString(url.Query); handlers[url.Host.ToLower()](parameters); //Отменяем переход по ссылке browser.StopLoading(); }; browser.LoadHtmlString (@" <html> <head></head> <body id=body> <h1>Интерфейс</h1> <button id=btn>Вызвать C#</button> <p id=msg></p> <script> function buttonClick() { window.location.href = 'mp://callFromJs?msg=Сообщение из js.'; } function showMessage(msg) { document.getElementById('msg').innerHTML = msg; } document.getElementById('btn').onclick = buttonClick; </script> </body> </html> ", null); this.Add (browser); }
public TileSet Load(char[,] level, Dictionary<char,Func<Point, Tile>> map) { var height = level.GetHeight() + 1; var width = level.GetWidth() + 1; var tileSet = from y in Enumerable.Range(0, height) from x in Enumerable.Range(0, width) let tiles = map[level[x, y]](new Point(x, y)) where tiles != null select tiles; return new TileSet(tileSet); }
public ActionResult Show(string digits) { var selectedOption = digits; var optionActions = new Dictionary<string, Func<TwiMLResult>>() { {"1", ReturnInstructions}, {"2", Planets} }; return optionActions.ContainsKey(selectedOption) ? optionActions[selectedOption]() : RedirectWelcome(); }
static void Main(string[] args) { // DO NOT TRY TO UNDERSTAND THIS CODE // THE TEACHER IS JUST SHOWING OFF Dictionary<Tuple<bool, bool>, Func<int, string>> dict = new Dictionary<Tuple<bool, bool>, Func<int, string>> { { Tuple.Create(false, false), i => i.ToString()}, { Tuple.Create(true, false), _ => "Fizz"}, { Tuple.Create(false, true), _ => "Buzz"}, { Tuple.Create(true, true), _ => "FizzBuzz"} }; Enumerable.Range(1, 100).ToList().ForEach(i => Console.WriteLine(dict[Tuple.Create(i % 3 == 0, i % 5 == 0)](i))); }
/// <summary></summary> public static string TransformText(string value, TextTransformationOption option) { if (value.Length > 0) { var dictionary = new Dictionary<TextTransformationOption, Func<string, string>>(); dictionary.Add(TextTransformationOption.CamelCase, ToCamel); dictionary.Add(TextTransformationOption.PascalCase, ToPascal); dictionary.Add(TextTransformationOption.Underscored, ToUnderscored); value = dictionary[option](value); } return value; }