Example #1
1
        private IEnumerable<XElement> AddDirectoryAsync(DirectoryInfo dir, string collectionId, ref int count, int fnumber,
            BackgroundWorker worker)
        {
            List<XElement> addedElements = new List<XElement>();
            // добавление коллекции
            string subCollectionId;
            List<XElement> ae = this.cass.AddCollection(dir.Name, collectionId, out subCollectionId).ToList();
            if (ae.Count > 0) addedElements.AddRange(ae);

            count++;
            foreach (FileInfo f in dir.GetFiles())
            {
                if (worker.CancellationPending) break;
                if (f.Name != "Thumbs.db")
                    addedElements.AddRange(this.cass.AddFile(f, subCollectionId));
                count++;
                worker.ReportProgress(100 * count / fnumber);
            }
            foreach (DirectoryInfo d in dir.GetDirectories())
            {
                if (worker.CancellationPending) break;
                addedElements.AddRange(AddDirectoryAsync(d, subCollectionId, ref count, fnumber, worker));
            }
            return addedElements;
        }
Example #2
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 #3
0
    static List<int> QuickSort(List<int> list)
    {
        if (list.Count <= 1)
        {
            return list;
        }

        List<int> min = new List<int>();
        List<int> max = new List<int>();
        int pilor = list[0];
        for (int i = 1; i < list.Count; i++)
        {
            if (list[i] <= pilor)
            {
                min.Add(list[i]);
            }
            else
            {
                max.Add(list[i]);
            }
        }

        List<int> result = new List<int>();
        result.AddRange(QuickSort(min));
        result.Add(pilor);
        result.AddRange(QuickSort(max));
        return result;
    }
        private byte[] GetLengthBytes()
        {
            var payloadLengthBytes = new List<byte>(9);

            if (PayloadLength > ushort.MaxValue)
            {
                payloadLengthBytes.Add(127);
                byte[] lengthBytes = BitConverter.GetBytes(PayloadLength);
                if (BitConverter.IsLittleEndian)
                    Array.Reverse(lengthBytes);
                payloadLengthBytes.AddRange(lengthBytes);
            }
            else if (PayloadLength > 125)
            {
                payloadLengthBytes.Add(126);
                byte[] lengthBytes = BitConverter.GetBytes((UInt16) PayloadLength);
                if (BitConverter.IsLittleEndian)
                    Array.Reverse(lengthBytes);
                payloadLengthBytes.AddRange(lengthBytes);
            }
            else
            {
                payloadLengthBytes.Add((byte) PayloadLength);
            }

            payloadLengthBytes[0] += (byte) (IsMasked ? 128 : 0);

            return payloadLengthBytes.ToArray();
        }
        internal static List<FilePathViewIndex> GetOpenedFiles(int view = 0)
        {
            var result = new List<FilePathViewIndex>();

            int filesCount;
            ClikeStringArray cStrArray;
            int ind;

            if (view == 0 || view == 1)
            {
                filesCount = (int)Win32.SendMessage(PluginBase.nppData._nppHandle, NppMsg.NPPM_GETNBOPENFILES, 0, 1);
                using (cStrArray = new ClikeStringArray(filesCount, Win32.MAX_PATH))
                {
                    ind = 0;
                    if (Win32.SendMessage(PluginBase.nppData._nppHandle, NppMsg.NPPM_GETOPENFILENAMESPRIMARY, cStrArray.NativePointer, filesCount) != IntPtr.Zero)
                        if (cStrArray.ManagedStringsUnicode.Count > 1 || !Utils.IsFileNew(cStrArray.ManagedStringsUnicode[0]))
                            result.AddRange(cStrArray.ManagedStringsUnicode.Select(str => new FilePathViewIndex(str, 0, ind++)));
                }
            }

            if (view == 0 || view == 2)
            {
                filesCount = (int)Win32.SendMessage(PluginBase.nppData._nppHandle, NppMsg.NPPM_GETNBOPENFILES, 0, 2);
                using (cStrArray = new ClikeStringArray(filesCount, Win32.MAX_PATH))
                {
                    ind = 0;
                    if (Win32.SendMessage(PluginBase.nppData._nppHandle, NppMsg.NPPM_GETOPENFILENAMESSECOND, cStrArray.NativePointer, filesCount) != IntPtr.Zero)
                        if (cStrArray.ManagedStringsUnicode.Count > 1 || !Utils.IsFileNew(cStrArray.ManagedStringsUnicode[0]))
                            result.AddRange(cStrArray.ManagedStringsUnicode.Select(str => new FilePathViewIndex(str, 1, ind++)));
                }
            }

            return result;
        }
Example #6
0
        // Return a list of folders that need to be on the %PATH%
        public virtual List<string> GetPathFolders(IEnvironment environment)
        {
            // Add the msbuild path and git path to the %PATH% so more tools are available
            var toolsPaths = new List<string> {
                environment.DeploymentToolsPath, // Add /site/deployments/tools to the path to allow users to drop tools in there
                environment.ScriptPath,
                Path.GetDirectoryName(ResolveMSBuildPath()),
                Path.GetDirectoryName(ResolveGitPath()),
                Path.GetDirectoryName(ResolveVsTestPath()),
                Path.GetDirectoryName(ResolveSQLCmdPath()),
                Path.GetDirectoryName(ResolveFSharpCPath())
            };

            toolsPaths.AddRange(ResolveGitToolPaths());
            toolsPaths.AddRange(ResolveNodeNpmPaths());
            toolsPaths.Add(ResolveNpmGlobalPrefix());

            toolsPaths.AddRange(new[]
            {
                ResolveBowerPath(),
                ResolveGruntPath(),
                ResolveGulpPath()
            }.Where(p => !String.IsNullOrEmpty(p)).Select(Path.GetDirectoryName));

            return toolsPaths;
        }
Example #7
0
        protected static byte[] ConvertOptionFieldToByte(ushort optionType, byte[] value, bool reverseByteOrder, Action<Exception> ActionOnException)
        {
            Contract.Requires<ArgumentNullException>(value != null, "value cannot be null");
            Contract.Requires<ArgumentException>(value.Length > 0 || optionType == 0, "Only for optionType == 0 value.Lenght can be == 0");
            Contract.Requires<IndexOutOfRangeException>(value.Length <= UInt16.MaxValue, "value.Lenght > UInt16.MaxValue");
            
            List<byte> ret = new List<byte>();

            try
            {
                int remainderLength = (AlignmentBoundary - value.Length % AlignmentBoundary) % AlignmentBoundary;
                ret.AddRange(BitConverter.GetBytes(optionType.ReverseByteOrder(reverseByteOrder)));
                ret.AddRange(BitConverter.GetBytes(((UInt16)value.Length).ReverseByteOrder(reverseByteOrder)));
                if (value.Length > 0)
                {
                    ret.AddRange(value);
                    for (int i = 0; i < remainderLength; i++)
                    {
                        ret.Add(0);
                    }
                }
            }
            catch (Exception exc)
            {
                if (ActionOnException != null)
                    ActionOnException(exc);
            }

            return ret.ToArray();
        }
        public List<TestRunResults> RemoveUnmatchedRunInfoTests(TestRunResults[] results, TestRunInfo[] infos)
        {
            var tests = new List<TestItem>();
            tests.AddRange(_cache.Failed);
            tests.AddRange(_cache.Ignored);

            var removed = new List<TestRunResults>();
            infos
                .Where(i => results.Count(x => i.Assembly.Equals(x.Assembly)) == 0).ToList()
                .ForEach(i =>
                    {
                        tests.Where(x => x.Key.Equals(i.Assembly) &&
                                   (!i.OnlyRunSpcifiedTestsFor(x.Value.Runner) || i.GetTestsFor(x.Value.Runner).Count(t => t.Equals(x.Value.Name)) > 0))
                            .GroupBy(x => x.Value.Runner).ToList()
                            .ForEach(x => 
                                {
                                    removed.Add(new TestRunResults(
                                        i.Project.Key,
                                        i.Assembly,
                                        i.OnlyRunSpcifiedTestsFor(TestRunner.Any),
                                        x.Key,
                                        x.Select(t => new TestResult(
                                            t.Value.Runner,
                                            TestRunStatus.Passed,
                                            t.Value.Name,
                                            t.Value.Message,
                                            t.Value.StackTrace,
                                            t.Value.TimeSpent.TotalMilliseconds).SetDisplayName(t.Value.DisplayName)).ToArray()));
                                });
                    });
            return removed;
        }
Example #9
0
 public IList<JToken> ToList()
 {
     var retval = new List<JToken>();
     retval.AddRange(Events.Values);
     retval.AddRange(Tours.Values);
     return retval;
 }
        public List<MaterialCost> GetMaterialCost(string hwso, string swso, string evalno)
        {
            List<MaterialCost> data = new List<MaterialCost>();
            if (hwso.Trim() != "")
            {
                List<MaterialCost> hwMCost = ComputeMaterialCost("CAPHWConnection",hwso.Trim());
                data.AddRange(hwMCost);
            }
            if (swso.Trim() != "")
            {
                List<MaterialCost> swMCost = ComputeMaterialCost("CAPSWConnection", swso.Trim());
                data.AddRange(swMCost);
            }

            if (evalno.Trim() != "")
            {
                string[] evalnos = evalno.Split(',');
                foreach (string e in evalnos)
                {
                    string nSoNum = Regex.Replace(e, "[^0-9]", "");
                    if (nSoNum.Trim() != "")
                    {
                        string connection = GetConnectionString(nSoNum.Trim());
                        if (connection.Trim() != "")
                        {
                            List<MaterialCost> eMCost = ComputeMaterialCost("CAPSWConnection", nSoNum.Trim());
                            data.AddRange(eMCost);
                        }
                    }
                }
            }
            return data;
        }
Example #11
0
        /// <summary>
        /// Gets all matches for a given requested route
        /// Overridden to handle greedy capturing
        /// </summary>
        /// <param name="segments">Requested route segments</param>
        /// <param name="currentIndex">Current index in the route segments</param>
        /// <param name="capturedParameters">Currently captured parameters</param>
        /// <param name="context">Current Nancy context</param>
        /// <returns>A collection of <see cref="MatchResult"/> objects</returns>
        public override IEnumerable<MatchResult> GetMatches(string[] segments, int currentIndex, IDictionary<string, object> capturedParameters, NancyContext context)
        {
            var fullGreedy = this.GetFullGreedy(segments, currentIndex, capturedParameters);
            if (!this.Children.Any())
            {
                return fullGreedy;
            }

            var sb = new StringBuilder(segments[currentIndex]);
            var results = new List<MatchResult>();
            currentIndex++;

            while (!this.NoMoreSegments(segments, currentIndex - 1))
            {
                var currentSegment = segments[currentIndex];

                TrieNode matchingChild;
                if (this.Children.TryGetValue(currentSegment, out matchingChild))
                {
                    var parameters = new Dictionary<string, object>(capturedParameters);
                    parameters[this.parameterName] = sb.ToString();
                    results.AddRange(matchingChild.GetMatches(segments, currentIndex, parameters, context));
                }

                sb.AppendFormat("/{0}", currentSegment);
                currentIndex++;
            }

            if (!results.Any())
            {
                results.AddRange(fullGreedy);
            }

            return results;
        }
Example #12
0
		public override byte[] GetData()
		{
			var data = new List<byte>();
			data.AddRange(NsBinaryWriter.WriteString(Cpu));
			data.AddRange(NsBinaryWriter.WriteString(Os));
			return data.ToArray();
		}
        public static List<Def> GetResearchRequirements( this RecipeDef recipeDef )
        {
            var researchDefs = new List< Def >();

            if( recipeDef.researchPrerequisite != null )
            {
                // Basic requirement
                researchDefs.Add( recipeDef.researchPrerequisite );

                // Advanced requirement
                var advancedResearchDefs = ResearchController.AdvancedResearch.Where( a => (
                    ( a.IsRecipeToggle )&&
                    ( !a.HideDefs )&&
                    ( a.recipeDefs.Contains( recipeDef ) )
                ) ).ToList();

                if( !advancedResearchDefs.NullOrEmpty() )
                {
                    foreach( var a in advancedResearchDefs )
                    {
                        researchDefs.Add( a );
                    }
                }

            }

            // Get list of things recipe is used on
            var thingsOn = new List< ThingDef >();
            var recipeThings = DefDatabase< ThingDef >.AllDefsListForReading.Where( t => (
                ( t.recipes != null )&&
                ( !t.IsLockedOut() )&&
                ( t.recipes.Contains( recipeDef ) )
            ) ).ToList();

            if( !recipeThings.NullOrEmpty() )
            {
                thingsOn.AddRange( recipeThings );
            }

            // Add those linked via the recipe
            if( !recipeDef.recipeUsers.NullOrEmpty() )
            {
                thingsOn.AddRange( recipeDef.recipeUsers );
            }

            // Make sure they all have hard requirements
            if(
                ( !thingsOn.NullOrEmpty() )&&
                ( thingsOn.All( t => t.HasResearchRequirement() ) )
            )
            {
                foreach( var t in thingsOn )
                {
                    researchDefs.AddRange( t.GetResearchRequirements() );
                }
            }

            // Return the list of research required
            return researchDefs;
        }
Example #14
0
        public SnapShotStatData GenerateStatisticData(int beginStaTime, int endStaTime, OtherSubSysInterface subSysInterface, int snapshotId)
        {
            StaSimulationCarrier carrier = new StaSimulationCarrier();
            SnapShotStatData data = new SnapShotStatData();
            data.SnapShotName = SimulationTools.GenerateSnapshotName(snapshotId);
            data.DlRsrpFailList.AddRange(this.DlRsrpFailUserList);
            data.UlRsrpFailList.AddRange(this.UlRsrpFailUserList);
            List<StatSimuCarrierResult> carrierResList = carrier.Statistic(beginStaTime, endStaTime, this.m_SimulationCarrierList, subSysInterface);
            data.StatSimuSiteResultList = new StaSimulationSite().Statistic(carrierResList, this.m_SimulationCarrierList);

            foreach (SimulationCarrier carrier2 in this.m_SimulationCarrierList)
            {
                this.SelectUsers(carrier2.OffLineUserList, data.OffLineList);
                List<ISimulationUser> waitUserList = new List<ISimulationUser>();
                waitUserList.AddRange(carrier2.DlDataWaitUserList);
                waitUserList.AddRange(carrier2.DlVoiceWaitUserList);
                waitUserList.AddRange(carrier2.UlDataWaitUserList);
                waitUserList.AddRange(carrier2.UlVoiceWaitUserList);
                temp = carrier2.count;
                this.ClassifyWaitUsers(waitUserList, data);
                data.SatisfiedList.AddRange(this.ToISimuUser(carrier2.UlVoiceServiceUserList));
                data.SatisfiedList.AddRange(this.ToISimuUser(carrier2.UlDataServiceUserList));
                data.SatisfiedList.AddRange(this.ToISimuUser(carrier2.DlVoiceServiceUserList));
                data.SatisfiedList.AddRange(this.ToISimuUser(carrier2.DlDataServiceUserList));
                data.DlRsSinrFailList.AddRange(this.ToISimuUser(carrier2.FailUserList));
                data.UlRsSinrFailList.AddRange(this.ToISimuUser(carrier2.UlRsSinrFailUserList));
            }
            
            data.WholeNetDLInstantaneousThroughput = this.m_WholeNetDLThroughput;
            data.WholeNetULInstantaneousThroughput = this.m_WholeNetULThroughput;
            return data;
        }
Example #15
0
		public List<string> GetAllFilePathsAsList()
		{
			var list = new List<string> { Csproj, AssemblyInfo };
			list.AddRange(Icons);
			list.AddRange(SourceCodeFiles);
			return list;
		}
 public static List<char> InvalidChars()
 {
     var invalidChars = new List<char>();
     invalidChars.AddRange(Path.GetInvalidFileNameChars());
     invalidChars.AddRange(Path.GetInvalidPathChars());
     return invalidChars;
 }
 static void Main()
 {
     Student[] arrStudentsTest = { new Student("Sonya", "Markova", 3), new Student("Sotir", "Galabov", 2), new Student("Svilen", "Belev", 2),
                                 new Student("Petar","Peshev", 5),new Student("Ivaylo","Drajev", 3),new Student("Krasi","Smilkov", 4),
                                 new Student("Yana","Mileva", 3),new Student("Vito","Zagorski", 1),new Student("Valeri","Timev", 5),
                                 new Student("Rumen","Vlahov", 6),};
     List<Student> studentsTest = arrStudentsTest.ToList();
     foreach (var student in studentsTest.OrderBy(s => s.Grade))
     {
         Console.WriteLine("Student: {0},\tGrade: {1}", student, student.Grade);
     }
     Worker[] arrWorkerTest = { new Worker("Angel", "Velev", 500, 8), new Worker("Lazar", "Penev", 230, 4), new Worker("Georgi", "Kostov", 340, 7),
                              new Worker("Vasil", "Vasilev", 600, 10), new Worker("Teo", "Simeonov", 550, 8), new Worker("Jivko", "Jelev", 380, 7),
                             new Worker("Daniel", "Hristov", 150, 5), new Worker("Mihail", "Ivanov", 480, 8), new Worker("Kamen", "Kamburov", 420, 8),
                             new Worker("Vesela", "Ganeva", 100, 2)};
     List<Worker> workerTest = arrWorkerTest.ToList();
     foreach (var worker in workerTest.OrderByDescending(w => w.MoneyPerHour()))
     {
         Console.WriteLine("Worker: {0},\tMoney Per Hour: {1:0.00}", worker.ToString(), worker.MoneyPerHour());
     }
     List<Human> all = new List<Human>();
     all.AddRange(workerTest);
     all.AddRange(studentsTest);
     foreach (var human in all.OrderBy(i => i.FirstName).ThenBy(i => i.LastName))
     {
         Console.WriteLine(human);
     }
 }
Example #18
0
        public List<Tag> BrowseTags()
        {
            //Cursor = Cursors.WaitCursor;
            if (sc == null || !sc.IsConnected()) { this.Connect(); }
            //check if the server is already connected, if not skip the execution
            if (!(sc == null))
            {
                if (sc.IsConnected())
                {
                    //build the tags query
                    var query = new TagQueryParams { PageSize = 100 };
                    var allTags = new List<Tag>();
                    List<Tag> tmp;
                    // return only string tags
                    query.Criteria.TagnameMask = "*";
                    query.Criteria.DataType = Proficy.Historian.ClientAccess.API.Tag.NativeDataType.Float;

                    //execute the query and populate the list datatype
                    while (sc.ITags.Query(ref query, out tmp))
                        allTags.AddRange(tmp);
                    allTags.AddRange(tmp);

                    //populate the combo box
                    //cboTags.DataSource = allTags;
                    //cboTags.DisplayMember = "Name";
                    //cboTags.ValueMember = "Name";

                    return allTags;
                }
            }
            return null;

            //Cursor = Cursors.Default;

        }
 private MethodInfo[] GetAllActionMethodsFromSelector()
 {
     List<MethodInfo> allValidMethods = new List<MethodInfo>();
     allValidMethods.AddRange(_selector.AliasedMethods);
     allValidMethods.AddRange(_selector.NonAliasedMethods.SelectMany(g => g));
     return allValidMethods.ToArray();
 }
Example #20
0
        public static CodeGenFile[] Generate(ICodeGeneratorDataProvider provider, string directory, ICodeGenerator[] codeGenerators)
        {
            directory = GetSafeDir(directory);
            CleanDir(directory);

            var generatedFiles = new List<CodeGenFile>();

            foreach (var generator in codeGenerators.OfType<IPoolCodeGenerator>()) {
                var files = generator.Generate(provider.poolNames);
                generatedFiles.AddRange(files);
                writeFiles(directory, files);
            }

            foreach (var generator in codeGenerators.OfType<IComponentCodeGenerator>()) {
                var files = generator.Generate(provider.componentInfos);
                generatedFiles.AddRange(files);
                writeFiles(directory, files);
            }

            foreach (var generator in codeGenerators.OfType<IBlueprintsCodeGenerator>()) {
                var files = generator.Generate(provider.blueprintNames);
                generatedFiles.AddRange(files);
                writeFiles(directory, files);
            }

            return generatedFiles.ToArray();
        }
Example #21
0
        /// <summary>
        /// Returns all type implementing the specified interface in all loaded assemblies
        /// </summary>
        /// <param name="expectedInterface"></param>
        /// <param name="assembly"></param>
        /// <param name="checkReferencedAssemblies">Check referenced assemblies also</param>
        /// <returns></returns>
        /// <exception cref="ArgumentNullException">when <paramref name="assembly"/> is null</exception>
        public static IList<Type> ThatImplement(Type expectedInterface, Assembly assembly, bool checkReferencedAssemblies)
        {
            if (assembly == null) throw new ArgumentNullException("assembly");

            var results = new List<Type>();

            var assemblies = new List<AssemblyName> {assembly.GetName()};

            if( checkReferencedAssemblies ) assemblies.AddRange(assembly.GetReferencedAssemblies());

            foreach( var referencedAssembly in assemblies )
            {
                // Catch loader exceptions for referenced assemblies
                var loadedAssembly = Assembly.Load(referencedAssembly);

                if( loadedAssembly == assembly)
                {
                    results.AddRange(ThatImplement(expectedInterface, loadedAssembly));
                }
                else
                {
                    try
                    {
                        results.AddRange(ThatImplement(expectedInterface, loadedAssembly));
                    }
                    catch (ReflectionTypeLoadException)
                    {
                        continue;
                    }
                }
            }

            return results;
        }
        private IEnumerable<SignatureHelpParameter> GetDelegateTypeParameters(IMethodSymbol invokeMethod, SemanticModel semanticModel, int position, CancellationToken cancellationToken)
        {
            const string TargetName = "target";

            var parts = new List<SymbolDisplayPart>();
            parts.AddRange(invokeMethod.ReturnType.ToMinimalDisplayParts(semanticModel, position));
            parts.Add(Space());
            parts.Add(Punctuation(SyntaxKind.OpenParenToken));

            var first = true;
            foreach (var parameter in invokeMethod.Parameters)
            {
                if (!first)
                {
                    parts.Add(Punctuation(SyntaxKind.CommaToken));
                    parts.Add(Space());
                }

                first = false;
                parts.AddRange(parameter.Type.ToMinimalDisplayParts(semanticModel, position));
            }

            parts.Add(Punctuation(SyntaxKind.CloseParenToken));
            parts.Add(Space());
            parts.Add(new SymbolDisplayPart(SymbolDisplayPartKind.ParameterName, null, TargetName));

            yield return new SignatureHelpParameter(
                TargetName,
                isOptional: false,
                documentationFactory: null,
                displayParts: parts);
        }
Example #23
0
        protected virtual ExitCode ChangeSetting(IClientSettings clientSettings, SettingsLocation location, ChangeType changeType)
        {
            // Don't want to save defaults for options that apply directly to this command
            List<string> settingsToSkip = new List<string>();
            settingsToSkip.AddRange(StandardOptions.List);
            settingsToSkip.AddRange(StandardOptions.Add);
            settingsToSkip.AddRange(StandardOptions.Remove);

            foreach (var setting in this.Arguments.Options)
            {
                if (settingsToSkip.Contains(setting.Key, StringComparer.OrdinalIgnoreCase)) { continue; }
                bool success = false;
                switch (changeType)
                {
                    case ChangeType.Add:
                        this.Loggers[LoggerType.Status].Write(XTaskStrings.DefaultsSavingProgress, setting.Key);
                        success = clientSettings.SaveSetting(location, setting.Key, setting.Value);
                        break;
                    case ChangeType.Remove:
                        this.Loggers[LoggerType.Status].Write(XTaskStrings.DefaultsRemovingProgress, setting.Key);
                        success = clientSettings.RemoveSetting(location, setting.Key);
                        break;
                }

                this.Loggers[LoggerType.Status].WriteLine(success ? XTaskStrings.Succeeded : XTaskStrings.Failed);
            }

            return ExitCode.Success;
        }
 public ActionResult Bonds()
 {
     List<Asset> assets = new List<Asset>();
     assets.AddRange(repository.GetUserAssets(UserId, AssetType.DomesticBond));
     assets.AddRange(repository.GetUserAssets(UserId, AssetType.InternationalBond));
     return View(assets);
 }
Example #25
0
    private static string MakeTestName(string path)
    {
      var rx = new Regex(@"test-(\d+)");
      var tests = new List<string>();
      tests.AddRange(Directory.GetDirectories(path).Select(Path.GetFileNameWithoutExtension));
      tests.AddRange(Directory.GetFiles(path, "*.test").Select(Path.GetFileNameWithoutExtension));
      tests.Sort();
      int num = 0;
      for (int i = tests.Count - 1; i >= 0; i--)
      {
        var testName = tests[i];
        var m = rx.Match(testName);
        if (m.Success)
        {
          num = int.Parse(m.Groups[1].Value) + 1;
          break;
        }
      }

      for (;; num++)
      {
        var fileName = "test-" + num.ToString("0000");
        if (!File.Exists(Path.Combine(path, fileName + ".test")))
          return fileName;
      }
    }
        /// <summary>
        /// This is invoked when the collection changes.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="System.Collections.Specialized.NotifyCollectionChangedEventArgs"/> instance containing the event data.</param>
        /// <remarks>
        /// This method must be public because the <see cref="IWeakEventListener"/> is used.
        /// </remarks>
        public void OnCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            Log.Debug("Automatically tracking change '{0}' of collection", e.Action);

            var undoList = new List<CollectionChangeUndo>();
            var collection = (IList)sender;

            switch (e.Action)
            {
                case NotifyCollectionChangedAction.Add:
                    undoList.AddRange(e.NewItems.Cast<object>().Select((item, i) => new CollectionChangeUndo(collection, CollectionChangeType.Add, -1, e.NewStartingIndex + i, null, item, Tag)));
                    break;

                case NotifyCollectionChangedAction.Remove:
                    undoList.AddRange(e.OldItems.Cast<object>().Select((item, i) => new CollectionChangeUndo(collection, CollectionChangeType.Remove, e.OldStartingIndex + i, -1, item, null, Tag)));
                    break;

                case NotifyCollectionChangedAction.Replace:
                    undoList.Add(new CollectionChangeUndo(collection, CollectionChangeType.Replace, e.OldStartingIndex, e.NewStartingIndex, e.OldItems[0], e.NewItems[0], Tag));
                    break;

#if NET
                case NotifyCollectionChangedAction.Move:
                    undoList.Add(new CollectionChangeUndo(collection, CollectionChangeType.Move, e.OldStartingIndex, e.NewStartingIndex, e.NewItems[0], e.NewItems[0], Tag));
                    break;
#endif
            }

            foreach (var operation in undoList)
            {
                MementoService.Add(operation);
            }

            Log.Debug("Automatically tracked change '{0}' of collection", e.Action);
        }
        public static NamespaceDeclarationSyntax AddUsingDirectives(
            this NamespaceDeclarationSyntax namespaceDeclaration,
            IList<UsingDirectiveSyntax> usingDirectives,
            bool placeSystemNamespaceFirst,
            params SyntaxAnnotation[] annotations)
        {
            if (!usingDirectives.Any())
            {
                return namespaceDeclaration;
            }

            var specialCaseSystem = placeSystemNamespaceFirst;
            var comparer = specialCaseSystem
                ? UsingsAndExternAliasesDirectiveComparer.SystemFirstInstance
                : UsingsAndExternAliasesDirectiveComparer.NormalInstance;

            var usings = new List<UsingDirectiveSyntax>();
            usings.AddRange(namespaceDeclaration.Usings);
            usings.AddRange(usingDirectives);

            if (namespaceDeclaration.Usings.IsSorted(comparer))
            {
                usings.Sort(comparer);
            }

            usings = usings.Select(u => u.WithAdditionalAnnotations(annotations)).ToList();
            var newNamespace = namespaceDeclaration.WithUsings(SyntaxFactory.List(usings));

            return newNamespace;
        }
Example #28
0
			/// <summary>
			/// Initializes a new instance of the <see cref="Subrule"/> class.
			/// </summary>
			/// <param name="id">The id.</param>
			/// <param name="desc">The description.</param>
			/// <param name="morpher">The morpher.</param>
			/// <param name="headLhs">The head LHS.</param>
			/// <param name="nonHeadLhs">The non-head LHS.</param>
			/// <param name="rhs">The RHS.</param>
			/// <param name="alphaVars">The alpha variables.</param>
			public Subrule(string id, string desc, Morpher morpher, IEnumerable<PhoneticPattern> headLhs,
				IEnumerable<PhoneticPattern> nonHeadLhs, IEnumerable<MorphologicalOutput> rhs, AlphaVariables alphaVars)
				: base (id, desc, morpher)
			{
				m_alphaVars = alphaVars;

				List<PhoneticPattern> lhs = new List<PhoneticPattern>();
				lhs.AddRange(headLhs);
				lhs.AddRange(nonHeadLhs);

				m_transform = new MorphologicalTransform(lhs, rhs, MorphologicalTransform.RedupMorphType.IMPLICIT);

				// the LHS template is generated by simply concatenating all of the
				// LHS partitions; it matches the entire word, so we check for both the
				// left and right margins.
				m_headLhsTemp = new PhoneticPattern();
				m_headLhsTemp.Add(new MarginContext(Direction.LEFT));
				int partition = 0;
				foreach (PhoneticPattern pat in headLhs)
					m_headLhsTemp.AddPartition(pat, partition++);
				m_headLhsTemp.Add(new MarginContext(Direction.RIGHT));

				m_firstNonHeadPartition = partition;
				m_nonHeadLhsTemp = new PhoneticPattern();
				m_nonHeadLhsTemp.Add(new MarginContext(Direction.LEFT));
				foreach (PhoneticPattern pat in nonHeadLhs)
					m_nonHeadLhsTemp.AddPartition(pat, partition++);
				m_nonHeadLhsTemp.Add(new MarginContext(Direction.RIGHT));
			}
 /// <summary>
 /// Выполнить скрипт
 /// </summary>
 /// <param name="text">Текст скрипта</param>
 public static void ExecuteScript(string text)
 {
     foreach (string block in text.Split('/'))
     {
         List<string> commands = new List<string>();
         string lower = block.ToLower();
         int posPackage = lower.IndexOf("package");
         int posProcedure = lower.IndexOf("procedure");
         int posDeclare = lower.IndexOf("declare");
         int posBegin = lower.IndexOf("begin");
         int posStart = posDeclare >= 0 ? posDeclare : posBegin;
         if (posPackage >= 0 || posProcedure >= 0)
             posStart = lower.LastIndexOf("create", posPackage >= 0 ? posPackage : posProcedure);
         if (posStart >= 0)
         {
             if (posStart > 0)
                 commands.AddRange(block.Substring(0, posStart - 1).Split(';'));
             commands.Add(block.Substring(posStart));
         }
         else
             commands.AddRange(block.Split(';'));
         foreach (string command in commands)
         {
             string commandText = command.Trim();
             if (string.IsNullOrEmpty(commandText)) continue;
             ExecuteBlock(commandText);
         }
     }
 }
		/// <summary>
		/// Do the validation.
		/// </summary>
		protected void DoValidate()
		{
			currentResults = new List<ValidationResult> ();
			currentResults.AddRange (new ValidateRaycastColliders ().Validate ());
			currentResults.AddRange (new ValidateLayers ().Validate ());
			currentResults.AddRange (new ValidateRigidbodies ().Validate ());
		}
Example #31
0
        public void StoreResultFeatures(
            [CanBeNull] List <IFeature> allStoredFeatures,
            [CanBeNull] Action <IEnumerable <KeyValuePair <IFeature, IList <IFeature> > > >
            onResultsSaved = null)
        {
            foreach (var observer in EditOperationObservers)
            {
                observer.StartedOperation();
            }

            foreach (KeyValuePair <IFeature, IList <IGeometry> > keyValuePair in
                     ResultGeometriesByFeature)
            {
                IFeature          originalFeature = keyValuePair.Key;
                IList <IGeometry> newGeometries   = keyValuePair.Value;

                IList <IFeature> cutResultFeatures;
                if (_networkFeatureCutter != null &&
                    _networkFeatureCutter.IsNetworkEdge(originalFeature))
                {
                    // Allow legacy geometric network support:
                    cutResultFeatures = SplitNetworkEdge(originalFeature, newGeometries);
                }
                else
                {
                    IGeometry largestGeo =
                        GeometryUtils.GetLargestGeometry(newGeometries);

                    cutResultFeatures = StoreGeometries(newGeometries,
                                                        originalFeature,
                                                        Assert.NotNull(largestGeo),
                                                        null);
                }

                allStoredFeatures?.AddRange(cutResultFeatures);

                NotifySplitObservers(originalFeature, cutResultFeatures);
            }

            if (_targetsToUpdate != null)
            {
                allStoredFeatures?.AddRange(StoreUpdatedTargets());
            }

            onResultsSaved?.Invoke(InsertedFeaturesByOriginal);

            foreach (var observer in EditOperationObservers)
            {
                observer.CompletingOperation();
            }
        }
Example #32
0
        public IList <ITypeInfo> GetParents(IType type, List <ITypeInfo> list = null)
        {
            IList <ITypeInfo> result;

            if (cacheParents.TryGetValue(type, out result))
            {
                list?.AddRange(result);
                return(result);
            }

            bool endPoint = list == null;

            if (endPoint)
            {
                activeTypes = new Stack <IType>();
                list        = new List <ITypeInfo>();
            }

            var typeDef = type.GetDefinition() ?? type;

            if (activeTypes.Contains(typeDef))
            {
                return(list);
            }

            activeTypes.Push(typeDef);

            var types        = type.GetAllBaseTypes();
            var thisTypelist = new List <ITypeInfo>();

            foreach (var t in types)
            {
                var bType = H5Types.Get(t, true);

                if (bType?.TypeInfo != null && !bType.Type.Equals(typeDef))
                {
                    thisTypelist.Add(bType.TypeInfo);
                }

                if (t.TypeArguments.Count > 0)
                {
                    foreach (var typeArgument in t.TypeArguments)
                    {
                        bType = H5Types.Get(typeArgument, true);
                        if (bType?.TypeInfo != null && !bType.Type.Equals(typeDef))
                        {
                            thisTypelist.Add(bType.TypeInfo);
                        }

                        GetParents(typeArgument, thisTypelist);
                    }
                }
            }
            list.AddRange(thisTypelist);
            activeTypes.Pop();
            list = list.Distinct().ToList();
            cacheParents[type] = list;

            return(list);
        }
Example #33
0
        public async Task OnNextAsync(DiffModel item, StreamSequenceToken token = null)
        {
            _logger.Verbose($"OnNextAsync called with {item.NewGrains.Count} items");
            var newGrains = await ApplyFilter(item.NewGrains);

            CurrentStats?.AddRange(newGrains);

            if (InSummaryMode)
            {
                await _dashboardInstanceStream.OnNextAsync(new DiffModel
                {
                    SummaryView      = InSummaryMode,
                    TypeCounts       = item.TypeCounts,
                    NewGrains        = GetGrainSummaries(),
                    SummaryViewLinks = GetGrainSummaryLinks(),
                    SessionId        = SessionId
                });
            }
            else
            {
                item.NewGrains = newGrains;
                _logger.Verbose($"OnNextAsync called with {item.NewGrains.Count} items");

                if (item.NewGrains != null && (item.NewGrains.Any() || item.RemovedGrains.Any()))
                {
                    item.SummaryView = InSummaryMode;
                    item.SessionId   = SessionId;
                    await _dashboardInstanceStream.OnNextAsync(item);
                }
            }
        }
        private async void OnDownloadFeed(object sender, EventArgs e)
        {
            try
            {
                FeedEpisodes.Clear();
                FeedEpisodes?.AddRange(await _feedHandler.DownloadFeedList());
                List <object> autoEpisodes = new List <object>();
                foreach (var feedEpisode in FeedEpisodes)
                {
                    if (LocalTvShows.Any(tvShow =>
                                         tvShow.Name.Equals(feedEpisode.Name) &&
                                         tvShow.AutoDownloadStatus.Equals(AutoDownload.On) &&
                                         !tvShow.Episodes.Any(episode => episode.EpisodeNumber.Equals(feedEpisode.EpisodeNumber))))
                    {
                        autoEpisodes.Add(feedEpisode);
                    }
                }

                _controller.UpdateDownloadList(autoEpisodes);
                _controller.RefreshData();
            }
            catch (Exception ex)
            {
                Log.Error(ex, "OnDownloadFeed Error!");
            }
        }
        public bool TryResolveAssemblyPaths(CompilationLibrary library, List <string>?assemblies)
        {
            ThrowHelper.ThrowIfNull(library);

            if (_nugetPackageDirectories == null || _nugetPackageDirectories.Length == 0 ||
                !string.Equals(library.Type, "package", StringComparison.OrdinalIgnoreCase))
            {
                return(false);
            }

            foreach (string directory in _nugetPackageDirectories)
            {
                string packagePath;

                if (ResolverUtils.TryResolvePackagePath(_fileSystem, library, directory, out packagePath))
                {
                    if (TryResolveFromPackagePath(_fileSystem, library, packagePath, out IEnumerable <string>?fullPathsFromPackage))
                    {
                        assemblies?.AddRange(fullPathsFromPackage);
                        return(true);
                    }
                }
            }
            return(false);
        }
Example #36
0
        async Task PerformSearch(CancellationToken token)
        {
            Searching = true;
            await Invoke(StateHasChanged);

            await Task.Delay(1);

            var options = GitterApi.GetNewOptions();

            options.Query = SearchText;
            options.Limit = 100;
            SearchResult  = new List <IChatMessage>();
            var messages = await GitterApi.SearchChatMessages(ChatRoom.Id, options);

            while ((messages?.Any() ?? false) && !token.IsCancellationRequested)
            {
                SearchResult?.AddRange(messages.OrderBy(m => m.Sent).Reverse());
                await Invoke(StateHasChanged);

                await Task.Delay(1000);

                options.Skip += messages.Count();
                messages      = await GitterApi.SearchChatMessages(ChatRoom.Id, options);
            }

            Searching = false;
            await Invoke(StateHasChanged);

            await Task.Delay(1);
        }
Example #37
0
            // ReSharper restore UnusedVariable

            private static int ReadNullTermString(BinaryReader fileStream, byte encoding, List <byte> text)
            {
                bool unicode = encoding == 1 || encoding == 2;

                if (!unicode)
                {
                    int  read = 0;
                    byte textByte;
                    while ((textByte = fileStream.ReadByte()) > 0)
                    {
                        text?.Add(textByte);
                        read++;
                    }
                    return(read + 1);                    // +1 = null-byte
                }
                else
                {
                    var buffer = new byte[2];
                    int read   = 0;
                    while (fileStream.Read(buffer, 0, 2) == 2 && (buffer[0] != 0 || buffer[1] != 0))
                    {
                        text?.AddRange(buffer);
                        read += 2;
                    }
                    return(read + 2);
                }
            }
Example #38
0
        public IList <ClaimHistory> GetClaimHistoryByPolicyNumber(string policynumber, DateTime Start, DateTime end)
        {
            IList <ClaimHistory> all           = NewMethod(policynumber, Start, end);
            IList <Claim>        allfromclaims = _session.QueryOver <Claim>().WhereRestrictionOn(x => x.enrolleePolicyNumber).IsInsensitiveLike(policynumber, MatchMode.End).Where(y => y.ServiceDate >= Start).Where(z => z.ServiceDate <= end).List <Claim>();

            //convert the claimhistory to shiit
            List <ClaimHistory> collection = new List <ClaimHistory>();

            foreach (Claim item in allfromclaims)
            {
                ClaimHistory nobj     = new ClaimHistory();
                Provider     provider = _providersvc.GetProvider(item.ProviderId);
                nobj.PROVIDER = provider != null?provider.Name.ToUpper() : "Unknown";

                nobj.PROVIDERID      = provider != null ? provider.Id : -1;
                nobj.POLICYNUMBER    = item.enrolleePolicyNumber;
                nobj.ENCOUNTERDATE   = Convert.ToDateTime(item.ServiceDate);
                nobj.DATERECEIVED    = item.CreatedOn;
                nobj.DIAGNOSIS       = item.Diagnosis.ToUpper();
                nobj.AMOUNTSUBMITTED = Convert.ToDecimal(item.DrugList.Sum(x => x.InitialAmount) + item.ServiceList.Sum(x => x.InitialAmount));
                nobj.AMOUNTPROCESSED = Convert.ToDecimal(item.DrugList.Sum(x => x.VettedAmount) + item.ServiceList.Sum(x => x.VettedAmount));
                nobj.CLASS           = Enum.GetName(typeof(ClaimsTAGS), item.Tag);
                nobj.CLIENTNAME      = item.enrolleeFullname;

                //added ? after collection, collection and all

                collection?.Add(nobj);
            }
            collection?.AddRange(all?.ToList());

            return(collection);
        }
Example #39
0
            protected override IEnumerable <CarLight> LoadLights()
            {
                var result = LoadLights <DeferredCarLight>().ToList();

                _lights?.AddRange(result);
                return(result);
            }
Example #40
0
        private void LoadLaws(ExcelWorksheet reader, List <Law> lawsList, string language, int row)
        {
            List <Law> result   = new List <Law>();
            var        laws     = ProcessLaws(GetString(reader, 6, row));
            var        lawLinks = ProcessLaws(GetString(reader, 7, row));

            if (laws == null)
            {
                return;
            }
            while (laws.Count > 0)
            {
                var link      = lawLinks?.Dequeue();
                var reference = link;

                Law law = new Law();
                result.Add(law);

                law.Names.Add(new LanguageLabel(laws.Dequeue(), language));
                if (link != null)
                {
                    law.Links.Add(new LanguageLabel(link, language));
                }
                law.LawReference = reference ?? law.Names.First().Label;
            }
            lawsList?.AddRange(result);
        }
Example #41
0
        /// <summary>
        /// Infer the shape of outputs and arguments of given known shapes of arguments
        /// </summary>
        /// <param name="argShapes"> Provide keyword arguments of known shapes.</param>
        /// <param name="inShape">List of shapes of arguments.The order is in the same order as list_arguments()</param>
        /// <param name="outShape">List of shapes of outputs.The order is in the same order as list_outputs()</param>
        /// <param name="auxShape">List of shapes of outputs.The order is in the same order as list_auxiliary()</param>
        public void InferShape(Dictionary <string, uint[]> argShapes, [Out] List <uint[]> inShape, [Out] List <uint[]> outShape, [Out] List <uint[]> auxShape)
        {
            var keys         = new List <string>();
            var argIndPtr    = new List <uint>();
            var argShapeData = new List <uint>();

            foreach (var arg in argShapes)
            {
                keys.Add(arg.Key);
                argIndPtr.Add((uint)argShapeData.Count);
                foreach (var i in arg.Value)
                {
                    argShapeData.Add(i);
                }
            }
            argIndPtr.Add((uint)argShapeData.Count);

            uint   inShapeSize;
            IntPtr inShapeNdimPtr;
            IntPtr inShapeDataPtr;
            uint   outShapeSize;
            IntPtr outShapeNdimPtr;
            IntPtr outShapeDataPtr;
            uint   auxShapeSize;
            IntPtr auxShapeNdimPtr;
            IntPtr auxShapeDataPtr;
            int    complete;

            Util.CallCheck(NativeMethods.MXSymbolInferShape(get_handle(), (uint)keys.Count, keys.ToArray(),
                                                            argIndPtr.ToArray(), argShapeData.ToArray(),
                                                            out inShapeSize, out inShapeNdimPtr, out inShapeDataPtr,
                                                            out outShapeSize, out outShapeNdimPtr, out outShapeDataPtr,
                                                            out auxShapeSize, out auxShapeNdimPtr, out auxShapeDataPtr,
                                                            out complete));

            var inShapeNdim = PtrToArrayUint32(inShapeNdimPtr, (int)inShapeSize);
            var inShapeData = PtrToArrayUint32(inShapeDataPtr, (int)inShapeSize, inShapeNdim);

            var outShapeNdim = PtrToArrayUint32(outShapeNdimPtr, (int)outShapeSize);
            var outShapeData = PtrToArrayUint32(outShapeDataPtr, (int)outShapeSize, outShapeNdim);

            var auxShapeNdim = PtrToArrayUint32(auxShapeNdimPtr, (int)auxShapeSize);
            var auxShapeData = PtrToArrayUint32(auxShapeDataPtr, (int)auxShapeSize, auxShapeNdim);

            if (complete > 0)
            {
                if (inShapeSize != 0)
                {
                    inShape?.AddRange(inShapeData);
                }
                if (outShapeSize != 0)
                {
                    outShape?.AddRange(outShapeData);
                }
                if (auxShapeSize != 0)
                {
                    auxShape?.AddRange(auxShapeData);
                }
            }
        }
Example #42
0
 private void Merge(List <string> source, List <string> destination)
 {
     if (source != null)
     {
         destination?.AddRange(source.Where(x => destination.All(m => m != x)));
     }
 }
Example #43
0
 /// <summary>
 /// Databases and users created through this method will be dropped
 /// during the test fixture's dispose routine. For that reason, do not pass details
 /// of an existing user or database that you expect to stay around after a test run.
 /// </summary>
 /// <param name="dbName"></param>
 /// <param name="users">Optional set of users to create along with the database.</param>
 /// <returns></returns>
 protected async Task CreateDatabase(string dbName, IEnumerable <DatabaseUser> users = null)
 {
     // Create the test database
     using (var systemDbClient = GetHttpTransport("_system"))
     {
         var dbApiClient = new DatabaseApiClient(systemDbClient);
         try
         {
             var postDatabaseResponse = await dbApiClient.PostDatabaseAsync(new PostDatabaseBody
             {
                 Name  = dbName,
                 Users = users
             });
         }
         catch (ApiErrorException ex) when(ex.ApiError.ErrorNum == 1207)
         {
             // database must exist already
             Console.WriteLine(ex.Message);
         }
         finally
         {
             _databases.Add(dbName);
             if (users != null)
             {
                 _users?.AddRange(users.Select(u => u.Username));
             }
         }
     }
 }
Example #44
0
        public virtual T FromXml(XElement element, List <ParserError> errors)
        {
            var result = FromXml(element);

            errors?.AddRange(Errors);

            return(result);
        }
Example #45
0
 protected override List <Body> AggregateResult(List <Body> aggregate, List <Body> nextResult)
 {
     if (nextResult != null)
     {
         aggregate?.AddRange(nextResult);
     }
     return(aggregate ?? nextResult);
 }
Example #46
0
        public async Task <IList <UpcomingInterviews> > GetUpcomingInterviews(string userOid, DateTime startDateTime)
        {
            if (string.IsNullOrEmpty(userOid))
            {
                throw new InvalidOperationException("Invalid user oid");
            }

            if (startDateTime == null || startDateTime == default(DateTime))
            {
                startDateTime = DateTime.UtcNow;
            }

            if (!DateTime.TryParse(startDateTime.ToString(CultureInfo.InvariantCulture), out startDateTime))
            {
                throw new InvalidOperationException("Invalid date");
            }

            List <string> jobApplicationIds = new List <string>();

            var jobOpenings = await this.jobApplicationQuery.GetActiveJobApplications(userOid);

            jobOpenings?.ForEach(jo =>
            {
                var jaIds = jo?.JobApplications?.Select(applications => applications.JobApplicationID).ToList();
                jobApplicationIds?.AddRange(jaIds);
            });

            var jobApplicationSchedules = await this.jobApplicationQuery.GetSchedulesForJobApplications(jobApplicationIds, startDateTime);

            IList <UpcomingInterviews> upcomingInterviews = new List <UpcomingInterviews>();

            jobOpenings?.ForEach(jo =>
            {
                var jaIdsForJobOpening = jo?.JobApplications?.Where(applications => applications?.JobOpening?.ExternalJobOpeningID == jo.ExternalJobOpeningID)?
                                         .Select(applications => applications.JobApplicationID).ToList();

                var scheduleSummaries = jobApplicationSchedules?.Where(jas => jaIdsForJobOpening.Contains(jas.JobApplicationId)).ToList();

                if (scheduleSummaries.Any())
                {
                    scheduleSummaries?.ForEach(ss =>
                    {
                        ss.CandidateName = jo?.JobApplications?.FirstOrDefault(app => app.JobApplicationID == ss.JobApplicationId)?
                                           .Candidate?.FullName?.GivenName;
                    });

                    var upcomingInterviewForJobOpening = new UpcomingInterviews
                    {
                        ExternalJobOpeningId = jo.ExternalJobOpeningID,
                        PositionTitle        = jo.PositionTitle,
                        ScheduleSummaries    = scheduleSummaries?.OrderBy(ss => ss.ScheduleStartDateTime).ToList(),
                    };
                    upcomingInterviews.Add(upcomingInterviewForJobOpening);
                }
            });

            return(upcomingInterviews);
        }
        ////////////////////////////////////////////////////////////////////////////////////////////////////
        /// <summary>   Loads the given p file. </summary>
        ///
        /// <param name="PFile">    The file to load. </param>
        ////////////////////////////////////////////////////////////////////////////////////////////////////

        internal void Load(TextReader PFile)
        {
            preLearningRateBiases?.AddRange(Utility.LoadArray(PFile));
            preLearningRateWeights?.AddRange(Utility.LoadArray(PFile));
            preMomentumBiases?.AddRange(Utility.LoadArray(PFile));
            preMomentumWeights?.AddRange(Utility.LoadArray(PFile));
            fineLearningRateBiases?.AddRange(Utility.LoadArray(PFile));
            fineLearningRateWeights?.AddRange(Utility.LoadArray(PFile));
        }
        public void Process(IEvaluatedObject evaluatedObject)
        {
            ProductionLogEvaluated evaluatedLogObject = evaluatedObject as ProductionLogEvaluated;

            _removedObjects?.AddRange(evaluatedLogObject.MomentValueObjects.Where(x => x.ActualPressure >= _minRange && x.ActualPressure <= _maxRange));
            evaluatedLogObject.MomentValueObjects.RemoveAll(x => x.ActualPressure >= _minRange && x.ActualPressure <= _maxRange);

            _followUpProcessor?.Process(evaluatedLogObject);
        }
    public List <Parashah> CreateParashotDataIfNotExistAndLoad(
        bool reset    = false,
        bool noText   = false,
        bool keepMemo = false)
    {
        CheckConnected();
        if (CreateParashotDataMutex)
        {
            throw new SystemException($"{nameof(CreateParashotDataIfNotExistAndLoad)} is already running.");
        }
        bool temp = Globals.IsReady;

        Globals.IsReady         = false;
        CreateParashotDataMutex = true;
        try
        {
            if (reset || Connection.CountRows(ParashotTableName) != ParashotFactory.Instance.All.Count())
            {
                SystemManager.TryCatchManage(() =>
                {
                    Connection.BeginTransaction();
                    try
                    {
                        List <string> memos = keepMemo ? new List <string>() : null;
                        memos?.AddRange(Parashot.Select(p => p.Memo));
                        DeleteParashot(true);
                        var list = ParashotFactory.Instance.All.Select(p => p.Clone()).Cast <Parashah>().ToList();
                        if (noText)
                        {
                            list.ForEach(p => { p.Translation = ""; p.Lettriq = ""; p.Memo = ""; });
                        }
                        if (memos is not null)
                        {
                            for (int index = 0, indexCheck = 0; index < list.Count && indexCheck < memos.Count; index++)
                            {
                                list[index].Memo = memos[index];
                            }
                        }
                        Connection.InsertAll(list);
                        Connection.Commit();
                    }
                    catch
                    {
                        Connection.Rollback();
                        throw;
                    }
                });
            }
            return(LoadParashot());
        }
        finally
        {
            CreateParashotDataMutex = false;
            Globals.IsReady         = temp;
        }
    }
        //private static void CanTakeOrder_PostFix(Pawn pawn, bool __result)
        //{
        //    if (__result)
        //    {
        //        floatMenuID = Rand.Range(1000, 9999);
        //        DebugMessage("FMOL :: ID Set to " + floatMenuID);
        //    }
        //}

        // RimWorld.FloatMenuMakerMap
        public static void AddHumanlikeOrders_PostFix(Vector3 clickPos, Pawn pawn, List<FloatMenuOption> opts)
        {
            var c = IntVec3.FromVector3(clickPos);

            // Heuristic to prevent computing our custom orders if pawn + location + float menu option labels haven't changed.
            var optsIDBuilder = new StringBuilder(pawn.ThingID).Append(c);
            if (opts != null)
                for (int i = 0, count = opts.Count; i < count; i++)
                    optsIDBuilder.Append(opts[i].Label);
            optsID = optsIDBuilder.ToString();
            if (optsID == lastOptsID)
            {
                opts?.AddRange(savedList);
                return;
            }

            DebugMessage("FMOL :: New list constructed");
            DebugMessage(optsID);
            lastOptsID = optsID;
            savedList.Clear();
            var things = c.GetThingList(pawn.Map);
            if (things.Count == 0)
                return;
            foreach (var (condition, funcs) in floatMenuOptionList)
            {
                if (funcs.NullOrEmpty())
                    continue;
                foreach (var passer in things)
                {
                    if (!condition.Passes(passer))
                        continue;
                    foreach (var func in funcs)
                    {
                        if (func.Invoke(clickPos, pawn, passer) is List<FloatMenuOption> newOpts &&
                            newOpts.Count > 0)
                        {
                            opts?.AddRange(newOpts);
                            savedList.AddRange(newOpts);
                        }
                    }
                }
            }
        }
Example #51
0
        public void InferType(
            Dictionary <string, Type> inputTypes,
            [Out] List <Type> inType,
            [Out] List <Type> auxType,
            [Out] List <Type> outType)
        {
            var keys        = new List <string>();
            var argTypeData = new List <int>();


            foreach (var arg in inputTypes)
            {
                keys.Add(arg.Key);
                argTypeData.Add(Util.DtypeNpToMx[arg.Value]);
            }


            uint   inTypeSize;
            IntPtr inTypeDataPtr;

            uint   outTypeSize;
            IntPtr outTypeDataPtr;

            uint   auxTypeSize;
            IntPtr auxTypeDataPtr;

            int complete;

            Util.CallCheck(NativeMethods.MXSymbolInferType(get_handle(), (uint)keys.Count, keys.ToArray(),
                                                           argTypeData.ToArray(),
                                                           out inTypeSize, out inTypeDataPtr,
                                                           out outTypeSize, out outTypeDataPtr,
                                                           out auxTypeSize, out auxTypeDataPtr,
                                                           out complete));

            var inTypeData  = PtrToArrayInt32(inTypeDataPtr, (int)inTypeSize);
            var outTypeData = PtrToArrayInt32(outTypeDataPtr, (int)outTypeSize);
            var auxTypeData = PtrToArrayInt32(auxTypeDataPtr, (int)auxTypeSize);

            if (complete > 0)
            {
                if (inTypeSize != 0)
                {
                    inType?.AddRange(inTypeData.Select(s => Util.DtypeMxToNp[s]));
                }
                if (outTypeSize != 0)
                {
                    outType?.AddRange(outTypeData.Select(s => Util.DtypeMxToNp[s]));
                }
                if (auxTypeSize != 0)
                {
                    auxType?.AddRange(auxTypeData.Select(s => Util.DtypeMxToNp[s]));
                }
            }
        }
Example #52
0
        private string AssembleShaderCode()
        {
            string source_code = "";

            switch (_type)
            {
            case TType.texture_test1: source_code = Code_Texture_Test1(); break;

            case TType.heightmap_test1: source_code = Code_HeightMap_Test1(); break;

            case TType.cone_step_map: source_code = Code_ConeStepMap(); break;
            }
            if (source_code == null || source_code == "")
            {
                return("");
            }

            string final_code = "#version 460\n";

            List <ITexture> all_textures = new List <ITexture>();

            all_textures?.AddRange(_out_textures);
            if (_in_textures != null)
            {
                all_textures?.AddRange(_in_textures);
            }
            for (int i = 0; i < all_textures.Count; ++i)
            {
                string format_str = "rgba8";
                switch (all_textures[i].InternalFormat)
                {
                case ITexture.Format.RGBA_8: format_str = "rgba8"; break;

                case ITexture.Format.RGBA_F32: format_str = "rgba32f"; break;
                }
                final_code += "#define IMAGE_FORMAT_" + i.ToString() + " " + format_str + "\n";
            }

            final_code += source_code;

            return(final_code);
        }
Example #53
0
        public void LoadStoryboard(string dir, OsuFile osu)
        {
            ClearLayer();

            List <Element> backEle = null;
            List <Element> foreEle = null;
            Stopwatch      sw      = new Stopwatch();

            Console.WriteLine(@"Parsing..");
            sw.Start();
            string osbFile = Path.Combine(dir, osu.OsbFileName);

            if (osu.Events.ElementGroup != null)
            {
                var osb = osu.Events.ElementGroup;

                sw.Restart();
                osb.Expand();
                Console.WriteLine($@"Osu's osb expanded done in {sw.ElapsedMilliseconds} ms");

                FillLayerList(ref backEle, ref foreEle, osb);
            }

            if (File.Exists(osbFile))
            {
                sw.Restart();
                var osb = ElementGroup.Parse(osbFile);
                Console.WriteLine($@"Parse osb done in {sw.ElapsedMilliseconds} ms");

                sw.Restart();
                osb.Expand();
                Console.WriteLine($@"Osb expanded done in {sw.ElapsedMilliseconds} ms");

                FillLayerList(ref backEle, ref foreEle, osb);
            }

            sw.Stop();
            Directory = dir;
            if (backEle == null && foreEle == null)
            {
                return;
            }
            StoryboardTiming.Reset();
            if (foreEle != null)
            {
                backEle?.AddRange(foreEle);
            }
            HwndRenderBase.AddLayers(new CustomLayer[]
            {
                new StoryboardLayer(HwndRenderBase.RenderTarget, backEle ?? foreEle, StoryboardTiming),
                new FpsLayer(HwndRenderBase.RenderTarget),
            });
            StoryboardTiming.Start();
        }
Example #54
0
        public IInterceptor[] SelectInterceptors(Type type, MethodInfo method, IInterceptor[] interceptors)
        {
            List <MethodInterceptionBaseAttribute> classAttributes =
                type?.GetCustomAttributes <MethodInterceptionBaseAttribute>(true).ToList();
            var methodAttributes = type?.GetMethod(method.Name)?.GetCustomAttributes <MethodInterceptionBaseAttribute>(true);

            classAttributes?.AddRange(methodAttributes);

            // ReSharper disable once CoVariantArrayConversion
            return(classAttributes?.OrderByDescending(x => x.Priority).ToArray());
        }
 public Task <string> GetLogsAsync(string channelName, int limit, List <Log> logs)
 {
     lock (this)
     {
         var batchId = Guid.NewGuid().ToString();
         var batch   = this[channelName].Take(limit).ToList();
         _pending.Add(batchId, batch);
         logs?.Clear();
         logs?.AddRange(batch);
         return(TaskExtension.GetCompletedTask(batchId));
     }
 }
Example #56
0
        private void GridBind(int status)
        {
            roleId = Convert.ToInt32(Session["RoleId"]);
            var rq = new RequestHandler();

            var list = rq.GetStudentRequestListForStudentOffice(status);

            _reqlist = list?.ToList();
            switch (status)
            {
            case 1:
                _reqlist = _reqlist?.Where(x => (x.Status == 1 || x.Status == 6)).ToList();
                break;

            case 2:
                _reqlist = _reqlist?.Where(x => x.Status == 2).ToList();
                break;

            case 5:

                break;

            case 6:
                var reqList = rq.GetStudentRequestListForStudentOffice(5)?.ToList();
                if (reqList != null)
                {
                    _reqlist?.AddRange(reqList);
                }

                break;
            }
            if (roleId != 1 && roleId != 50)
            {
                var location = "";
                switch (roleId)
                {
                case 37:
                case 38:
                    location = "ملاصدرا";
                    break;

                case 39:
                case 40:
                    location = "رام";
                    break;
                }

                _reqlist = _reqlist?.Where(x => x.Location.Contains(location)).ToList();
            }

            grdRequestList.DataSource = _reqlist;
            grdRequestList.DataBind();
        }
Example #57
0
        private static QuickPulseCollectionStateManager CreateManager(
            IQuickPulseServiceClient serviceClient,
            Clock timeProvider,
            List <string> actions,
            List <QuickPulseDataSample> returnedSamples = null,
            QuickPulseTimings timings = null,
            List <CollectionConfigurationInfo> collectionConfigurationInfos = null)
        {
            var manager = new QuickPulseCollectionStateManager(
                serviceClient,
                timeProvider,
                timings ?? QuickPulseTimings.Default,
                () => actions.Add(StartCollectionMessage),
                () => actions.Add(StopCollectionMessage),
                () =>
            {
                actions.Add(CollectMessage);

                CollectionConfigurationError[] errors;
                var now = DateTimeOffset.UtcNow;
                return
                (new[]
                {
                    new QuickPulseDataSample(
                        new QuickPulseDataAccumulator(
                            new CollectionConfiguration(EmptyCollectionConfigurationInfo, out errors, timeProvider))
                    {
                        AIRequestSuccessCount = 5,
                        StartTimestamp = now,
                        EndTimestamp = now.AddSeconds(1)
                    },
                        new Dictionary <string, Tuple <PerformanceCounterData, double> >(),
                        Enumerable.Empty <Tuple <string, int> >(),
                        false)
                }.ToList());
            },
                samples =>
            {
                returnedSamples?.AddRange(samples);
            },
                collectionConfigurationInfo =>
            {
                actions.Add(UpdatedConfigurationMessage);
                collectionConfigurationInfos?.Add(collectionConfigurationInfo);

                CollectionConfigurationError[] errors;
                new CollectionConfiguration(collectionConfigurationInfo, out errors, timeProvider);
                return(errors);
            },
                _ => { });

            return(manager);
        }
Example #58
0
        /// <summary>
        /// Asynchronously retrieves logs from storage and flags them to avoid duplicate retrievals on subsequent calls
        /// </summary>
        /// <param name="channelName">Name of the channel to retrieve logs from</param>
        /// <param name="limit">The maximum number of logs to retrieve</param>
        /// <param name="logs">A list to which the retrieved logs will be added</param>
        /// <returns>A batch ID for the set of returned logs; null if no logs are found</returns>
        /// <exception cref="StorageException"/>
        public Task <string> GetLogsAsync(string channelName, int limit, List <Log> logs)
        {
            return(AddTaskToQueue(() =>
            {
                logs?.Clear();
                var retrievedLogs = new List <Log>();
                AppCenterLog.Debug(AppCenterLog.LogTag,
                                   $"Trying to get up to {limit} logs from storage for {channelName}");
                var idPairs = new List <Tuple <Guid?, long> >();
                var failedToDeserializeALog = false;
                var objectEntries = _storageAdapter.Select(TableName, ColumnChannelName, channelName, ColumnIdName, _pendingDbIdentifiers.Cast <object>().ToArray(), limit);
                var retrievedEntries = objectEntries.Select(entries =>
                                                            new LogEntry()
                {
                    Id = (long)entries[0],
                    Channel = (string)entries[1],
                    Log = (string)entries[2]
                }
                                                            ).ToList();
                foreach (var entry in retrievedEntries)
                {
                    try
                    {
                        var log = LogSerializer.DeserializeLog(entry.Log);
                        retrievedLogs.Add(log);
                        idPairs.Add(Tuple.Create(log.Sid, Convert.ToInt64(entry.Id)));
                    }
                    catch (JsonException e)
                    {
                        AppCenterLog.Error(AppCenterLog.LogTag, "Cannot deserialize a log in storage", e);
                        failedToDeserializeALog = true;
                        _storageAdapter.Delete(TableName, ColumnIdName, entry.Id);
                    }
                }
                if (failedToDeserializeALog)
                {
                    AppCenterLog.Warn(AppCenterLog.LogTag, "Deleted logs that could not be deserialized");
                }
                if (idPairs.Count == 0)
                {
                    AppCenterLog.Debug(AppCenterLog.LogTag,
                                       $"No available logs in storage for channel '{channelName}'");
                    return null;
                }

                // Process the results
                var batchId = Guid.NewGuid().ToString();
                ProcessLogIds(channelName, batchId, idPairs);
                logs?.AddRange(retrievedLogs);
                return batchId;
            }));
        }
Example #59
0
        /// <summary>
        /// Asynchronously retrieves logs from storage and flags them to avoid duplicate retrievals on subsequent calls
        /// </summary>
        /// <param name="channelName">Name of the channel to retrieve logs from</param>
        /// <param name="limit">The maximum number of logs to retrieve</param>
        /// <param name="logs">A list to which the retrieved logs will be added</param>
        /// <returns>A batch ID for the set of returned logs; null if no logs are found</returns>
        /// <exception cref="StorageException"/>
        public Task <string> GetLogsAsync(string channelName, int limit, List <Log> logs)
        {
            return(AddTaskToQueue(() =>
            {
                logs?.Clear();
                var retrievedLogs = new List <Log>();
                AppCenterLog.Debug(AppCenterLog.LogTag,
                                   $"Trying to get up to {limit} logs from storage for {channelName}");
                var idPairs = new List <Tuple <Guid?, long> >();
                var failedToDeserializeALog = false;
                var retrievedEntries =
                    _storageAdapter.GetAsync <LogEntry>(entry => entry.Channel == channelName, limit)
                    .GetAwaiter().GetResult();
                foreach (var entry in retrievedEntries)
                {
                    if (_pendingDbIdentifiers.Contains(entry.Id))
                    {
                        continue;
                    }
                    try
                    {
                        var log = LogSerializer.DeserializeLog(entry.Log);
                        retrievedLogs.Add(log);
                        idPairs.Add(Tuple.Create(log.Sid, Convert.ToInt64(entry.Id)));
                    }
                    catch (JsonException e)
                    {
                        AppCenterLog.Error(AppCenterLog.LogTag, "Cannot deserialize a log in storage", e);
                        failedToDeserializeALog = true;
                        _storageAdapter.DeleteAsync <LogEntry>(row => row.Id == entry.Id)
                        .GetAwaiter().GetResult();
                    }
                }
                if (failedToDeserializeALog)
                {
                    AppCenterLog.Warn(AppCenterLog.LogTag, "Deleted logs that could not be deserialized");
                }
                if (idPairs.Count == 0)
                {
                    AppCenterLog.Debug(AppCenterLog.LogTag,
                                       $"No available logs in storage for channel '{channelName}'");
                    return null;
                }

                // Process the results
                var batchId = Guid.NewGuid().ToString();
                ProcessLogIds(channelName, batchId, idPairs);
                logs?.AddRange(retrievedLogs);
                return batchId;
            }));
        }
Example #60
0
        private MessageModel SetLanguagePairInformation(
            IProject newProject,
            PackageModel package)
        {
            if (package?.LanguagePairs != null)
            {
                foreach (var pair in package.LanguagePairs)
                {
                    if (!pair.TargetFile.Any() || pair.TargetFile.Count == 0)
                    {
                        _messageModel.IsProjectCreated = false;
                        _messageModel.Message          =
                            "Project was not created correctly because no target files were found in the package!";
                        _messageModel.Title = "Informative message";
                        return(_messageModel);
                    }

                    if (pair.CreateNewTm)
                    {
                        //TODO:Investigate and refactor
                        foreach (var starTmMetadata in pair.StarTranslationMemoryMetadatas)
                        {
                            AddTmPenalties(package, starTmMetadata);
                            AddMtMemories(package, starTmMetadata);
                        }

                        //TODO: Investigate if we really need this later we'll join the mt and tms becasue
                        // Remove found items from pair.StarTranslationMemoryMetadatas (the remained ones are those which does not have penalties set on them)
                        foreach (var item in _penaltiesTmsList)
                        {
                            pair.StarTranslationMemoryMetadatas.Remove(item);
                        }

                        // Remove Machine Translation memories from pair.StarTranslationMemoryMetadatas, if the user requests them, they will be imported separately, but never in the main TM
                        pair.StarTranslationMemoryMetadatas.RemoveAll(item =>
                                                                      Path.GetFileName(item?.TargetFile ?? "").Contains("_AEXTR_MT_"));
                    }

                    _targetProjectFiles?.Clear();

                    // Import language pair TM if any
                    ImportLanguagePairTm(pair, newProject, package);

                    _targetProjectFiles?.AddRange(newProject.AddFiles(pair.TargetFile.ToArray()));
                    _messageModel = UpdateProjectSettings(newProject);
                }
                _projectsController?.RefreshProjects();
            }
            return(_messageModel);
        }