internal static MethodInvoker Create(MethodInfo method, object target)
        {

            var args = new List<Type>(method.GetParameters().Select(p => p.ParameterType));
            Type delegateType;

            var returnMethodInvoker = new MethodInvoker
            {
                ParameterTypeList = args.ToList(),
                ParameterCount = args.Count,
                ReturnType = method.ReturnType,
                MethodName = method.Name
            };


            if (method.ReturnType == typeof(void))
            {
                delegateType = Expression.GetActionType(args.ToArray());
            }
            else
            {
                args.Add(method.ReturnType);
                delegateType = Expression.GetFuncType(args.ToArray());
            }

            returnMethodInvoker.MethodDelegate = method.CreateDelegate(delegateType, target);

            return returnMethodInvoker;

        }
        private async void GetEmotionDetails(SoftwareBitmap bitmap, List <Face> faces)
        {
            if (bitmap != null)
            {
                try
                {
                    using (var randomAccessStream = new InMemoryRandomAccessStream())
                    {
                        var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, randomAccessStream);

                        encoder.SetSoftwareBitmap(bitmap);
                        await encoder.FlushAsync();

                        randomAccessStream.Seek(0);

                        Emotion[] emotions = await _emotionServiceClient.RecognizeAsync(randomAccessStream.AsStream());

                        ProcessResults(faces?.ToArray(), emotions?.ToArray(), bitmap);
                    }
                }
                catch (Exception ex)
                {
                    Debug.WriteLine("GetEmotionDetails exception : " + ex.Message);
                    ProcessResults(faces?.ToArray(), null, bitmap);
                }
            }
        }
        public void JsonObjectConstructorParmsTest()
        {
            JsonObject target = new JsonObject();
            Assert.Equal(0, target.Count);

            string key1 = AnyInstance.AnyString;
            string key2 = AnyInstance.AnyString2;
            JsonValue value1 = AnyInstance.AnyJsonValue1;
            JsonValue value2 = AnyInstance.AnyJsonValue2;

            List<KeyValuePair<string, JsonValue>> items = new List<KeyValuePair<string, JsonValue>>()
            {
                new KeyValuePair<string, JsonValue>(key1, value1),
                new KeyValuePair<string, JsonValue>(key2, value2),
            };

            target = new JsonObject(items[0], items[1]);
            Assert.Equal(2, target.Count);
            ValidateJsonObjectItems(target, key1, value1, key2, value2);

            target = new JsonObject(items.ToArray());
            Assert.Equal(2, target.Count);
            ValidateJsonObjectItems(target, key1, value1, key2, value2);

            // Invalid tests
            items.Add(new KeyValuePair<string, JsonValue>(key1, AnyInstance.DefaultJsonValue));
            ExceptionHelper.Throws<ArgumentException>(delegate { new JsonObject(items[0], items[1], items[2]); });
            ExceptionHelper.Throws<ArgumentException>(delegate { new JsonObject(items.ToArray()); });
        }
Example #4
0
        public static string[] FindVars(string find, int max)
        {
            List<string> Ret = new List<string>();
            string[] Keys = (string[])CVars.Keys.ToArray();
            for (int x = 0; x < Keys.Length; x++)
            {
                if (Keys.Contains(find))
                {
                    foreach (string S in Keys)
                    {
                        if (S.Contains(find))
                        {
                            if (Ret.Count == max)
                                return Ret.ToArray();
                            Ret.Add(S);
                        }

                    }
                }
                else
                {
                    return new string[0];
                }
            }

            return Ret.ToArray();
        }
Example #5
0
        public static string[] GetValueListFromJSONArray(string jsonString)
        {
            List<string> valueList = new List<string>();

            if (string.IsNullOrEmpty(jsonString)
            || jsonString.Equals("null")
            )
                return valueList.ToArray();
            try
            {
                JArray jo = JArray.Parse(jsonString);
                foreach (JToken token in jo.Values())
                {
                    if (token.Type == JsonTokenType.String)
                        valueList.Add(token.Value<string>().Trim());
                }
            }
            catch (Exception e)
            {
                valueList.Add(jsonString);
                return valueList.ToArray();
            }

            return valueList.ToArray();
        }
Example #6
0
        public ActionResult log(int PageIndex = 0, int PageSize = 15, string Host = "", string Level = "ERROR", string kw = "")
        {
            ViewModel <log4netsyslog> vm = new ViewModel <log4netsyslog>();
            string filter = string.Empty;
            List <MySqlParameter> parameters = new List <MySqlParameter>();

            filter += " 1=1 ";
            if (!string.IsNullOrEmpty(Host))
            {
                filter += " and Host=@Host ";
                parameters.Add(new MySqlParameter("@Host", Host));
            }
            if (!string.IsNullOrEmpty(Level))
            {
                filter += " and Level=@Level ";
                parameters.Add(new MySqlParameter("@Level", Level));
            }
            if (!string.IsNullOrEmpty(kw))
            {
                filter += $" and ( msgbody like @kw or msgexception like @kw ) ";
                parameters.Add(new MySqlParameter("@kw", Core.MiniApp.Utils.FuzzyQuery(kw)));
            }

            vm.DataList   = log4netsyslogBLL.SingleModel.GetListByParam(filter, parameters?.ToArray(), PageSize, PageIndex, "*", " id desc");
            vm.PageSize   = PageSize;
            vm.PageIndex  = PageIndex;
            vm.TotalCount = log4netsyslogBLL.SingleModel.GetCount(filter, parameters?.ToArray());
            return(View(vm));
        }
        /// <summary>
        /// 구성 섹션 처리기를 만듭니다.
        /// </summary>
        /// <returns>
        /// 만들어진 섹션 처리기 개체입니다.
        /// </returns>
        /// <param name="parent">부모 개체입니다.</param><param name="configContext">구성 컨텍스트 개체입니다.</param>
        /// <param name="section">섹션 XML 노드입니다.</param>
        public object Create(object parent, object configContext, XmlNode section) {
            if(log.IsInfoEnabled)
                log.Info("MongoDB를 NHibernate 2nd 캐시로 사용하기 위해, 환경설정 값을 로드합니다...");

            var cacheConfigs = new List<RavenCacheConfig>();

            if(section == null)
                return cacheConfigs.ToArray();

            XmlNodeList nodes = section.SelectNodes(SR.NodeCache);

            if(nodes == null)
                return cacheConfigs.ToArray();

            foreach(XmlElement node in nodes) {
                var region = node.AttributeToString(SR.AttrRegion, SR.DefaultRegionName);
                var connectionString = node.AttributeToString(SR.AttrConnectionString, SR.DefaultConnectionString);
                var expiration = node.AttributeToString(SR.AttrExpiration, SR.DefaultExpiry.ToString());
                var compressThreshold = node.AttributeToString(SR.AttrCompressThreshold, "4096");

                if(IsDebugEnabled)
                    log.Debug("MongoDB를 이용한 NHibernate.Caches의 환경설정 정보. " +
                              @"region=[{0}],connectionString=[{1}], expiration=[{2}], compressThreshold=[{3}] bytes",
                              region, connectionString, expiration, compressThreshold);

                cacheConfigs.Add(new RavenCacheConfig(region, connectionString, expiration, compressThreshold));
            }

            if(IsDebugEnabled) {
                log.Debug("MongoDB를 NHibernate 2nd 캐시로 사용하기 위해, 환경설정 값을 모두 로드했습니다. ");
                cacheConfigs.ForEach(cfg => log.Debug(cfg));
            }

            return cacheConfigs.ToArray();
        }
    public static string GetCompactedJavaScript()
    {
        List<string> scripts = new List<string>();
        foreach (string script in SiteUtility.Scripts)
        {
            scripts.Add(HttpContext.Current.Request.MapPath(script));
        }

        // set to expire cache when any of the source files changes
        CacheDependency cacheDependency = new CacheDependency(scripts.ToArray());

        Cache cache = HttpRuntime.Cache;
        string cacheKey = "CompactedJavaScript";
        if (cache[cacheKey] != null)
        {
            return cache[cacheKey] as string;
        }

        StringBuilder sb = new StringBuilder();
        sb.AppendLine("/*  Generated " + DateTime.Now.ToUniversalTime().ToString("R", DateTimeFormatInfo.InvariantInfo) + "  */\n");
        sb.AppendLine(FileProcessor.Run(PackMode.JSMin, scripts.ToArray(), false));

        string output = sb.ToString();

        // hold for 30 minutes
        cache.Insert(cacheKey, output, cacheDependency, DateTime.Now.AddMinutes(30),
            Cache.NoSlidingExpiration, CacheItemPriority.Normal, null);

        return output;
    }
Example #9
0
        private Delegate CreateActionDelegate(MethodInfo method)
        {
            List<ParameterExpression> parameters = new List<ParameterExpression>();
            foreach (ParameterInfo parameterInfo in method.GetParameters())
            {
                parameters.Add(Expression.Parameter(parameterInfo.ParameterType, parameterInfo.Name));
            }

            LambdaExpression lambda;

            if (method.IsStatic)
            {
                lambda = Expression.Lambda(
                    GetActionType(parameters.Select(p => p.Type).ToArray()),
                    Expression.Call(method, parameters.Cast<Expression>().ToArray()),
                    parameters.ToArray());
            }
            else
            {
                Type bindingType = method.DeclaringType;
                Expression<Func<object>> getInstanceExpression =
                    () => ScenarioContext.Current.GetBindingInstance(bindingType);

                lambda = Expression.Lambda(
                    GetActionType(parameters.Select(p => p.Type).ToArray()),
                    Expression.Call(
                        Expression.Convert(getInstanceExpression.Body, bindingType),
                        method,
                        parameters.Cast<Expression>().ToArray()),
                    parameters.ToArray());
            }


            return lambda.Compile();
        }
Example #10
0
    public static int GetDockedVesselsCount(Vessel Vsl) {
      List<uint> MissionIds = new List<uint> ();
      ProtoPartSnapshot[] Parts = Vsl.protoVessel.protoPartSnapshots.ToArray();

      for (int i = 0; i < Parts.Length; i++) {
        uint missionId = Parts [i].missionID;
        bool found = false;
        for (int k = 0; k < MissionIds.ToArray ().Length; k++) {
          uint _missionId = MissionIds.ToArray () [k];
          if (missionId == _missionId) {
            found = true;
          }
        }

        if (!found) {
          MissionIds.Add (missionId);
        }
      }

      int missionCount = MissionIds.Count - 1;

      if (OnAstroid (Vsl)) {
        missionCount--;
      }

      return missionCount;
    }
        private static object[] GetInvokeParametersForMethod(MethodInfo methodInfo, IList<string> arguments)
        {
            var invokeParameters = new List<object>();
            var args = new List<string>(arguments);
            var methodParameters = methodInfo.GetParameters();
            bool methodHasParams = false;

            if (methodParameters.Length == 0) {
                if (args.Count == 0)
                    return invokeParameters.ToArray();
                return null;
            }

            if (methodParameters[methodParameters.Length - 1].ParameterType.IsAssignableFrom(typeof(string[]))) {
                methodHasParams = true;
            }

            if (!methodHasParams && args.Count != methodParameters.Length) return null;
            if (methodHasParams && (methodParameters.Length - args.Count >= 2)) return null;

            for (int i = 0; i < args.Count; i++) {
                if (methodParameters[i].ParameterType.IsAssignableFrom(typeof(string[]))) {
                    invokeParameters.Add(args.GetRange(i, args.Count - i).ToArray());
                    break;
                }
                invokeParameters.Add(Convert.ChangeType(arguments[i], methodParameters[i].ParameterType));
            }

            if (methodHasParams && (methodParameters.Length - args.Count == 1)) invokeParameters.Add(new string[] { });

            return invokeParameters.ToArray();
        }
Example #12
0
 public int copy_int(int state, int size, string name)
 {
     byte[] s;
     if (size < 2)
     {
         s = new byte[1];
         s[0] = (byte)state;
     }
     else
     {
         s = BitConverter.GetBytes(size == 1 ? (byte)state : (ushort)state);
     }
     name += ": ";
     var nameBytes = new UTF8Encoding().GetBytes(name);
     var list = new List<byte>();
     list.AddRange(nameBytes);
     list.AddRange(s);
     list.AddRange(new byte[] { (byte)'\n' });
     func(buf, list.ToArray(), (uint)list.ToArray().Length);
     if (size < 2)
     {
         return s[0];
     }
     else
     {
         return BitConverter.ToUInt16(s, 0);
     }
 }
Example #13
0
        public static string[] AssembleChunks(this List<string> s, int length)
        {
            if (s == null)
                return new string[0];

            var result = new List<string>();

            if (s == null || s.Count == 0)
                return result.ToArray();

            string line = null;

            foreach (var item in s)
            {
                if (item.Length < length)
                {
                    line += item;
                    result.Add(line);
                    line = null;
                }
                else
                    line += item;
            }

            if (line != null)
                result.Add(line);

            return result.ToArray();
        }
        public int Add(string input)
        {
            List<string> seperators = new List<string>() { ",", "\n" };

            // check for new seperators and add if need be
            if (input.StartsWith("//") && input[3] == '\n') {
                seperators.Add(input[2].ToString());
                input = input.Replace("//", "");
            }

            // get an empty string
            if (string.IsNullOrEmpty(input))
                return 0;
            // handle two numbers
            else if (input.Contains(seperators.ToArray()))
            {
                // do split method
                string[] numbers = input.Split(seperators.ToArray(),StringSplitOptions.RemoveEmptyEntries);
                int sum = 0;
                foreach (string num in numbers)
                {
                    sum += int.Parse(num);
                }
                return sum;

            }
            else // handle a single number
                return int.Parse(input);
        }
        public PartialViewResult FlashACard(string wantedDisplayDrug)
        {
            FlashDrugSetModel drugSetModel = new FlashDrugSetModel();

            List<Drug> myBrandSearch = new DrugCardsRepository().GetDrugBrand(wantedDisplayDrug);
            List<Drug> myGenericSearch = new DrugCardsRepository().GetDrugGeneric(wantedDisplayDrug);

            drugSetModel.currentArrayIndex = 0;
            List<string> resultInfo = new List<string>();

            if (myBrandSearch.Count > 0 )
            {
                drugSetModel.currentDisplayDrug = myBrandSearch.First();

                resultInfo.AddRange(myBrandSearch.Select(x => x.DrugBrand).ToList());
                drugSetModel.userDrugInfoArray = resultInfo.ToArray();
            }
            else if(myGenericSearch.Count>0)
            {
                drugSetModel.currentDisplayDrug = myGenericSearch.First();

                resultInfo.AddRange(myGenericSearch.Select(x => x.DrugBrand).ToList());
                drugSetModel.userDrugInfoArray = resultInfo.ToArray();
            }

            return PartialView("_FlashMyCard", drugSetModel);
        }
Example #16
0
        public override void ViewDidLoad()
        {
            base.ViewDidLoad ();

            TKChart chart = new TKChart (this.ExampleBounds);
            chart.AutoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight;
            this.View.AddSubview (chart);

            Random r = new Random ();
            List<CustomObject> data = new List<CustomObject> ();
            for (int i = 0; i < 5; i++) {
                CustomObject obj = new CustomObject () {
                    ObjectID = i,
                    Value1 = r.Next (100),
                    Value2 = r.Next (100),
                    Value3 = r.Next (100)
                };
                data.Add (obj);
            }

            chart.AddSeries (new TKChartAreaSeries (data.ToArray(), "ObjectID", "Value1"));
            chart.AddSeries (new TKChartAreaSeries (data.ToArray(), "ObjectID", "Value2"));
            chart.AddSeries (new TKChartAreaSeries (data.ToArray(), "ObjectID", "Value3"));

            TKChartStackInfo stackInfo = new TKChartStackInfo (new NSNumber (1), TKChartStackMode.Stack);
            for (int i = 0; i < chart.Series.Length; i++) {
                TKChartSeries series = chart.Series [i];
                series.SelectionMode = TKChartSeriesSelectionMode.Series;
                series.StackInfo = stackInfo;
            }

            chart.ReloadData ();
        }
        /// <summary>
        /// Frame the incoming data and raise the OnFrameReceived when the lastBuffer holds at least a frame type in the frames to listen to list.
        /// </summary>
        public void ProcessData(byte[] bytes)
        {
            lastBuffer.AddRange(bytes.ToList());
            List<byte> workingBuffer = new List<byte>();
            //Get all the bytes that constitute a whole frame
            var str = toStr(bytes);
            while (lastBuffer.IndexOf(frameSeparator) > 0)
            {
                if (lastBuffer.Count > lastBuffer.IndexOf(frameSeparator))
                    workingBuffer = lastBuffer.Take(lastBuffer.IndexOf(frameSeparator) + 1).ToList();
                else if (lastBuffer.Count == lastBuffer.IndexOf(frameSeparator))
                    workingBuffer = lastBuffer;


                if (workingBuffer.Count() > 0)
                {
                    foreach (var frame in Frames)
                    {
                        if (frame.IsFrameType(workingBuffer.ToArray()))
                        {
                            if (OnFrameReceived != null)
                                OnFrameReceived(frame.GetFrame(workingBuffer.ToArray()));
                        }
                    }
                    workingBuffer.Clear();
                }
                //Get the bytes from the last buffer that trail the last frame
                if (lastBuffer.IndexOf(frameSeparator) + 1 == lastBuffer.Count)
                    lastBuffer.Clear();
                else if (lastBuffer.IndexOf(frameSeparator) + 1 < lastBuffer.Count)
                    lastBuffer.RemoveRange(0, lastBuffer.IndexOf(frameSeparator) + 1);
            }
        }
Example #18
0
        /// <summary>
        /// Takes a list of metric strings, separating them with newlines into a byte packet of the maximum specified size.
        /// </summary>
        /// <param name="metrics">   	The metrics to act on. </param>
        /// <param name="packetSize">	Maximum size of each packet (512 bytes recommended for Udp). </param>
        /// <returns>	A streamed list of byte arrays, where each array is a maximum of 512 bytes. </returns>
        public static IEnumerable<byte[]> ToMaximumBytePackets(this IEnumerable<string> metrics, int packetSize)
        {
            List<byte> packet = new List<byte>(packetSize);

            foreach (string metric in metrics)
            {
                var bytes = Encoding.UTF8.GetBytes(metric);
                if (packet.Count + _terminator.Length + bytes.Length <= packetSize)
                {
                    packet.AddRange(bytes);
                    packet.AddRange(_terminator);
                }
                else if (bytes.Length >= packetSize)
                {
                    yield return bytes;
                }
                else
                {
                    yield return packet.ToArray();
                    packet.Clear();
                    packet.AddRange(bytes);
                    packet.AddRange(_terminator);
                }
            }

            if (packet.Count > 0)
            {
                yield return packet.ToArray();
            }
        }
Example #19
0
 internal static string ParseCPUTreeUsageInfo(List<string> processStrings, List<string> errorStrings)
 {
     if (processStrings.Count == 1) return processStrings[0];
     if (errorStrings.Count > 0 && errorStrings.Exists(s => s.Contains("NoSuchProcess"))) throw new InvalidOperationException("Process could not be found. Output from CPU sampler is:"+string.Join(",", processStrings.ToArray()));
     throw new ApplicationException(
         string.Format("Could not process cpu snapshot output. StdOutput: {0}, ErrOutput: {1}", string.Join(",", processStrings.ToArray()), string.Join(",", errorStrings.ToArray())));
 }
Example #20
0
    static void Main(string[] args)
    {
        List<double> results;
        List<double> modularity;
        string line = "";
        System.IO.File.Delete(Properties.Settings.Default.ResultFile);

        for (double mod = Properties.Settings.Default.Modularity_From; mod <= Properties.Settings.Default.Modularity_To; mod += Properties.Settings.Default.Modularity_Step)
        {
                Console.WriteLine();
                line = "";
                for(double bias = Properties.Settings.Default.bias_from; bias <= Properties.Settings.Default.bias_to; bias += Properties.Settings.Default.bias_step)
                {
                    results = new List<double>();
                    modularity = new List<double>();
                    System.Threading.Tasks.Parallel.For(0, Properties.Settings.Default.runs, j =>
                    {
                        ClusterNetwork net = new ClusterNetwork(Properties.Settings.Default.Nodes, Properties.Settings.Default.Edges, Properties.Settings.Default.Clusters, mod);

                        Console.WriteLine("Run {0}, created cluster network with modularity={1:0.00}", j, (net as ClusterNetwork).NewmanModularityUndirected);
                        /// TODO: Run experiment
                    });
                    line = string.Format(new CultureInfo("en-US").NumberFormat, "{0:0.000} {1:0.000} {2:0.000} {3:0.000} \t", MathNet.Numerics.Statistics.Statistics.Mean(modularity.ToArray()), bias, MathNet.Numerics.Statistics.Statistics.Mean(results.ToArray()), MathNet.Numerics.Statistics.Statistics.StandardDeviation(results.ToArray()));
                    System.IO.File.AppendAllText(Properties.Settings.Default.ResultFile, line + "\n");
                    Console.WriteLine("Finished spreading on cluster network for modularity = {0:0.00}, bias = {1:0.00}, Average = {2:0.00}", mod, bias, MathNet.Numerics.Statistics.Statistics.Mean(results.ToArray()));
                }
                System.IO.File.AppendAllText(Properties.Settings.Default.ResultFile, "\n");
        }
    }
Example #21
0
        public void ArrayLiterals()
        {
            //You don't have to specify a type if the arguments can be inferred
            var array = new [] { 42 };
            Assert.Equal(typeof(int[]), array.GetType());
            Assert.Equal(new int[] { 42 }, array);

            //Are arrays 0-based or 1-based?
            Assert.Equal(42, array[((int)0)]);

            //This is important because...
            Assert.True(array.IsFixedSize);

            //...it means we can't do this: array[1] = 13;
            Assert.Throws(typeof(IndexOutOfRangeException), delegate() { array[1] = 13; });

            //This is because the array is fixed at length 1. You could write a function
            //which created a new array bigger than the last, copied the elements over, and
            //returned the new array. Or you could do this:
            List<int> dynamicArray = new List<int>();
            dynamicArray.Add(42);
            Assert.Equal(array, dynamicArray.ToArray());

            dynamicArray.Add(13);
            Assert.Equal((new int[] { 42, (int)13}), dynamicArray.ToArray());
        }
        public List<CurrencyBlacklist> GetList(string currencyNumber, Pagination paging)
        {
            string sql = null;
            List<DbParameter> parameterList = new List<DbParameter>();

            sql = " select PkId, CurrencyKindCode, FaceAmount, CurrencyVersion, CurrencyNumber from tbl_currency_blacklist where 1=1 ";

            if (currencyNumber.IsNotNullOrEmpty())
            {
                sql += " and CurrencyNumber like concat(\'%\', {0}, \'%\') ".FormatWith("@CurrencyNumber");

                parameterList.Add(new MySqlParameter("@CurrencyNumber", currencyNumber));
            }

            if (paging != null)
            {
                return DbHelper.ExecutePagingList<CurrencyBlacklist>(sql, paging, parameterList.ToArray());
            }

            else
            {
                sql += " order by PkId desc ";

                return DbHelper.ExecuteList<CurrencyBlacklist>(sql, CommandType.Text, parameterList.ToArray());
            }
        }
        public static void PurgeAllMessages(IEnumerable<AzureMessageQueue> monitorQueues)
        {
            List<Task> tasks = new List<Task>();

              foreach( var queue in monitorQueues ) {

            if( AzureServiceBusReceiver.GetAzureQueueCount(queue.Queue.Name) > 0 ) {
              tasks.Add(Task.Factory.StartNew(() => {
            try {
              _log.Trace("Purging Queue {0}...".With(queue.Queue.Name));
              queue.Purge();
              _log.Trace("Finished Purging Queue " + queue.Queue.Name);

            } catch(Exception ex) {
              _log.Error("Error when Purgin queue {0}, {1}".With(queue.Queue.Name, ex));
            }
              }));
              Thread.Sleep(500);
            }

            if( tasks.Count > 0 && ( tasks.Count % 15) == 0 ) {
              Task.WaitAll(tasks.ToArray());
              tasks.Clear();
            }
              }

              if( tasks.Count > 0 )
            Task.WaitAll(tasks.ToArray());
        }
Example #24
0
  static void Main()
  {
    Solver solver = new Google.OrTools.ConstraintSolver.Solver("p");

    // creating dummy variables
    List<IntVar> vars = new List<IntVar>();
    for (int i = 0; i < 200000; i++)
    {
      vars.Add(solver.MakeIntVar(0, 1));
    }

    IntExpr globalSum = solver.MakeSum(vars.ToArray());

    DecisionBuilder db = solver.MakePhase(
        vars.ToArray(),
        Google.OrTools.ConstraintSolver.Solver.INT_VAR_SIMPLE,
        Google.OrTools.ConstraintSolver.Solver.INT_VALUE_SIMPLE);

    solver.NewSearch(db, new OptimizeVar(solver, true, globalSum.Var(), 100));

    GC.Collect();
    GC.WaitForPendingFinalizers();

    while (solver.NextSolution())
    {
      Console.WriteLine("solution " + globalSum.Var().Value());
    }
    Console.WriteLine("fini");
    Console.ReadLine();
  }
 public string[] readFile(string filePath)
 {
     StreamReader sr = new StreamReader(filePath);
     List<string> list = new List<string> { };
     try
     {
         string aLine = "";
         while (aLine != null)
         {
             aLine = sr.ReadLine();
             list.Add(aLine);
         }
         list.RemoveAt(list.Count - 1);
         return list.ToArray();
     }
     catch
     {
         list.Add("nothing");
         return list.ToArray();
     }
     finally
     {
         sr.Close();
     }
 }
Example #26
0
 private static string[] GetAllFiles(DirectoryInfo directory, string extension)
 {
     List<string> allFiles = new List<string>();
     DirectoryInfo[] allDirectory = directory.GetDirectories();
     if (allDirectory.Length > 0)
     {
         foreach (string[] files in allDirectory.Select(single => GetAllFiles(single, extension)))
         {
             allFiles.AddRange(files);
         }
         FileInfo[] fileInfos = directory.GetFiles();
         allFiles.AddRange(from file in fileInfos
                           where file.Extension.ToLower().Equals(extension)
                           select file.FullName);
         return allFiles.ToArray();
     }
     else
     {
         FileInfo[] files = directory.GetFiles();
         allFiles.AddRange(from file in files
                           where file.Extension.ToLower().Equals(extension)
                           select file.FullName);
         return allFiles.ToArray();
     }
 }
        public short[] GetAppliedMigrationVersions(string scope)
        {
            var shortList = new List<short>();

            if (string.IsNullOrEmpty(scope))
            {
                var list1 = _databaseProvider.ExecuteScalarArray<long>(
                        "SELECT {1} FROM {0} WHERE {2} IS NULL ORDER BY {1}",
                        TableName, VersionColumnName, ScopeColumnName);

                foreach (var item in list1)
                {
                    shortList.Add((short) item);
                }

                return shortList.ToArray();
            }

            var list2 = _databaseProvider.ExecuteScalarArray<long>(
                    "SELECT {1} FROM {0} WHERE {2} = '{3}' ORDER BY {1}",
                    TableName, VersionColumnName, ScopeColumnName, scope);

            foreach (var item in list2)
            {
                shortList.Add((short)item);
            }

            return shortList.ToArray();
        }
Example #28
0
        public ModelQty[] GetModelQty()
        {

            string methodName = System.Reflection.MethodBase.GetCurrentMethod().Name;
            IList<ModelQty> ret = new List<ModelQty>();
            DateTime now = new DateTime(2014, 1, 1);
            Random rnd = new Random();            
            try
            {

                //1.检查传进来的参数
                //Execute.ValidateParameter(CustSN);

                //2.获取DB中的数据
                //ModelResponse modelReponse = Execute.modelResponseMsg(CustSN);

                //logger.DebugFormat("Reponse data:{0}", modelReponse.ToString());
                for (int i = 0; i <= 100; ++i)
                {
                    ret.Add(new ModelQty { Qty = rnd.Next(0, 200), Date = now.AddDays(i) });
                }
                return ret.ToArray();
            }
            catch (Exception e)
            {              

                ret.Add(new ModelQty { Qty = 0, Date = now });
                return ret.ToArray();
            }
            finally
            {
               
            }
        }
    public string[] GetEmployee(string prefixText, int count)
    {
        MatterView BEL = new MatterView();
        DataTable dt = BEL.SelectLikeDataAssignedLawyer(prefixText.ToUpper());

        List<string> txtItems = new List<string>();
        String dbValues;
        String dbValues1;

        foreach (DataRow row in dt.Rows)
        {
            //String From DataBase(dbValues)
            dbValues1 = row["Employee_Id"].ToString().ToUpper();
            dbValues = row["UserName"].ToString().ToUpper();
            dbValues = dbValues.ToUpper();
            txtItems.Add(string.Format("{0} {1}", dbValues1, dbValues));
            // txtItems.Add(dbValues,);

            if (txtItems.Count > count)
            {
                return txtItems.ToArray();
            }
        }

        return txtItems.ToArray();
    }
Example #30
0
        public object Evaluate(IBindingEnvironment environment)
        {
            ICallable callable = (ICallable)environment.GetValue(this.name);

            if (callable == null)
                callable = (ICallable)Machine.Current.Environment.GetValue(this.name);

            List<object> parameters = new List<object>();

            foreach (IExpression expression in this.arguments)
            {
                object parameter = expression.Evaluate(environment);

                if (expression is VariableVariableExpression)
                {
                    if (parameter != null)
                        foreach (object obj in (IEnumerable)parameter)
                            parameters.Add(obj);
                }
                else
                    parameters.Add(parameter);
            }

            if (callable is ILocalCallable)
                return callable.Invoke(environment, parameters.ToArray());

            return callable.Invoke(parameters.ToArray());
        }
		protected override void InitializeInternal()
		{
			var name = new List<byte>();
			var data = new List<byte>();
			bool isName = true;
			foreach (var singleByte in _content.ToArray())
			{
				if (singleByte == '=')
				{
					isName = false;
				}
				else if (singleByte == '&')
				{
					isName = true;
					this[_encoding.GetString(name.ToArray())] = _encoding.GetString(data.ToArray());
					name.Clear();
					data.Clear();
				}
				else
				{
					if (isName)
					{
						name.Add(singleByte);
					}
					else
					{
						data.Add(singleByte);
					}
				}
			}
			if (data.Count > 0 && name.Count > 0)
			{
				this[_encoding.GetString(name.ToArray())] = _encoding.GetString(data.ToArray());
			}
		}
Example #32
0
 private void button1_Click(object sender, EventArgs e)
 {
     Int32 i = 0;
     richTextBox1.Text = "";
     //HuffmanTree htree = new HuffmanTree();
     htree.Build(textBox1.Text);
     encoded = htree.Encode(textBox1.Text);
     MessageBox.Show("Закодировано");
     foreach (bool bit in encoded)
     {
         richTextBox1.Text += ((bit ? 1 : 0).ToString() + " ");
     }
     foreach (KeyValuePair<char, int> item in htree.Frequencies)
     {
         Debug.Assert( richTextBox3 != null, "richTextBox3 != null" );
         List<String> list = new List<String>();
         foreach (String s in htree.Codec)
         {
             list.Add( s );
         }
         if (list.ToArray().Length > i)
         {
             richTextBox3.Text += (@"Символ: " + item.Key + @"	Количество: " + item.Value.ToString() + @"	Частота: " + Round( value: (float)item.Value / textBox1.Text.Length, digits: 3) + @"	Код " + list.ToArray()[i] + "\n");
         }
         Int32 i1 = i++;
     }
     String originalText = textBox1.Text;
     int countSimbol = originalText.Length;
     int summ = countSimbol * 8;
     textBox2.Text = Convert.ToString(summ);        
     
 }
Example #33
0
File: Tile.cs Project: MK4H/MHUrho
        /// <inheritdoc />
        public void SetBuilding(IBuilding building)
        {
            if (Building != null && building != Building)
            {
                throw new InvalidOperationException("There is a building already on this tile");
            }
            //Enumerate on a copy because some units may be destroyed during the enumeration
            foreach (var unit in units?.ToArray() ?? Enumerable.Empty <IUnit>())
            {
                unit.BuildingBuilt(building, this);
            }

            Building = building;
        }
Example #34
0
        public EmptyResult ExecuteCommand(bool keepConnectionOpen = false)
        {
            var result = executeInternal <object>((connection) =>
            {
                connection.ExecuteCommand(_sqlCommand, base.getTimeout(), _parameters?.ToArray());

                return(null);
            }, keepConnectionOpen);

            return(new EmptyResult()
            {
                Exception = result.Exception
            });
        }
Example #35
0
        public int RunModule(
            [Operand(Name = "module-name", Description = "The name of the module.")] string moduleName,
            [Option(LongName = "plugin")] List <string> pluginListOverride,
            [Option(LongName = "param", ShortName = "p")] List <string> moduleSettingOverrides)
        {
            var commandContext = CommandLineHandler.Context;

            if (string.IsNullOrEmpty(moduleName))
            {
                CommandLineHandler.DisplayHelp("run module");
                return((int)ExecutionResult.HostArgumentError);
            }

            commandContext.Logger.Information("loading module {Module}", moduleName);

            var loadResult = ModuleLoader.LoadModule(commandContext, moduleName, moduleSettingOverrides?.ToArray(), pluginListOverride?.ToArray(), false, out var module);

            if (loadResult != ExecutionResult.Success)
            {
                return((int)loadResult);
            }

            var executionResult = ExecutionResult.Success;

            if (module.EnabledPlugins.Count > 0)
            {
                executionResult = ModuleExecuter.Execute(commandContext, module);
            }

            ModuleLoader.UnloadModule(commandContext, module);

            return((int)executionResult);
        }
Example #36
0
        private CollisionPointStructure ExecuteEPAEngine(
            GJKOutput gjkOutput,
            VertexProperties[] vertexObjA,
            VertexProperties[] vertexObjB,
            int ID_A,
            int ID_B)
        {
            EPAOutput epaOutput = compenetrationEngine.Execute(
                vertexObjA,
                vertexObjB,
                gjkOutput.SupportTriangles,
                gjkOutput.Centroid);

            if (epaOutput.CollisionPoint.CollisionNormal.Length() < normalTolerance)
            {
                return(null);
            }

            List <CollisionPoint> collisionPointsList = null;

            collisionPointsList = manifoldEPAPointsGenerator.GetManifoldPoints(
                Array.ConvertAll(vertexObjA, x => x.Vertex),
                Array.ConvertAll(vertexObjB, x => x.Vertex),
                epaOutput.CollisionPoint);

            var collisionPointBaseStr = new CollisionPointBaseStructure(
                epaOutput.CollisionPoint,
                collisionPointsList?.ToArray());

            return(new CollisionPointStructure(
                       ID_A,
                       ID_B,
                       collisionPointBaseStr));
        }
Example #37
0
        public static int[] bestSum(int targetSum, int[] numbers)
        {
            if (targetSum == 0)
            {
                return(Array.Empty <int>());
            }
            if (targetSum < 0)
            {
                return(null);
            }
            List <int> shortestCombination = null;

            foreach (var num in numbers)
            {
                List <int> combination     = new List <int>();
                var        remainder       = targetSum - num;
                var        remainderResult = bestSum(remainder, numbers);
                if (remainderResult != null)
                {
                    combination.AddRange(remainderResult);
                    combination.Add(num);
                    if (shortestCombination == null || combination.Count < shortestCombination.Count)
                    {
                        shortestCombination = combination;
                    }
                }
            }
            return(shortestCombination?.ToArray());
        }
Example #38
0
        private (MessageLogger[] MessageLoggers, ScopeLogger[] ScopeLoggers) ApplyFilters(LoggerInformation[] loggers)
        {
            var messageLoggers = new List <MessageLogger>();
            List <ScopeLogger> scopeLoggers = _filterOptions.CaptureScopes ? new List <ScopeLogger>() : null;

            foreach (LoggerInformation loggerInformation in loggers)
            {
                RuleSelector.Select(_filterOptions,
                                    loggerInformation.ProviderType,
                                    loggerInformation.Category,
                                    out LogLevel? minLevel,
                                    out Func <string, string, LogLevel, bool> filter);

                if (minLevel != null && minLevel > LogLevel.Critical)
                {
                    continue;
                }

                messageLoggers.Add(new MessageLogger(loggerInformation.Logger, loggerInformation.Category, loggerInformation.ProviderType.FullName, minLevel, filter));

                if (!loggerInformation.ExternalScope)
                {
                    scopeLoggers?.Add(new ScopeLogger(logger: loggerInformation.Logger, externalScopeProvider: null));
                }
            }

            if (_scopeProvider != null)
            {
                scopeLoggers?.Add(new ScopeLogger(logger: null, externalScopeProvider: _scopeProvider));
            }

            return(messageLoggers.ToArray(), scopeLoggers?.ToArray());
        }
Example #39
0
        public ExtendTypeInfo(Type type, BindingFlags bindingFlag)
        {
            //TypeFullName = type.FullName;
            Type         = type;
            Constructors = type.GetConstructors(ReflectionHelper.ms_SearchFlagDefault)?.ToArray() ??
                           EmptyArrays.ConstructorInfo;
            Constructor = GetConstructor(Constructors);
            var c = string.Empty.ToArray();

            ConstructorParameters = Constructor?.GetParameters() ??
                                    EmptyArrays.ParameterInfo;
            ConstructorArgs = ConstructorParameters.Length > 0 ?
                              new object[ConstructorParameters.Length] : EmptyArrays.@object;
            for (var i = 0; i < ConstructorParameters.Length; i++)
            {
                ConstructorArgs[i] = ReflectionHelper.CreateInstance(ConstructorParameters[i].ParameterType);
            }
            Members = type.GetMembers(bindingFlag)?.ToArray() ??
                      EmptyArrays.MemberInfo;
            Properties = Members?.OfType <PropertyInfo>()?.ToArray() ??
                         EmptyArrays.PropertyInfo;
            Fields = Members?.OfType <FieldInfo>()?.ToArray() ??
                     EmptyArrays.FieldInfo;
            var variableList = new List <MemberInfo>(Properties);

            variableList.AddRange(Fields);
            Variables = variableList?.ToArray() ?? EmptyArrays.MemberInfo;
            Methods   = Members?.OfType <MethodInfo>()?.ToArray() ??
                        EmptyArrays.MethodInfo;
            Events = Members?.OfType <EventInfo>()?.ToArray() ??
                     EmptyArrays.EventInfo;
        }
Example #40
0
 /// <summary>
 /// 获取文件服务器列表
 /// </summary>
 /// <returns>文件服务器列表</returns>
 public static FileServerItem[] GetFileServers()
 {
     lock (_root)
     {
         return(fileServers?.ToArray());
     }
 }
Example #41
0
        private void LoadPlugins(GameController gameController)
        {
            var pluginLoader = new PluginLoader(_gameController, _graphics, this);

            var pluginUpdateSettings = SettingsContainer.LoadSettingFile <PluginsUpdateSettings>(AutoPluginUpdateSettingsPath);

            var loadPluginTasks = new List <Task <List <PluginWrapper> > >();

            if (pluginUpdateSettings != null)
            {
                loadPluginTasks.AddRange(RunPluginAutoUpdate(pluginLoader, pluginUpdateSettings));
            }
            loadPluginTasks.AddRange(LoadCompiledDirPlugins(pluginLoader, pluginUpdateSettings));

            Task.WaitAll(loadPluginTasks?.ToArray());

            Plugins = loadPluginTasks
                      .Where(t => t.Result != null)
                      .SelectMany(t => t.Result)
                      .OrderBy(x => x.Order)
                      .ThenByDescending(x => x.CanBeMultiThreading)
                      .ThenBy(x => x.Name)
                      .ToList();

            AddPluginInfoToDevTree();

            InitialisePlugins(gameController);

            AreaOnOnAreaChange(gameController.Area.CurrentArea);
            AllPluginsLoaded = true;
        }
Example #42
0
        public override SubEntity Build()
        {
            if (_rel == null || !_rel.Any())
            {
                throw new ArgumentException("Rel is required.");
            }

            var subEntity = new SubEntity()
            {
                Class      = _class?.ToArray(),
                Rel        = _rel?.ToArray(),
                Properties = _properties?.ToDictionary(kvp => kvp.Key, kvp => kvp.Value),
                Entities   = _subEntityBuilders?.Select(x => x.Build()).ToArray(),
                Links      = _linkBuilders?.Select(x => x.Build()).ToArray(),
                Actions    = _actionBuilders?.Select(x => x.Build()).ToArray(),
                Title      = _title
            };

            if (subEntity.Actions != null && new HashSet <string>(subEntity.Actions.Select(x => x.Name)).Count != subEntity.Actions.Count)
            {
                throw new ArgumentException("Action names MUST be unique within the set of actions for an entity.");
            }

            return(subEntity);
        }
Example #43
0
        private Reinf.Irko.ResultadoGravarRetornoEvento GravarEnvio(XmlNode _retorno, List <string> _listaId, string _cnpj, string _tipo)
        {
            XmlDocument _xml = new XmlDocument();

            _xml.LoadXml(_retorno.OuterXml);

            XmlElement _root = _xml.DocumentElement;

            String _xmlns = _root.Attributes["xmlns"].Value;

            String [] _versao = _xmlns.Split('/');

            Reinf.Irko.RetornoXML _parametro = new Reinf.Irko.RetornoXML
            {
                Empresa = new Reinf.Irko.Empresa()
                {
                    Codigo = GetDesktop().GetEmpresa().Codigo, StatusSpecified = false
                },
                Usuario = new Reinf.Irko.Usuario()
                {
                    Codigo = GetDesktop().GetUsuario().Codigo, DataInicio = DateTime.Now, StatusSpecified = false
                },
                DataProcessamento = DateTime.Now,
                ArquivoXML        = _retorno.OuterXml,
                Ids    = _listaId?.ToArray(),
                Versao = _versao[5]
            };

            Reinf.Irko.ResultadoGravarRetornoEvento _retornoWR = wrReinf.GravarRetornoEvento(Guid, _parametro, _tipo);
            return(_retornoWR);
        }
Example #44
0
		private void ProcessPath(string path)
		{
			if (path.StartsWith("/"))
				path = path.Substring(1);

			if (path.Contains("{"))
			{
				var match = Regex.Match(path, @"([^\/]+)", RegexOptions.Compiled);

				if (match.Success)
				{
					List<string> args = null;

					path = "";
					for (; match != null && match.Success; match = match.NextMatch())
					{
						if (match.Value.StartsWith("{"))
						{
							args = args ?? new List<string>();
							args.Add(match.Value.Substring(1, match.Value.Length - 2));
						}
						else if (args == null)
						{
							path += match.Value + "/";
						}
					}

					this.Args = args?.ToArray();
				}
			}

			this.Path = path;
		}
Example #45
0
        private void FindDlls()
        {
            SVClas.Msg = string.Empty;
            List <string> fnames = new List <string>();

            var mlsl = OSync.FileReadList();

            if (mlsl != null && mlsl.Count > 0)
            {
                for (int i = 0; i < mlsl.Count; i++)
                {
                    fnames.Add(mlsl[i].ModName);
                }
            }

            if (!(fnames?.Count > 0))
            {
                SVClas.Dlls = new string[] { "There are no dlls in ↓", FDPath }
            }
            ;
            else
            {
                SVClas.Dlls = fnames?.ToArray();
            }
        }
Example #46
0
        private TaskField[] GetSurroundingFields(Messages.GameMaster.IConnection connection, IPlayer player)
        {
            var gameState  = connection.GameState;
            var location   = player.Location;
            var taskFields = new List <TaskField>();

            for (int i = -1; i <= 1; i++)
            {
                for (int j = -1; j <= 1; j++)
                {
                    if (location.x + i < 0 || location.x + i >= gameState.BoardWidth ||
                        location.y + j < 0 || location.y + j >= (gameState.TaskAreaLength + gameState.GoalAreaLength * 2))
                    {
                        continue;
                    }
                    if (gameState.BoardList[(int)location.x + i][(int)location.y + j] is Xsd2.TaskField)
                    {
                        //Console.WriteLine(" my location x is: " + location.x + " y is: " + location.y);
                        taskFields.Add(gameState.BoardList[(int)location.x + i][(int)location.y + j] as TaskField);
                    }
                }
            }

            return(taskFields?.ToArray());
        }
        public WeatherForecastMapper()
        {
            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
            List <Workflow>?workflow = JsonConvert.DeserializeObject <List <Workflow> >(GetFileText());

            _rulesEngine = new RulesEngine.RulesEngine(workflow?.ToArray());
        }
Example #48
0
 public PacketWaitEntry[] GetEntries()
 {
     lock ( _waitEntryLock )
     {
         return(_waitEntries?.ToArray());
     }
 }
Example #49
0
        public InstructionArray ToArray()
        {
#if STATS
            lock (_executedInstructions)
            {
                _instructions.ForEach((instr) =>
                {
                    int value = 0;
                    var name  = instr.GetType().Name;
                    _executedInstructions.TryGetValue(name, out value);
                    _executedInstructions[name] = value + 1;

                    Dictionary <object, bool> dict;
                    if (!_instances.TryGetValue(name, out dict))
                    {
                        _instances[name] = dict = new Dictionary <object, bool>();
                    }
                    dict[instr] = true;
                });
            }
#endif
            return(new InstructionArray(
                       _maxStackDepth,
                       _maxContinuationDepth,
                       _instructions.ToArray(),
                       _objects?.ToArray(),
                       BuildRuntimeLabels(),
                       _debugCookies
                       ));
        }
Example #50
0
            public ElementMetadata Build()
            {
                var schema = _localName is null ? null : new SchemaAttrAttribute(_nsId, _localName);
                var lookup = _children is null ? _lazy : new Lazy <ElementLookup>(() => new ElementLookup(_children.Select(c => c.Build())), true);

                return(new ElementMetadata(BuildAttributes(), GetValidators(), _constraints?.ToArray(), Availability, schema, Particle.Compile(), lookup));
            }
Example #51
0
        /// <summary>
        /// Updates the specified recipe in the database.
        /// </summary>
        /// <param name="recipe">The recipe to update in the database.</param>
        /// <returns>Returns whether or not the required queries were successful.</returns>
        public static async Task <QueryResult[]> UpdateRecipe(FullRecipe recipe)
        {
            List <QueryResult> allResults = null;

            try
            {
                //Updates the basic info of the recipe & deletes all recipe links temporarily
                allResults = new List <QueryResult>
                {
                    await App.ExecuteQuery(
                        "update Rezepte " +
                        $"set Gerichtname = '{recipe.Name}', Zubereitung = '{recipe.Preparation}' " +
                        $"where ID = {recipe.ID}"),
                    await App.ExecuteQuery($"delete from Rezeptzutatenliste where IDRezepte = {recipe.ID}")
                };

                //Updates the ingredient links of the recipe
                for (int i = 0; i < recipe.LinkedIngredients.Count; i++)
                {
                    allResults.Add(await App.ExecuteQuery(
                                       "insert into Rezeptzutatenliste(IDRezepte, IDZutaten, Menge, Notiz) " +
                                       $"values({recipe.ID}, " +
                                       $"{recipe.LinkedIngredients[i].ID}, " +
                                       $"'{recipe.LinkedIngredients[i].Amount}', " +
                                       $"'{recipe.LinkedIngredients[i].Note}')"));
                }
            }
            catch (Exception)
            {
                //Ignore
            }

            return(allResults?.ToArray());
        }
Example #52
0
        public void Oldvert()
        {
            verts    = Vertices.ToArray();
            normals  = Normals.ToArray();
            texts    = TexCoords.ToArray();
            tangents = Tangents != null?Tangents.ToArray() : TangentsFor(verts, normals, texts);

            v4_colors  = Colors?.ToArray();
            v4_tcolors = TCOLs?.ToArray();
            v4_thvs    = THVs?.ToArray();
            v4_thws    = THWs?.ToArray();
            v4_thvs2   = THVs2?.ToArray();
            v4_thws2   = THWs2?.ToArray();
            Vertices   = null;
            Normals    = null;
            TexCoords  = null;
            Tangents   = null;
            Colors     = null;
            TCOLs      = null;
            THVs       = null;
            THWs       = null;
            THVs2      = null;
            THWs2      = null;
            // TODO: Other arrays?
        }
Example #53
0
        //get single osu beatmap
        public WorkingBeatmap GetWorkingBeatmap(int rulesetID = 0, bool useFake = false, int beatmapIndex = 0, List <Mod> listMops = null)
        {
            WorkingBeatmap beatmap = null;

            var beatmapInfo = db.Query <BeatmapInfo>().FirstOrDefault(b => b.RulesetID == rulesetID);

            if (beatmapInfo != null)
            {
                beatmap = db.GetWorkingBeatmap(beatmapInfo);
            }

            //if cannot find any beatmap ,or use fake beatmap just create one
            if (beatmap?.Track == null || useFake)
            {
                beatmap = new RpTestWorkingBeatmap(getFakeBeatmapByRulesetId(rulesetID));
            }

            //adding Mods
            if (listMops != null)
            {
                beatmap.Mods.Value = listMops?.ToArray();
            }

            return(beatmap);
        }
Example #54
0
        public PageVariableFragment(ReadOnlyMemory <char> originalText, JsToken expr, List <JsCallExpression> filterCommands)
        {
            OriginalText      = originalText;
            Expression        = expr;
            FilterExpressions = filterCommands?.ToArray() ?? TypeConstants <JsCallExpression> .EmptyArray;

            if (expr is JsLiteral initialValue)
            {
                InitialValue = initialValue.Value;
            }
            else if (ReferenceEquals(expr, JsNull.Value))
            {
                InitialValue = expr;
            }
            else if (expr is JsCallExpression initialExpr)
            {
                InitialExpression = initialExpr;
            }
            else if (expr is JsIdentifier initialBinding)
            {
                Binding = initialBinding.Name;
            }

            if (FilterExpressions.Length > 0)
            {
                LastFilterName = FilterExpressions[FilterExpressions.Length - 1].Name;
            }
        }
        public async Task RulesEngine_Execute_Rule_For_Nested_Rule_Params_Returns_Success(string ruleFileName)
        {
            dynamic[] inputs = GetInputs4();

            var ruleParams = new List <RuleParameter>();

            for (int i = 0; i < inputs.Length; i++)
            {
                var input = inputs[i];
                var obj   = Utils.GetTypedObject(input);
                ruleParams.Add(new RuleParameter($"input{i + 1}", obj));
            }

            var files = Directory.GetFiles(Directory.GetCurrentDirectory(), ruleFileName, SearchOption.AllDirectories);

            if (files == null || files.Length == 0)
            {
                throw new Exception("Rules not found.");
            }

            var fileData   = File.ReadAllText(files[0]);
            var bre        = new RulesEngine(JsonConvert.DeserializeObject <WorkflowRules[]>(fileData), null);
            var result     = await bre.ExecuteAllRulesAsync("inputWorkflow", ruleParams?.ToArray());;
            var ruleResult = result?.FirstOrDefault(r => string.Equals(r.Rule.RuleName, "GiveDiscount10", StringComparison.OrdinalIgnoreCase));

            Assert.True(ruleResult.IsSuccess);
        }
Example #56
0
        public CfanModule GeneratorRandomModule(
            List <ModDependency> conflicts  = null,
            List <ModDependency> depends    = null,
            List <ModDependency> sugests    = null,
            List <String> provides          = null,
            List <ModDependency> recommends = null,
            string identifier = null,
            Version version   = null)
        {
            if (depends == null)
            {
                depends = new List <ModDependency>();
            }
            if (depends.All(p => p.modName != "base"))
            {
                depends.Add(new ModDependency("base"));
            }

            var cfanJson = new CfanJson()
            {
                modInfo = new ModInfoJson()
                {
                    dependencies = depends.ToArray(),
                    version      = new ModVersion(version?.ToString() ?? "0.0.1"),
                    name         = identifier ?? Generator.Next().ToString(CultureInfo.InvariantCulture),
                    description  = Generator.Next().ToString(CultureInfo.InvariantCulture),
                    title        = Generator.Next().ToString(CultureInfo.InvariantCulture)
                },
                conflicts = conflicts?.ToArray(),
                suggests  = sugests?.ToArray()
            };

            return(new CfanModule(cfanJson));
        }
Example #57
0
        public Action Build()
        {
            if (string.IsNullOrEmpty(_name))
            {
                throw new ArgumentException("Name is required.");
            }

            if (string.IsNullOrEmpty(_href))
            {
                throw new ArgumentException("Href is required.");
            }

            var action = new Action
            {
                Name   = _name,
                Class  = _class?.ToArray(),
                Method = !string.IsNullOrEmpty(_method) ? _method : "GET",
                Href   = _href,
                Title  = _title,
                Type   = !string.IsNullOrEmpty(_type) ? _type : _fieldBuilders != null ? "application/x-www-form-urlencoded" : null,
                Fields = _fieldBuilders?.Select(x => x.Build()).ToArray()
            };

            if (action.Fields != null && new HashSet <string>(action.Fields.Select(x => x.Name)).Count != action.Fields.Count)
            {
                throw new ArgumentException("Field names MUST be unique within the set of fields for an action.");
            }

            return(action);
        }
Example #58
0
        public string OcrImage(string img)
        {
            string        res  = String.Empty;
            List <string> wrds = new List <string>();

            try
            {
                if (File.Exists(img))
                {
                    using (Image <Bgr, byte> i = new Image <Bgr, byte>(img))
                    {
                        if (OcrEngine != null)
                        {
                            OcrEngine.Recognize(i);
                            res = OcrEngine.GetText().TrimEnd();

                            wrds.AddRange(res.Split(new string[] { " ", "\r", "\n" },
                                                    StringSplitOptions.RemoveEmptyEntries).ToList());

                            this.Words = wrds?.ToArray();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }

            return(res);
        }
Example #59
0
        /// <summary>
        /// Рассчитать расстояние между всеми точками
        /// </summary>
        /// <param name="routes">Список точек</param>
        /// <returns>Матрица N*N расстояний между i и j точкой</returns>
        public static double[][] GetDistanсeBetweenAllPoints(List <Point> routes)
        {
            var points   = routes?.ToArray();
            var n        = points.Length;
            var distance = new double[n][];

            for (var i = 0; i < n; i++)
            {
                distance[i] = new double[n];
            }

            for (var i = 0; i < n; i++)
            {
                for (var j = 0; j < n; j++)
                {
                    if (i == j)
                    {
                        distance[i][j] = 0;
                        continue;
                    }

                    distance[i][j] = distance[j][i] = MathFunctions.GetDistanceToPoint(points[i], points[j]);
                }
            }

            return(distance);
        }
        private IEnumerable <Expression> VisitExpressionList(IEnumerable <Expression> original)
        {
            if (original == null)
            {
                return(null);
            }

            var originalAsList     = original as IReadOnlyList <Expression> ?? original.ToArray();
            List <Expression> list = null;

            for (int index = 0; index < originalAsList.Count; index++)
            {
                var p = Visit(originalAsList[index]);
                if (list != null)
                {
                    list.Add(p);
                    continue;
                }

                if (p == originalAsList[index])
                {
                    continue;
                }

                list = new List <Expression>(originalAsList.Count);
                for (var j = 0; j < index; j++)
                {
                    list.Add(originalAsList[j]);
                }
                list.Add(p);
            }

            return(list?.ToArray() ?? originalAsList);
        }