private void Complete(Which which, params object[] args) { if (which == Which.Resolve) { DoThen = (f, e, p) => { Resolve(args); }; } else { DoThen = (f, e, p) => { Reject(args); }; } var i = 0; while (i < Thens.Count) { var aThen = Thens[i]; if (which == Which.Resolve) { if (aThen.Filled != null) { aThen.Filled.Apply(null, args); } } else { if (aThen.Error != null) { aThen.Error.Apply(null, args); } } i++; } Thens.Clear(); }
TreeNode (TreeNode left, TreeNode right, int item) { this.next = new Next (); this.next.left = left; this.next.right = right; this.item = item; }
public SimplePromise() { Thens = new List<A>(); DoThen = (f, e, p) => { this.Thens.Add(new A() { Filled = f, Error = e, Progress = p }); }; }
/// <summary>delPort /// Remove Ports using the push api /// </summary> /// <param name="next">Callback for the async handler</param> public static void delPort(int port, string serverIP, string InterIPAddress, Next next) { Async(() => { //var eval = Session.Get("ports/del/" + InternalData.SettingsGrid.Username + "/" + InternalData.InformationGrid.ipAddress + "/" + port + "/" + serverIP); var eval = Session.Get("ports/del/" + InternalData.SettingsGrid.Username + "/" + InterIPAddress + "/" + port + "/" + serverIP); if (eval == null) return; var jO = JObject.Parse(eval); if (jO["msg"] != null) { next(true, jO["msg"].ToString()); } else { next(false, jO["emsg"].ToString()); } }); }
public override Task <Terminator <TReduction> > InvokeAsync(TReduction reduction, TInput value) => Test(value) ? Next.InvokeAsync(reduction, value) : Task.FromResult(Reduction(reduction));
/// <summary> /// Searches a path between the given 'start' and 'end' nodes. /// </summary> /// <param name="start">Start node</param> /// <param name="end">End node</param> /// <param name="results">The list is populated with the results</param> /// <param name="heuristic">Heuristic function</param> public void Search(T start, T end, ref List <T> results, Func <T, T, float> heuristic = null) { results.Clear(); if (GetNeighbors == null) { return; } var H = HeuristicResult(heuristic, start, end); var ParentNode = new AStarNode <T>(0, H, start, start); Open.Clear(); Closed.Clear(); Open.Push(ParentNode); while (Open.Count > 0) { ParentNode = Open.Pop(); Closed.Add(ParentNode); if (ParentNode.Pos.Equals(end)) { Closed.Add(ParentNode); PrepareResult(ref results); return; } foreach (var Next in GetNeighbors(ParentNode.Pos)) { var ClosedExists = false; foreach (var Item in Closed) { if (Item.Pos.Equals(Next)) { ClosedExists = true; break; } } if (ClosedExists) { continue; } var NewG = ParentNode.G + Next.Cost(ParentNode.Pos); var Index = -1; for (int i = 0; i < Open.Count; i++) { if (Open[i].Pos.Equals(Next)) { Index = i; break; } } if (Index == -1 || (Index > -1 && NewG < Open[Index].G)) { H = HeuristicResult(heuristic, Next, end); var NewNode = new AStarNode <T>(NewG, H, Next, ParentNode.Pos); if (Index == -1) { Open.Push(NewNode); } else { Open[Index] = NewNode; } } } } return; }
/// <summary> /// Solve the equation! /// This method recurses into the whole tree and returns a result from the equation. /// </summary> /// <param name="paramCallback">Parameter callback that will be used to get teh values of parameter nodes.</param> /// <returns>The solution of this node and all its subnodes!</returns> public override double Solve(ParamDelegate paramCallback) { //make sure this node is set up correctly //check arguments if (null == Prev) { throw new ArgumentNullException("Prev"); } if (null == Next) { throw new ArgumentNullException("Next"); } //Solve the sub nodes! double prevResult = Prev.Solve(paramCallback); double nextResult = Next.Solve(paramCallback); //what kind of operator do we got? switch (OrderOfOperationsValue) { case PemdasValue.Exponent: { return(Math.Pow(prevResult, nextResult)); } case PemdasValue.Multiplication: { return(prevResult * nextResult); } case PemdasValue.Division: { //guard against divide by zero exception if (0.0 == nextResult) { return(0.0); } else { return(prevResult / nextResult); } } case PemdasValue.Modulo: { //guard against divide by zero exception if (0.0 == nextResult) { return(0.0); } else { return(prevResult % nextResult); } } case PemdasValue.Addition: { return(prevResult + nextResult); } case PemdasValue.Subtraction: { return(prevResult - nextResult); } default: { throw new NotSupportedException("found a weirdo thing in an equation node?"); } } }
/// <summary> /// Frequent pattern extraction method that implement FPGrowth logic using an /// iterative pattern growth approach /// </summary> /// <param name="allTrans">Total list of input transaction</param> /// <returns>Frequent ItemSets</returns> public List <ItemSet> ExtractFrequentPattern(List <Transaction> allTrans) { // compute absolute support = relative support * # of transactions absMinSup = (int)System.Math.Ceiling(allTrans.Count * _minSup); result = new List <ItemSet>(); //We could have used two stacks instead of these lists!!! List <FPTree> FPTreeList = new List <FPTree>(); List <FPTree> FPTreeListNext = new List <FPTree>(); List <ItemSet> GivenListNow = new List <ItemSet>(); List <ItemSet> GivenListNext = new List <ItemSet>(); FPTree Next; ItemSet Given; ItemSet Beta; List <ItemSet> wholeTransToItemSet = new List <ItemSet>(); foreach (Transaction trans in allTrans) { wholeTransToItemSet.Add(trans.Itemset); } FPTree StartFPtree = new FPTree(); StartFPtree.SetMinSup(absMinSup); //Build the first tree on the whole transaction database list StartFPtree.BuildFirstTree(wholeTransToItemSet); //Add the first tree to the list of the fptree to process FPTreeList.Add(StartFPtree); //Here our given prefix is null GivenListNow.Add(new ItemSet()); //Looping on each fptree until there are ones to process while (FPTreeList.Count > 0) { for (int j = 0; j < FPTreeList.Count; j++) { Next = FPTreeList[j]; Given = GivenListNow[j]; if (!Next.isEmpty()) { // If the FPTree we are examining is composed of a single path // we use an optimization based on path node combination which // arrest current iteration if (Next.HasSinglePath) { GenerateCombPattern(Next, Given); } else { // Header table sorting Next.SortHeaderTable(); //Loop on each header table entry for (int i = 0; i < Next.GetHTSize(); i++) { //New beta ItemSet representing a frequent pattern Beta = new ItemSet(); //Concatenate with items present in the given ItemSet foreach (int item in Given.Items) { Beta.Add(item); } Beta.Add(Next.GetHTItem(i)); Beta.ItemsSupport = Next.GetHTFreq(i); // Add beta to frequent pattern result result.Add(Beta); // Here we generate the so called Conditional FPTree using a projection // of the original database called Conditional Pattern Base FPTreeListNext.Add(Next.CreateFPtree(i)); // Insert current beta in next given list GivenListNext.Add(Beta); } FPTreeList[j] = null; GivenListNow[j] = null; } } } FPTreeList.Clear(); GivenListNow.Clear(); for (int j = 0; j < GivenListNext.Count; j++) { FPTreeList.Add(FPTreeListNext[j]); GivenListNow.Add(GivenListNext[j]); GivenListNext[j] = null; FPTreeListNext[j] = null; } GivenListNext.Clear(); FPTreeListNext.Clear(); } return(result); }
/// <summary> /// Get the ports open for the user /// </summary> /// <param name="next">Callback for the async handler</param> public static void getPorts(Next next) { Async(() => { var eval = Session.Get("ports/get/" + InternalData.SettingsGrid.Username); if (eval == null) return; var jO = JArray.Parse(Session.Get("ports/get/" + InternalData.SettingsGrid.Username)); next(jO != null, jO); }); }
/// <summary> /// Async login /// </summary> /// <param name="username">Username</param> /// <param name="password">Password</param> /// <param name="next">Async callback</param> public static void Login(string username, string password, Next next) { Async(() => { try { var sender = new JObject(); sender["username"] = username; sender["password"] = password; var jO = JObject.Parse(Session.Post("login", sender.ToString())); if (jO["msg"] != null) { next(true, jO["msg"].ToString()); } else { next(false, jO["emsg"].ToString()); } } catch (Exception) { next(false, "Could not connect, please try again."); } }); }
public override void GenerateCode(GeneratedMethod method, ISourceWriter writer) { writer.WriteLine($"var {RoutingFrames.Segments} = (string[]){RouteGraph.Context}.Items[\"{RoutingFrames.Segments}\"];"); Next?.GenerateCode(method, writer); }
public override async Task Invoke(IOwinContext context) { RequestContextStorage.Value = new RequestContext(Guid.NewGuid().ToString()); await Next.Invoke(context); }
public static void ServersToItems(Next next, Next done = null) { Servers((success, value) => { var s = EventRegistrar.Status.AddTask("Fetching servers, and ping tests"); var items = ((JArray)value).Select(jO => { var name = new[] { jO["name"].ToString(), jO["locationCountry"].ToString(), jO["locationCity"].ToString(), jO["ip"].ToString() }; return new ListViewItem(name) { Name = jO["ip"].ToString(), Tag = string.Join(" ", name).ToLower() }; }) .ToList(); Parallel.ForEach(items, new ParallelOptions { MaxDegreeOfParallelism = 10 }, item => { var pingSender = new Ping(); var reply = pingSender.Send(IPAddress.Parse(item.Name), 5000); if (reply != null && reply.Status != IPStatus.Success) return; item.SubItems.Add(reply.RoundtripTime + ""); next(true, item); }); s.Lock(); if (done != null) done(true, null); }); }
public Task Invoke(ICommunicationContext env) { return(Task.Run(() => Next.Invoke(env))); }
public static void ServersToDropDown(Next next, Next done = null) { Servers((success, value) => { var s = EventRegistrar.Status.AddTask("Fetching Servers for Portforwarding"); var items = ((JArray)value).Select(jO => { var name = new[] { jO["name"].ToString(), jO["ip"].ToString() }; return new ListViewItem(name) { Name = jO["ip"].ToString(), Tag = string.Join(" ", name).ToLower() }; }) .ToList(); s.Lock(); if (done != null) done(true, null); }); }
public static void loadPorts(Next next, Next done = null) { getPorts((success, value) => { var s = EventRegistrar.Status.AddTask("Fetching ports"); var items = ((JArray)value).Select(jO => { var name = new[] { jO["serverip"].ToString(), jO["port"].ToString(), jO["internalip"].ToString(), jO["createdAt"].ToString(), jO["updatedAt"].ToString() }; return new ListViewItem(name) { Name = jO["id"].ToString(), Tag = string.Join(" ", name).ToLower() }; }) .ToList(); Parallel.ForEach(items, new ParallelOptions { MaxDegreeOfParallelism = 10 }, item => { next(true, item); }); s.Lock(); if (done != null) done(true, null); }); }
public static void Stats(Next next) { Async(() => GetStats((success, value) => { if (success) { var jO = (JObject) value; var data = new Dictionary<string, string>(); data["username"] = jO["user"]["username"].ToString(); data["activeConnections"] = jO["user"]["activeConnections"].ToString(); data["subscription"] = jO["user"]["subscription"].ToString(); data["serversAvailable"] = jO["server"]["serversAvailable"].ToString(); next(true, data); } })); }
public static void CreateConfig(string ip, Next next) { Async(() => GetCerts(ip, (success, value) => { var task = EventRegistrar.Status.AddTask("Creating config for " + ip); if (!Directory.Exists("ovpn")) Directory.CreateDirectory("ovpn"); if (success) { var blockedSites = ""; if (!string.IsNullOrEmpty(InternalData.SettingsGrid.Ignore)) { blockedSites = InternalData.SettingsGrid.Ignore.Trim().Replace("\r\n", ",").Split(',') .Aggregate("", (current, site) => current + ("route " + site.Replace(" ", "") + " 255.255.255.255 net_gateway\r\n")); } File.WriteAllText("ovpn\\" + ip + ".ovpn", Properties.Settings.Default.Config.Replace("$ip", ip) + "\r\n" + blockedSites + "\r\n" + (string) value); } next(success, "ovpn\\" + ip + ".ovpn"); task.Lock(); })); }
/// <summary> /// Get the active server list from the push api /// </summary> /// <param name="next">Callback for the async handler</param> public static void Servers(Next next) { Async(() => { var eval = Session.Get("servers"); if (eval == null) return; var jO = JArray.Parse(Session.Get("servers")); next(jO != null, jO); }); }
public override Task Invoke(IOwinContext context) { context.Response.Write("hello" + DateTime.Now);//管道继续往下走 return(Next.Invoke(context)); }
/// <summary> /// Gets the non-default, config from the server containg only the certs for the server /// </summary> /// <param name="ip">Ip of the server</param> /// <param name="next">Callback for the async handler</param> public static void GetCerts(string ip, Next next) { Async(() => { var config = Session.Get("config/" + ip); next(config != "404", config); }); }
public override async Task InvokeAsync(IPipeContext context, CancellationToken token) { await _handler(context, () => Next.InvokeAsync(context, token)); }
public override async Task Invoke(IOwinContext context) { await Task.Delay(1); await Next.Invoke(context); }
public override async Task Invoke(IOwinContext context) { this._logger.Write("Inside the 'Invoke' method of the '{0}' middleware.", GetType().Name); await Next.Invoke(context); }
public LambdaExpression ToLambdaExpression() => ExpressionChainer.Chain(Current?.ToLambdaExpression(), Next?.ToLambdaExpression());
public (float A, float B, float C) FindEquationOfLinePassingThrough() { return(VectorOperations.Vector.FindEquationOfLinePassingThrough(Previous.GetVector(), Next.GetVector())); }
/// <summary> /// Get the user statistics /// </summary> /// <param name="next">Callback for the async handler</param> public static void GetStats(Next next) { Async(() => { string ret = Session.Get("stats"); next(ret != "404", ret); }); }
/// <summary> /// Updates Internal IP for portforwarding using the push api /// </summary> /// <param name="next">Callback for the async handler</param> public static void updatePort(int port, string serverIP, string InterIPAddress, Next next) { Async(() => { //var eval = Session.Get("ports/add/" + InternalData.SettingsGrid.Username + "/" + InternalData.InformationGrid.ipAddress + "/" + port + "/" + serverIP); var eval = Session.Get("ports/update/" + InternalData.SettingsGrid.Username + "/" + InterIPAddress + "/" + port + "/" + serverIP); if (eval == null) { return; } var jO = JObject.Parse(eval); if (jO["msg"] != null) { next(true, jO["msg"].ToString()); } else { next(false, jO["emsg"].ToString()); } }); }
static WmiNetUtilsHelper() { myDllPath = System.Runtime.InteropServices.RuntimeEnvironment.GetRuntimeDirectory() + "\\wminet_utils.dll"; IntPtr procAddr = IntPtr.Zero; IntPtr loadLibrary = IntPtr.Zero; loadLibrary = LoadLibrary(myDllPath); if( loadLibrary != IntPtr.Zero) { procAddr = GetProcAddress(loadLibrary, "ResetSecurity"); if( procAddr != IntPtr.Zero) { ResetSecurity_f =(ResetSecurity) Marshal.GetDelegateForFunctionPointer(procAddr, typeof(ResetSecurity)); } procAddr = GetProcAddress(loadLibrary, "SetSecurity"); if( procAddr != IntPtr.Zero) { SetSecurity_f =(SetSecurity) Marshal.GetDelegateForFunctionPointer(procAddr, typeof(SetSecurity)); } procAddr = GetProcAddress(loadLibrary, "BlessIWbemServices"); if( procAddr != IntPtr.Zero) { BlessIWbemServices_f =(BlessIWbemServices) Marshal.GetDelegateForFunctionPointer(procAddr, typeof(BlessIWbemServices)); } procAddr = GetProcAddress(loadLibrary, "BlessIWbemServicesObject"); if( procAddr != IntPtr.Zero) { BlessIWbemServicesObject_f =(BlessIWbemServicesObject) Marshal.GetDelegateForFunctionPointer(procAddr, typeof(BlessIWbemServicesObject)); } procAddr = GetProcAddress(loadLibrary, "GetPropertyHandle"); if( procAddr != IntPtr.Zero) { GetPropertyHandle_f27=(GetPropertyHandle) Marshal.GetDelegateForFunctionPointer(procAddr, typeof(GetPropertyHandle)); } procAddr = GetProcAddress(loadLibrary, "WritePropertyValue"); if( procAddr != IntPtr.Zero) { WritePropertyValue_f28=(WritePropertyValue) Marshal.GetDelegateForFunctionPointer(procAddr, typeof(WritePropertyValue)); } procAddr = GetProcAddress(loadLibrary, "Clone"); if( procAddr != IntPtr.Zero) { Clone_f12=(Clone) Marshal.GetDelegateForFunctionPointer(procAddr, typeof(Clone)); } procAddr = GetProcAddress(loadLibrary, "VerifyClientKey"); if( procAddr != IntPtr.Zero) { VerifyClientKey_f =(VerifyClientKey) Marshal.GetDelegateForFunctionPointer(procAddr, typeof(VerifyClientKey)); } procAddr = GetProcAddress(loadLibrary, "GetQualifierSet"); if( procAddr != IntPtr.Zero) { GetQualifierSet_f =(GetQualifierSet) Marshal.GetDelegateForFunctionPointer(procAddr, typeof(GetQualifierSet)); } procAddr = GetProcAddress(loadLibrary, "Get"); if( procAddr != IntPtr.Zero) { Get_f =(Get) Marshal.GetDelegateForFunctionPointer(procAddr, typeof(Get)); } procAddr = GetProcAddress(loadLibrary, "Put"); if( procAddr != IntPtr.Zero) { Put_f =(Put) Marshal.GetDelegateForFunctionPointer(procAddr, typeof(Put)); } procAddr = GetProcAddress(loadLibrary, "Delete"); if( procAddr != IntPtr.Zero) { Delete_f =(Delete) Marshal.GetDelegateForFunctionPointer(procAddr, typeof(Delete)); } procAddr = GetProcAddress(loadLibrary, "GetNames"); if( procAddr != IntPtr.Zero) { GetNames_f =(GetNames) Marshal.GetDelegateForFunctionPointer(procAddr, typeof(GetNames)); } procAddr = GetProcAddress(loadLibrary, "BeginEnumeration"); if( procAddr != IntPtr.Zero) { BeginEnumeration_f =(BeginEnumeration) Marshal.GetDelegateForFunctionPointer(procAddr, typeof(BeginEnumeration)); } procAddr = GetProcAddress(loadLibrary, "Next"); if( procAddr != IntPtr.Zero) { Next_f =(Next) Marshal.GetDelegateForFunctionPointer(procAddr, typeof(Next)); } procAddr = GetProcAddress(loadLibrary, "EndEnumeration"); if( procAddr != IntPtr.Zero) { EndEnumeration_f =(EndEnumeration) Marshal.GetDelegateForFunctionPointer(procAddr, typeof(EndEnumeration)); } procAddr = GetProcAddress(loadLibrary, "GetPropertyQualifierSet"); if( procAddr != IntPtr.Zero) { GetPropertyQualifierSet_f =(GetPropertyQualifierSet) Marshal.GetDelegateForFunctionPointer(procAddr, typeof(GetPropertyQualifierSet)); } procAddr = GetProcAddress(loadLibrary, "Clone"); if( procAddr != IntPtr.Zero) { Clone_f =(Clone) Marshal.GetDelegateForFunctionPointer(procAddr, typeof(Clone)); } procAddr = GetProcAddress(loadLibrary, "GetObjectText"); if( procAddr != IntPtr.Zero) { GetObjectText_f =(GetObjectText) Marshal.GetDelegateForFunctionPointer(procAddr, typeof(GetObjectText)); } procAddr = GetProcAddress(loadLibrary, "SpawnDerivedClass"); if( procAddr != IntPtr.Zero) { SpawnDerivedClass_f =(SpawnDerivedClass) Marshal.GetDelegateForFunctionPointer(procAddr, typeof(SpawnDerivedClass)); } procAddr = GetProcAddress(loadLibrary, "SpawnInstance"); if( procAddr != IntPtr.Zero) { SpawnInstance_f =(SpawnInstance) Marshal.GetDelegateForFunctionPointer(procAddr, typeof(SpawnInstance)); } procAddr = GetProcAddress(loadLibrary, "CompareTo"); if( procAddr != IntPtr.Zero) { CompareTo_f =(CompareTo) Marshal.GetDelegateForFunctionPointer(procAddr, typeof(CompareTo)); } procAddr = GetProcAddress(loadLibrary, "GetPropertyOrigin"); if( procAddr != IntPtr.Zero) { GetPropertyOrigin_f =(GetPropertyOrigin) Marshal.GetDelegateForFunctionPointer(procAddr, typeof(GetPropertyOrigin)); } procAddr = GetProcAddress(loadLibrary, "InheritsFrom"); if( procAddr != IntPtr.Zero) { InheritsFrom_f =(InheritsFrom) Marshal.GetDelegateForFunctionPointer(procAddr, typeof(InheritsFrom)); } procAddr = GetProcAddress(loadLibrary, "GetMethod"); if( procAddr != IntPtr.Zero) { GetMethod_f =(GetMethod) Marshal.GetDelegateForFunctionPointer(procAddr, typeof(GetMethod)); } procAddr = GetProcAddress(loadLibrary, "PutMethod"); if( procAddr != IntPtr.Zero) { PutMethod_f =(PutMethod) Marshal.GetDelegateForFunctionPointer(procAddr, typeof(PutMethod)); } procAddr = GetProcAddress(loadLibrary, "DeleteMethod"); if( procAddr != IntPtr.Zero) { DeleteMethod_f =(DeleteMethod) Marshal.GetDelegateForFunctionPointer(procAddr, typeof(DeleteMethod)); } procAddr = GetProcAddress(loadLibrary, "BeginMethodEnumeration"); if( procAddr != IntPtr.Zero) { BeginMethodEnumeration_f =(BeginMethodEnumeration) Marshal.GetDelegateForFunctionPointer(procAddr, typeof(BeginMethodEnumeration)); } procAddr = GetProcAddress(loadLibrary, "NextMethod"); if( procAddr != IntPtr.Zero) { NextMethod_f =(NextMethod) Marshal.GetDelegateForFunctionPointer(procAddr, typeof(NextMethod)); } procAddr = GetProcAddress(loadLibrary, "EndMethodEnumeration"); if( procAddr != IntPtr.Zero) { EndMethodEnumeration_f =(EndMethodEnumeration) Marshal.GetDelegateForFunctionPointer(procAddr, typeof(EndMethodEnumeration)); } procAddr = GetProcAddress(loadLibrary, "GetMethodQualifierSet"); if( procAddr != IntPtr.Zero) { GetMethodQualifierSet_f =(GetMethodQualifierSet) Marshal.GetDelegateForFunctionPointer(procAddr, typeof(GetMethodQualifierSet)); } procAddr = GetProcAddress(loadLibrary, "GetMethodOrigin"); if( procAddr != IntPtr.Zero) { GetMethodOrigin_f =(GetMethodOrigin) Marshal.GetDelegateForFunctionPointer(procAddr, typeof(GetMethodOrigin)); } procAddr = GetProcAddress(loadLibrary, "QualifierSet_Get"); if( procAddr != IntPtr.Zero) { QualifierGet_f=(QualifierSet_Get) Marshal.GetDelegateForFunctionPointer(procAddr, typeof(QualifierSet_Get)); } procAddr = GetProcAddress(loadLibrary, "QualifierSet_Put"); if( procAddr != IntPtr.Zero) { QualifierPut_f=(QualifierSet_Put) Marshal.GetDelegateForFunctionPointer(procAddr, typeof(QualifierSet_Put)); } procAddr = GetProcAddress(loadLibrary, "QualifierSet_Delete"); if( procAddr != IntPtr.Zero) { QualifierDelete_f=(QualifierSet_Delete) Marshal.GetDelegateForFunctionPointer(procAddr, typeof(QualifierSet_Delete)); } procAddr = GetProcAddress(loadLibrary, "QualifierSet_GetNames"); if( procAddr != IntPtr.Zero) { QualifierGetNames_f=(QualifierSet_GetNames) Marshal.GetDelegateForFunctionPointer(procAddr, typeof(QualifierSet_GetNames)); } procAddr = GetProcAddress(loadLibrary, "QualifierSet_BeginEnumeration"); if( procAddr != IntPtr.Zero) { QualifierBeginEnumeration_f=(QualifierSet_BeginEnumeration) Marshal.GetDelegateForFunctionPointer(procAddr, typeof(QualifierSet_BeginEnumeration)); } procAddr = GetProcAddress(loadLibrary, "QualifierSet_Next"); if( procAddr != IntPtr.Zero) { QualifierNext_f=(QualifierSet_Next) Marshal.GetDelegateForFunctionPointer(procAddr, typeof(QualifierSet_Next)); } procAddr = GetProcAddress(loadLibrary, "QualifierSet_EndEnumeration"); if( procAddr != IntPtr.Zero) { QualifierEndEnumeration_f=(QualifierSet_EndEnumeration) Marshal.GetDelegateForFunctionPointer(procAddr, typeof(QualifierSet_EndEnumeration)); } procAddr = GetProcAddress(loadLibrary, "GetCurrentApartmentType"); if( procAddr != IntPtr.Zero) { GetCurrentApartmentType_f =(GetCurrentApartmentType) Marshal.GetDelegateForFunctionPointer(procAddr, typeof(GetCurrentApartmentType)); } procAddr = GetProcAddress(loadLibrary, "GetDemultiplexedStub"); if( procAddr != IntPtr.Zero) { GetDemultiplexedStub_f =(GetDemultiplexedStub) Marshal.GetDelegateForFunctionPointer(procAddr, typeof(GetDemultiplexedStub)); } procAddr = GetProcAddress(loadLibrary, "CreateInstanceEnumWmi"); if( procAddr != IntPtr.Zero) { CreateInstanceEnumWmi_f =(CreateInstanceEnumWmi) Marshal.GetDelegateForFunctionPointer(procAddr, typeof(CreateInstanceEnumWmi)); } procAddr = GetProcAddress(loadLibrary, "CreateClassEnumWmi"); if( procAddr != IntPtr.Zero) { CreateClassEnumWmi_f =(CreateClassEnumWmi) Marshal.GetDelegateForFunctionPointer(procAddr, typeof(CreateClassEnumWmi)); } procAddr = GetProcAddress(loadLibrary, "ExecQueryWmi"); if( procAddr != IntPtr.Zero) { ExecQueryWmi_f =(ExecQueryWmi) Marshal.GetDelegateForFunctionPointer(procAddr, typeof(ExecQueryWmi)); } procAddr = GetProcAddress(loadLibrary, "ExecNotificationQueryWmi"); if( procAddr != IntPtr.Zero) { ExecNotificationQueryWmi_f =(ExecNotificationQueryWmi) Marshal.GetDelegateForFunctionPointer(procAddr, typeof(ExecNotificationQueryWmi)); } procAddr = GetProcAddress(loadLibrary, "PutInstanceWmi"); if( procAddr != IntPtr.Zero) { PutInstanceWmi_f =(PutInstanceWmi) Marshal.GetDelegateForFunctionPointer(procAddr, typeof(PutInstanceWmi)); } procAddr = GetProcAddress(loadLibrary, "PutClassWmi"); if( procAddr != IntPtr.Zero) { PutClassWmi_f =(PutClassWmi) Marshal.GetDelegateForFunctionPointer(procAddr, typeof(PutClassWmi)); } procAddr = GetProcAddress(loadLibrary, "CloneEnumWbemClassObject"); if( procAddr != IntPtr.Zero) { CloneEnumWbemClassObject_f =(CloneEnumWbemClassObject) Marshal.GetDelegateForFunctionPointer(procAddr, typeof(CloneEnumWbemClassObject)); } procAddr = GetProcAddress(loadLibrary, "ConnectServerWmi"); if( procAddr != IntPtr.Zero) { ConnectServerWmi_f =(ConnectServerWmi) Marshal.GetDelegateForFunctionPointer(procAddr, typeof(ConnectServerWmi)); } } }
public bool Contains(IExpressionChain chain) { return(chain == null || (chain.Current.Equals(Current) && (chain.Next == null || (Next != null && Next.Contains(chain.Next))))); }
TreeNode(int item){ this.item = item; this.next = null; }
/// <summary> /// Get the element type of this iterator. /// </summary> /// <param name="node">Node to report diagnostics, if any, such as "yield statement cannot be used /// inside a lambda expression"</param> /// <param name="diagnostics">Where to place any diagnostics</param> /// <returns>Element type of the current iterator, or an error type.</returns> internal virtual TypeSymbol GetIteratorElementType(YieldStatementSyntax node, DiagnosticBag diagnostics) { return(Next.GetIteratorElementType(node, diagnostics)); }
TreeNode (Next next, int item) { this.next = next; this.item = item; }
public override Terminator <TReduction> Invoke(TReduction reduction, TInput value) => Test(value) ? Next.Invoke(reduction, value) : Reduction(reduction);
public double Satisfy (State s, Next next) { return Transitions.Where (t => t.From.Equals (s)) .Select (x => x.Probability * Satisfy (x.To, next.Enclosed)) .Sum (); }
/// <summary> /// Three cards with same value /// </summary> /// <param name="cards">The list of cards to check for a match</param> /// <returns>Boolean value indicating whether the given cards are a match</returns> public override Result IsMatch(List <Card> cards) { var groupedCards = cards.GroupBy(c => c.Rank); return(groupedCards.Any(g => g.Count() >= 3) ? new Result(cards, RuleName.ThreeOfAKind) : Next.IsMatch(cards)); }
void Awake() { instance = this; }
public override HandRank Catagorise(Hand hand) { return(hand.HasNoOfKind(2) ? HandRank.Pair : Next.Catagorise(hand)); }
private TreeNode(TreeNode left, TreeNode right, int item) { _next = new Next(); _next.left = left; _next.right = right; _item = item; }
public override async Task Invoke(IOwinContext context) { if (IsStorefrontRequest(context.Request)) { var workContext = _container.Resolve <WorkContext>(); var linkListService = _container.Resolve <IMenuLinkListService>(); var cartBuilder = _container.Resolve <ICartBuilder>(); var catalogSearchService = _container.Resolve <ICatalogSearchService>(); // Initialize common properties workContext.RequestUrl = context.Request.Uri; workContext.AllCountries = _allCountries; workContext.AllStores = await _cacheManager.GetAsync("GetAllStores", "ApiRegion", async() => await GetAllStoresAsync()); if (workContext.AllStores != null && workContext.AllStores.Any()) { // Initialize request specific properties workContext.CurrentStore = GetStore(context, workContext.AllStores); workContext.CurrentLanguage = GetLanguage(context, workContext.AllStores, workContext.CurrentStore); workContext.AllCurrencies = await _cacheManager.GetAsync("GetAllCurrencies-" + workContext.CurrentLanguage.CultureName, "ApiRegion", async() => { return((await _commerceApi.CommerceGetAllCurrenciesAsync()).Select(x => x.ToWebModel(workContext.CurrentLanguage)).ToArray()); }); //Sync store currencies with avail in system foreach (var store in workContext.AllStores) { store.SyncCurrencies(workContext.AllCurrencies, workContext.CurrentLanguage); store.CurrentSeoInfo = store.SeoInfos.FirstOrDefault(x => x.Language == workContext.CurrentLanguage); } //Set current currency workContext.CurrentCurrency = GetCurrency(context, workContext.CurrentStore); var qs = HttpUtility.ParseQueryString(workContext.RequestUrl.Query); //Initialize catalog search criteria workContext.CurrentCatalogSearchCriteria = new CatalogSearchCriteria(workContext.CurrentLanguage, workContext.CurrentCurrency, qs) { CatalogId = workContext.CurrentStore.Catalog }; //This line make delay categories loading initialization (categories can be evaluated on view rendering time) workContext.Categories = new MutablePagedList <Category>((pageNumber, pageSize) => { var criteria = workContext.CurrentCatalogSearchCriteria.Clone(); criteria.PageNumber = pageNumber; criteria.PageSize = pageSize; var result = catalogSearchService.SearchCategories(criteria); foreach (var category in result) { category.Products = new MutablePagedList <Product>((pageNumber2, pageSize2) => { criteria.CategoryId = category.Id; criteria.PageNumber = pageNumber2; criteria.PageSize = pageSize2; var searchResult = catalogSearchService.SearchProducts(criteria); //Because catalog search products returns also aggregations we can use it to populate workContext using C# closure //now workContext.Aggregation will be contains preloaded aggregations for current category workContext.Aggregations = new MutablePagedList <Aggregation>(searchResult.Aggregations); return(searchResult.Products); }); } return(result); }); //This line make delay products loading initialization (products can be evaluated on view rendering time) workContext.Products = new MutablePagedList <Product>((pageNumber, pageSize) => { var criteria = workContext.CurrentCatalogSearchCriteria.Clone(); criteria.PageNumber = pageNumber; criteria.PageSize = pageSize; var result = catalogSearchService.SearchProducts(criteria); //Prevent double api request for get aggregations //Because catalog search products returns also aggregations we can use it to populate workContext using C# closure //now workContext.Aggregation will be contains preloaded aggregations for current search criteria workContext.Aggregations = new MutablePagedList <Aggregation>(result.Aggregations); return(result.Products); }); //This line make delay aggregation loading initialization (aggregation can be evaluated on view rendering time) workContext.Aggregations = new MutablePagedList <Aggregation>((pageNumber, pageSize) => { var criteria = workContext.CurrentCatalogSearchCriteria.Clone(); criteria.PageNumber = pageNumber; criteria.PageSize = pageSize; //Force to load products and its also populate workContext.Aggregations by preloaded values workContext.Products.Slice(pageNumber, pageSize); return(workContext.Aggregations); }); workContext.CurrentOrderSearchCriteria = new Model.Order.OrderSearchCriteria(qs); workContext.CurrentQuoteSearchCriteria = new Model.Quote.QuoteSearchCriteria(qs); //Get current customer workContext.CurrentCustomer = await GetCustomerAsync(context); //Validate that current customer has to store access ValidateUserStoreLogin(context, workContext.CurrentCustomer, workContext.CurrentStore); MaintainAnonymousCustomerCookie(context, workContext); // Gets the collection of external login providers var externalAuthTypes = context.Authentication.GetExternalAuthenticationTypes(); workContext.ExternalLoginProviders = externalAuthTypes.Select(at => new LoginProvider { AuthenticationType = at.AuthenticationType, Caption = at.Caption, Properties = at.Properties }).ToList(); workContext.ApplicationSettings = GetApplicationSettings(); //Do not load shopping cart and other for resource requests if (!IsAssetRequest(context.Request)) { //Shopping cart await cartBuilder.GetOrCreateNewTransientCartAsync(workContext.CurrentStore, workContext.CurrentCustomer, workContext.CurrentLanguage, workContext.CurrentCurrency); workContext.CurrentCart = cartBuilder.Cart; if (workContext.CurrentStore.QuotesEnabled) { await _quoteRequestBuilder.GetOrCreateNewTransientQuoteRequestAsync(workContext.CurrentStore, workContext.CurrentCustomer, workContext.CurrentLanguage, workContext.CurrentCurrency); workContext.CurrentQuoteRequest = _quoteRequestBuilder.QuoteRequest; } var linkLists = await _cacheManager.GetAsync("GetAllStoreLinkLists-" + workContext.CurrentStore.Id, "ApiRegion", async() => await linkListService.LoadAllStoreLinkListsAsync(workContext.CurrentStore.Id)); workContext.CurrentLinkLists = linkLists.Where(x => x.Language == workContext.CurrentLanguage).ToList(); // load all static content var staticContents = _cacheManager.Get(string.Join(":", "AllStoreStaticContent", workContext.CurrentStore.Id), "ContentRegion", () => { var allContentItems = _staticContentService.LoadStoreStaticContent(workContext.CurrentStore).ToList(); var blogs = allContentItems.OfType <Blog>().ToArray(); var blogArticlesGroup = allContentItems.OfType <BlogArticle>().GroupBy(x => x.BlogName, x => x).ToList(); foreach (var blog in blogs) { var blogArticles = blogArticlesGroup.FirstOrDefault(x => string.Equals(x.Key, blog.Name, StringComparison.OrdinalIgnoreCase)); if (blogArticles != null) { blog.Articles = new MutablePagedList <BlogArticle>(blogArticles); } } return(new { Pages = allContentItems, Blogs = blogs }); }); workContext.Pages = new MutablePagedList <ContentItem>(staticContents.Pages); workContext.Blogs = new MutablePagedList <Blog>(staticContents.Blogs); // Initialize blogs search criteria workContext.CurrentBlogSearchCritera = new BlogSearchCriteria(qs); //Pricelists var pricelistCacheKey = string.Join("-", "EvaluatePriceLists", workContext.CurrentStore.Id, workContext.CurrentCustomer.Id); workContext.CurrentPricelists = await _cacheManager.GetAsync(pricelistCacheKey, "ApiRegion", async() => { var evalContext = new VirtoCommerceDomainPricingModelPriceEvaluationContext { StoreId = workContext.CurrentStore.Id, CatalogId = workContext.CurrentStore.Catalog, CustomerId = workContext.CurrentCustomer.Id, Quantity = 1 }; var pricingResult = await _pricingModuleApi.PricingModuleEvaluatePriceListsAsync(evalContext); return(pricingResult.Select(p => p.ToWebModel()).ToList()); }); } } } await Next.Invoke(context); }
private TreeNode(int item) { _item = item; _next = null; }
public Task <object> ExecuteAsync(object query, HttpQueryDispatcher dispatcher, Next next) { this.next = next; this.dispatcher = dispatcher; return(ExecuteNextAsync(query)); }
public override async Task Invoke(IOwinContext context) { int test = 1; try { OwinCallContext.Set(context); if (test == 1) { //validate token const string sec = "ProEMLh5e_qnzdNUQrqdHPgp"; const string sec1 = "ProEMLh5e_qnzdNU"; var securityKey = new SymmetricSecurityKey(Encoding.Default.GetBytes(sec)); var securityKey1 = new SymmetricSecurityKey(Encoding.Default.GetBytes(sec1)); // This is the input JWT which we want to validate. string tokenString = "eyJhbGciOiJBMTI4S1ciLCJlbmMiOiJBMTI4Q0JDLUhTMjU2IiwidHlwIjoiSldUIn0.tRxgOq6KhMF3iMMLvWA_nIIx3dk3vfUT_JqdcMBMsjEtsnlJPre2dg.pnsytilmOxuHyny47unEHg.7YAE4f0d9vg1W22NFn-yIo2VMKN6ICMyk0OUr0yCMPmgsCvpSxP-v4k_N61A_prrsPmrfxwi-MPgiYTRPbnh4-jUYYvAtqr2FctzOJJPR0Pt6MRtNh1gXzM1bI67HtDxcbxBg2K3QPj_gpnQUUON06kE9WRRnBjbM4AeAbNr12lKvnmnlC9Grurk0QTSzLwaolf3buXTmwl6kSka_WW66sHZL0RahT7pjT28r0GD5I9veZC5ZC0lzSFaprOjsy6FiZ5YpiV0L5aNZX7KhF1N8fnjuuhNKEugHpdW3cA4f-ehTu0EjiErESly7-TBcVHpjN3yevARV8iSkZY3GywZmw.MOaTPpkobSeKi0uvbO_mEw"; // If we retrieve the token without decrypting the claims, we won't get any claims // DO not use this jwt variable var jwt = new JwtSecurityToken(tokenString); // Verification var tokenValidationParameters = new TokenValidationParameters() { ValidAudiences = new string[] { "536481524875-glk7nibpj1q9c4184d4n3gittrt8q3mn.apps.googleusercontent.com" }, ValidIssuers = new string[] { "https://accounts.google.com" }, IssuerSigningKey = securityKey, // This is the decryption key TokenDecryptionKey = securityKey1 }; SecurityToken validatedToken; var handler = new JwtSecurityTokenHandler(); handler.ValidateToken(tokenString, tokenValidationParameters, out validatedToken); //end await Next.Invoke(context); } else { // create Jwt token var plainTextSecurityKey = "This is my shared, not so secret, secret!"; var signingKey = new InMemorySymmetricSecurityKey( Encoding.UTF8.GetBytes(plainTextSecurityKey)); var signingCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256Signature, SecurityAlgorithms.Sha256Digest); //end context.Response.StatusCode = (int)HttpStatusCode.OK; context.Response.ContentType = "application/json"; context.Response.Write(jwt.RawEncryptedKey.ToString()); } } catch (Exception ex) { throw ex; } finally { OwinCallContext.Remove(context); } }
public async override Task Invoke(IOwinContext context) { await Next.Invoke(context); }
public override CompileResult Compile() { var prevIsAddress = Prev.GetType() == typeof(ExcelAddressExpression); var prevIsOffset = Prev.GetType() == typeof(FunctionExpression) && ((FunctionExpression)Prev).ExpressionString.ToLower() == "offset"; var nextIsAddress = Next.GetType() == typeof(ExcelAddressExpression); var nextIsOffset = Next.GetType() == typeof(FunctionExpression) && ((FunctionExpression)Next).ExpressionString.ToLower() == "offset"; if (!prevIsAddress && !prevIsOffset) { return(new CompileResult(eErrorType.Value)); } if (!nextIsAddress && !nextIsOffset) { return(new CompileResult(eErrorType.Value)); } if (prevIsAddress && nextIsOffset) { return(InternalCompile(Prev.Compile().Result.ToString(), Next.Compile().Result as ExcelDataProvider.IRangeInfo)); } else if (prevIsOffset && nextIsAddress) { return(InternalCompile(Prev.Compile().Result as ExcelDataProvider.IRangeInfo, Next.Compile().Result.ToString())); } else if (prevIsOffset && nextIsOffset) { return(InternalCompile(Prev.Compile().Result as ExcelDataProvider.IRangeInfo, Next.Compile().Result as ExcelDataProvider.IRangeInfo)); } return(new CompileResult(eErrorType.Value)); }
public override void GenerateCode(GeneratedMethod method, ISourceWriter writer) { writer.Write($"var {Variable.Usage} = {_scope.Usage}.{nameof(Scope.GetInstance)}<{Variable.VariableType.FullNameInCode()}>(\"{_name}\");"); Next?.GenerateCode(method, writer); }
// Metoda, ve které se uskutečňuje pohyb agenta po hracím poli public void PohybujSe(int pocetBehu) { for (int b = 0; b < pocetBehu; b++) { // Pomocné pole pro uložení výsledku posunu agenta ve třídě POZICE int[] report_pomocna = new int[4]; // Do tohoto pole si uložím možné směry agenta, které zjišťuji v metodě expandujVrcholy int[] expanduj_pomocna = ExpandujVrcholy(agent.AktPozice[0], agent.AktPozice[1]); // Směr je nejprve na sever, protože směry v expanduj_pomocna jsou uloženy od severu int smer = 0; // Projdu všechny směry v expanduj_pomocna foreach (int i in expanduj_pomocna) { // Pokud je dany smer povoleny, tedy -- 1, tak se vytvori nova POZICE s hodnotami tohoto policka if (i == 1) { // Prozkoumám pozici daným směrem a získám report se vším potřebným pro vytvoření této pozice report_pomocna = agent.Pohyb(smer); // Výpočet heuristické funkce pro danou pozici // Vstupem je X -- Y -- aktuální cena cesty int celkovaCena = HeuristickaFunkce(report_pomocna[1], report_pomocna[2], report_pomocna[0]); // Přidání nalezené pozice do NEXT, tedy budoucích pozicí, kam je možné jít Next.Add(new Pozice(IDVrcholu, report_pomocna[0], report_pomocna[1], report_pomocna[2], report_pomocna[3], celkovaCena)); // Zvýším ID, aby další vrchol měl jedičné IDVrcholu++; // Porovnám pozice v NEXT podle celkové ceny cesty SESTUPNE IEnumerable <Pozice> zalozni = Next.OrderBy(a => a.CelkovaCenaCesty); Next = new List <Pozice>(); // Porovnanou kolekci si uložím z5 do původní, tedy do NEXT foreach (Pozice p in zalozni) { Next.Add(p); } } // Zvýším proměnnou směr, čímž půjdu na směr posunutý o 90° smer++; } // Do prozkoumaných pozic ve STACK si uložím současnou pozici agenta, tedy poslední prozkoumanou Stack.Add(agent); // Vezmu první pozici v NEXT, tedy ta s nejnižší celkovou cenou cesty agent = Next[0]; // Kontrola zda tato nová pozice, která se bude při dalším běhu této metody prozkoumávat není výherní if (Vyhra(agent.AktPozice[0], agent.AktPozice[1], b)) { break; } // Vykreslím hrací pole, kde pozici agenta znázorňuje prázdná pozice ZobrazHraciPole(agent.AktPozice[0], agent.AktPozice[1]); // Smažu pozici, kterou jsem si uložil do agenta z NEXT Next.RemoveAt(0); } Console.WriteLine("\n---------------STACK-----------------\n|X |Y |AktCena|CelkCena"); foreach (Pozice p in Stack) { Console.WriteLine(p); } Console.WriteLine("\n---------------NEXT-----------------\n|X |Y |AktCena|CelkCena"); foreach (Pozice p in Next) { Console.WriteLine(p); } Console.WriteLine("\n---------------AGENT-----------------\n|X |Y |AktCena|CelkCena"); Console.WriteLine(agent); }
private void RaiseNext() { Next?.Invoke(this, EventArgs.Empty); }
public object Clone() => new LinkedListNode <T>(Value, (LinkedListNode <T>)Next?.Clone());
public override void GenerateCode(GeneratedMethod method, ISourceWriter writer) { writer.Write($"{_endpoint.Usage}.{nameof(ControllerBase.ControllerContext)} = {_context.Usage};"); Next?.GenerateCode(method, writer); }
public float GetLength() { return((Previous.GetVector() - Next.GetVector()).Magnitude); }