System.Diagnostics.Debug.Assert(bool)

Here are the examples of the csharp api System.Diagnostics.Debug.Assert(bool) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

12000 Examples 7

19 View Source File : AddToSccCommands.cs
License : Apache License 2.0
Project Creator : AmpScm

static void SetProjectsManaged(CommandEventArgs e)
        {
            ISvnStatusCache cache = e.GetService<ISvnStatusCache>();
            IFileStatusMonitor monitor = e.GetService<IFileStatusMonitor>();
            IAnkhSccService scc = e.GetService<IAnkhSccService>();
            IProjectFileMapper mapper = e.GetService<IProjectFileMapper>();
            AnkhMessageBox mb = new AnkhMessageBox(e.Context);

            if (mapper == null)
                return;

            List<SccProject> projectsToBeManaged = new List<SccProject>();
            SvnItem slnItem = cache[e.Selection.SolutionFilename];
            Uri solutionReposRoot = null;
            if (slnItem.WorkingCopy != null)
            {
                solutionReposRoot = slnItem.WorkingCopy.RepositoryRoot;

                foreach (SccProject project in GetSelection(e.Selection))
                {
                    ISccProjectInfo projInfo = mapper.GetProjectInfo(project);

                    if (projInfo == null || projInfo.ProjectDirectory == null
                        || !projInfo.IsSccBindable)
                        continue; // Some projects can't be managed

                    SvnItem projectDir = cache[projInfo.ProjectDirectory];

                    if (projectDir.WorkingCopy == slnItem.WorkingCopy)
                    {
                        // This is a 'normal' project, part of the solution and in the same working copy
                        projectsToBeManaged.Add(project);
                        continue;
                    }

                    bool markAsManaged;
                    bool writeReference;

                    if (projectDir.IsVersioned)
                        continue; // We don't have to add this one
                    if (projectDir.IsVersionable)
                    {
                        SvnItem parentDir = GetVersionedParent(projectDir);
                        Debug.replacedert(parentDir != null);

                        DialogResult rslt = mb.Show(string.Format(CommandStrings.AddXToExistingWcY,
                                                                  projInfo.ProjectName,
                                                                  parentDir.FullPath), AnkhId.PlkProduct, MessageBoxButtons.YesNoCancel);

                        switch (rslt)
                        {
                            case DialogResult.Cancel:
                                return;
                            case DialogResult.No:
                                if (CheckoutWorkingCopyForProject(e, project, projInfo, solutionReposRoot, out markAsManaged, out writeReference))
                                {
                                    if (markAsManaged)
                                        scc.SetProjectManaged(project, true);
                                    if (writeReference)
                                        scc.EnsureCheckOutReference(project);

                                    continue;
                                }
                                break;
                            case DialogResult.Yes:
                                projectsToBeManaged.Add(project);
                                AddPathToSubversion(e, projInfo.ProjectFile ?? projInfo.ProjectDirectory);
                                continue;
                        }
                    }
                    else
                    {
                        // We have to checkout (and create repository location)
                        if (CheckoutWorkingCopyForProject(e, project, projInfo, solutionReposRoot, out markAsManaged, out writeReference))
                        {
                            if (markAsManaged)
                                scc.SetProjectManaged(project, true);
                            if (writeReference)
                                scc.EnsureCheckOutReference(project);

                            continue;
                        }
                    }
                }
            }

            if (!AskSetManagedSelectionProjects(e, mapper, scc, projectsToBeManaged))
                return;

            foreach (SccProject project in projectsToBeManaged)
            {
                if (!scc.IsProjectManaged(project))
                {
                    scc.SetProjectManaged(project, true);

                    monitor.ScheduleSvnStatus(mapper.GetAllFilesOf(project)); // Update for 'New' status
                }
            }
        }

19 View Source File : LogCommand.cs
License : Apache License 2.0
Project Creator : AmpScm

public override void OnUpdate(CommandUpdateEventArgs e)
        {
            int i;

            switch (e.Command)
            {
                case AnkhCommand.ProjectHistory:
                    SccProject p = EnumTools.GetFirst(e.Selection.GetSelectedProjects(false));
                    if (p == null)
                        break;

                    ISccProjectInfo pi = e.GetService<IProjectFileMapper>().GetProjectInfo(p);

                    if (pi == null || string.IsNullOrEmpty(pi.ProjectDirectory))
                        break; // No project location

                    if (e.GetService<ISvnStatusCache>()[pi.ProjectDirectory].HasCopyableHistory)
                        return; // Ok, we have history!                                           

                    break; // No history

                case AnkhCommand.SolutionHistory:
                    IAnkhSolutionSettings ss = e.GetService<IAnkhSolutionSettings>();

                    if (ss == null || string.IsNullOrEmpty(ss.ProjectRoot))
                        break;

                    if (e.GetService<ISvnStatusCache>()[ss.ProjectRoot].HasCopyableHistory)
                        return; // Ok, we have history!

                    break; // No history
                case AnkhCommand.DoreplacedentHistory:
                    SvnItem docitem = e.Selection.ActiveDoreplacedentSvnItem;
                    if (docitem != null && docitem.HasCopyableHistory)
                        return;
                    break; // No history
                case AnkhCommand.Log:
                    int itemCount = 0;
                    int needsRemoteCount = 0;
                    foreach (SvnItem item in e.Selection.GetSelectedSvnItems(false))
                    {
                        if (!item.IsVersioned)
                        {
                            e.Enabled = false;
                            return;
                        }

                        if (item.IsReplaced || item.IsAdded)
                        {
                            if (item.HasCopyableHistory)
                                needsRemoteCount++;
                            else
                            {
                                e.Enabled = false;
                                return;
                            }
                        }
                        itemCount++;
                    }
                    if (itemCount == 0 || (needsRemoteCount != 0 && itemCount > 1))
                    {
                        e.Enabled = false;
                        return;
                    }
                    if (needsRemoteCount >= 1)
                    {
                        // One remote log
                        Debug.replacedert(needsRemoteCount == 1);
                        return;
                    }
                    
                    // Local log only
                    return;
                case AnkhCommand.ReposExplorerLog:
                    i = 0;
                    foreach (ISvnRepositoryItem item in e.Selection.GetSelection<ISvnRepositoryItem>())
                    {
                        if (item == null || item.Origin == null)
                            continue;
                        i++;
                        break;
                    }
                    if (i >= 1)
                        return;
                    break;
                case AnkhCommand.AnnotateShowLog:
                    IAnnotateSection section = EnumTools.GetSingle(e.Selection.GetSelection<IAnnotateSection>());
                    if (section != null && section.Revision >= 0)
                        return;
                    break;
            }
            e.Enabled = false;
        }

19 View Source File : LogCommand.cs
License : Apache License 2.0
Project Creator : AmpScm

public override void OnExecute(CommandEventArgs e)
        {
            List<SvnOrigin> selected = new List<SvnOrigin>();
            ISvnStatusCache cache = e.GetService<ISvnStatusCache>();

            switch (e.Command)
            {
                case AnkhCommand.Log:
                    IAnkhDiffHandler diffHandler = e.GetService<IAnkhDiffHandler>();
                    List<SvnOrigin> items = new List<SvnOrigin>();
                    foreach (SvnItem i in e.Selection.GetSelectedSvnItems(false))
                    {
                        Debug.replacedert(i.IsVersioned);

                        if (i.IsReplaced || i.IsAdded)
                        {
                            if (!i.HasCopyableHistory)
                                continue;

                            items.Add(new SvnOrigin(diffHandler.GetCopyOrigin(i), i.WorkingCopy.RepositoryRoot));
                            continue;
                        }

                        items.Add(new SvnOrigin(i));
                    }
                    PerformLog(e.Context, items, null, null);
                    break;
                case AnkhCommand.SolutionHistory:
                    IAnkhSolutionSettings settings = e.GetService<IAnkhSolutionSettings>();

                    PerformLog(e.Context, new SvnOrigin[] { new SvnOrigin(cache[settings.ProjectRoot]) }, null, null);
                    break;
                case AnkhCommand.ProjectHistory:
                    IProjectFileMapper mapper = e.GetService<IProjectFileMapper>();
                    foreach (SccProject p in e.Selection.GetSelectedProjects(false))
                    {
                        ISccProjectInfo info = mapper.GetProjectInfo(p);

                        if (info != null)
                            selected.Add(new SvnOrigin(cache[info.ProjectDirectory]));
                    }

                    PerformLog(e.Context, selected, null, null);
                    break;
                case AnkhCommand.DoreplacedentHistory:
                    SvnItem docItem = e.Selection.ActiveDoreplacedentSvnItem;
                    Debug.replacedert(docItem != null);

                    PerformLog(e.Context, new SvnOrigin[] { new SvnOrigin(docItem) }, null, null);
                    break;
                case AnkhCommand.ReposExplorerLog:
                    foreach (ISvnRepositoryItem i in e.Selection.GetSelection<ISvnRepositoryItem>())
                    {
                        if (i != null && i.Origin != null)
                            selected.Add(i.Origin);
                    }

                    if (selected.Count > 0)
                        PerformLog(e.Context, selected, null, null);
                    break;
                case AnkhCommand.AnnotateShowLog:
                    IAnnotateSection section = EnumTools.GetSingle(e.Selection.GetSelection<IAnnotateSection>());

                    if (section == null)
                        return;

                    PerformLog(e.Context, new SvnOrigin[] { section.Origin }, section.Revision, null);

                    break;
            }
        }

19 View Source File : SolutionUpdateCommand.cs
License : Apache License 2.0
Project Creator : AmpScm

public override void OnExecute(CommandEventArgs e)
        {
            IAnkhServiceEvents ci = e.GetService<IAnkhServiceEvents>();

            if (ci != null)
                ci.OnLastChanged(new LastChangedEventArgs(null, null));

            SvnRevision rev;
            bool allowUnversionedObstructions = false;
            bool updateExternals = true;
            bool setDepthInfinity = true;

            IAnkhSolutionSettings settings = e.GetService<IAnkhSolutionSettings>();
            ISvnStatusCache cache = e.GetService<ISvnStatusCache>();
            IProjectFileMapper mapper = e.GetService<IProjectFileMapper>();
            Uri reposRoot = null;

            if (IsHeadCommand(e.Command) || e.DontPrompt)
                rev = SvnRevision.Head;
            else if (IsSolutionCommand(e.Command))
            {
                SvnItem projecreplacedem = settings.ProjectRootSvnItem;

                Debug.replacedert(projecreplacedem != null, "Has item");

                using (UpdateDialog ud = new UpdateDialog())
                {
                    ud.ItemToUpdate = projecreplacedem;
                    ud.Revision = SvnRevision.Head;

                    if (ud.ShowDialog(e.Context) != DialogResult.OK)
                        return;

                    rev = ud.Revision;
                    allowUnversionedObstructions = ud.AllowUnversionedObstructions;
                    updateExternals = ud.UpdateExternals;
                    setDepthInfinity = ud.SetDepthInfinty;
                }
            }
            else if (IsFolderCommand(e.Command))
            {
                SvnItem dirItem = EnumTools.GetFirst(e.Selection.GetSelectedSvnItems(false));

                Debug.replacedert(dirItem != null && dirItem.IsDirectory && dirItem.IsVersioned);

                using (UpdateDialog ud = new UpdateDialog())
                {
                    ud.Text = CommandStrings.UpdateFolder;
                    ud.FolderLabelText = CommandStrings.UpdateFolderLabel;
                    ud.ItemToUpdate = dirItem;
                    ud.Revision = SvnRevision.Head;

                    if (ud.ShowDialog(e.Context) != DialogResult.OK)
                        return;

                    rev = ud.Revision;
                    allowUnversionedObstructions = ud.AllowUnversionedObstructions;
                    updateExternals = ud.UpdateExternals;
                    setDepthInfinity = ud.SetDepthInfinty;
                }
            }
            else
            {
                // We checked there was only a single repository to select a revision 
                // from in OnUpdate, so we can suffice with only calculate the path

                SvnItem si = null;
                SvnOrigin origin = null;
                foreach (SccProject p in GetSelectedProjects(e))
                {
                    ISccProjectInfo pi = mapper.GetProjectInfo(p);
                    if (pi == null || pi.ProjectDirectory == null)
                        continue;

                    SvnItem item = cache[pi.ProjectDirectory];
                    if (!item.IsVersioned)
                        continue;

                    if (si == null && origin == null)
                    {
                        si = item;
                        origin = new SvnOrigin(item);
                        reposRoot = item.WorkingCopy.RepositoryRoot;
                    }
                    else
                    {
                        si = null;
                        string urlPath1 = origin.Uri.AbsolutePath;
                        string urlPath2 = item.Uri.AbsolutePath;

                        int i = 0;
                        while (i < urlPath1.Length && i < urlPath2.Length
                            && urlPath1[i] == urlPath2[i])
                        {
                            i++;
                        }

                        while (i > 0 && urlPath1[i - 1] != '/')
                            i--;

                        origin = new SvnOrigin(new Uri(origin.Uri, urlPath1.Substring(0, i)), origin.RepositoryRoot);
                    }
                }

                Debug.replacedert(origin != null);

                using (UpdateDialog ud = new UpdateDialog())
                {
                    ud.Text = CommandStrings.UpdateProject;

                    if (si != null)
                        ud.ItemToUpdate = si;
                    else
                    {
                        ud.SvnOrigin = origin;
                        ud.SetMultiple(true);
                    }

                    ud.Revision = SvnRevision.Head;

                    if (ud.ShowDialog(e.Context) != DialogResult.OK)
                        return;

                    rev = ud.Revision;
                    allowUnversionedObstructions = ud.AllowUnversionedObstructions;
                    updateExternals = ud.UpdateExternals;
                    setDepthInfinity = ud.SetDepthInfinty;
                }
            }

            Dictionary<string, SvnItem> itemsToUpdate = new Dictionary<string, SvnItem>(StringComparer.OrdinalIgnoreCase);
            SortedList<string, UpdateGroup> groups = new SortedList<string, UpdateGroup>(StringComparer.OrdinalIgnoreCase);

            // Get a list of all doreplacedents below the specified paths that are open in editors inside VS
            HybridCollection<string> lockPaths = new HybridCollection<string>(StringComparer.OrdinalIgnoreCase);
            IAnkhOpenDoreplacedentTracker doreplacedentTracker = e.GetService<IAnkhOpenDoreplacedentTracker>();

            foreach (SvnItem item in GetAllUpdateRoots(e))
            {
                // GetAllUpdateRoots can (and probably will) return duplicates!

                if (itemsToUpdate.ContainsKey(item.FullPath) || !item.IsVersioned)
                    continue;

                SvnWorkingCopy wc = item.WorkingCopy;

                if (!IsHeadCommand(e.Command) && reposRoot != null)
                {
                    // Specific revisions are only valid on a single repository!
                    if (wc != null && wc.RepositoryRoot != reposRoot)
                        continue;
                }

                UpdateGroup group;

                if (!groups.TryGetValue(wc.FullPath, out group))
                {
                    group = new UpdateGroup(wc.FullPath);
                    groups.Add(wc.FullPath, group);
                }

                group.Nodes.Add(item.FullPath);
                itemsToUpdate.Add(item.FullPath, item);

                foreach (string file in doreplacedentTracker.GetDoreplacedentsBelow(item.FullPath))
                {
                    if (!lockPaths.Contains(file))
                        lockPaths.Add(file);
                }
            }

            doreplacedentTracker.SaveDoreplacedents(lockPaths); // Make sure all files are saved before updating/merging!

            using (DoreplacedentLock lck = doreplacedentTracker.LockDoreplacedents(lockPaths, DoreplacedentLockType.NoReload))
            using (lck.MonitorChangesForReload())
            {
                SvnUpdateResult updateResult = null;

                ProgressRunnerArgs pa = new ProgressRunnerArgs();
                pa.CreateLog = true;

                string replacedle;

                if (IsSolutionCommand(e.Command))
                    replacedle = CommandStrings.UpdatingSolution;
                else if (IsFolderCommand(e.Command))
                    replacedle = CommandStrings.UpdatingFolder;
                else
                    replacedle = CommandStrings.UpdatingProject;

                IConflictHandler ih = e.Context.GetService<IConflictHandler>();

                e.GetService<IProgressRunner>().RunModal(replacedle, pa,
                    delegate(object sender, ProgressWorkerArgs a)
                    {
                        PerformUpdate(e, a, rev, allowUnversionedObstructions, updateExternals, setDepthInfinity, groups.Values, ih, out updateResult);
                    });

                if (ci != null && updateResult != null && IsSolutionCommand(e.Command))
                {
                    ci.OnLastChanged(new LastChangedEventArgs(CommandStrings.UpdatedToreplacedle, updateResult.Revision.ToString()));
                }
            }
        }

19 View Source File : MyersDiff.cs
License : Apache License 2.0
Project Creator : AmpScm

public EditScript Execute()
        {
            ArrayList MatchPoints = new ArrayList();

            SubArray A = new SubArray(m_arA);
            SubArray B = new SubArray(m_arB);

            GetMatchPoints(A, B, MatchPoints);

            Debug.replacedert(MatchPoints.Count == GetLCSLength(), "The number of match points must equal the LCS length.");

            EditScript Script = ConvertMatchPointsToEditScript(A.Length, B.Length, MatchPoints);
            Debug.replacedert(Script.TotalEditLength == GetSESLength());

            return Script;
        }

19 View Source File : MyersDiff.cs
License : Apache License 2.0
Project Creator : AmpScm

public int GetSESLength()
        {
            SubArray A = new SubArray(m_arA);
            SubArray B = new SubArray(m_arB);

            if (SetupFicreplacediousPoints(A, B))
            {
                int N = m_arA.Length;
                int M = m_arB.Length;

                for (int D = 0; D <= N + M; D++)
                {
                    for (int k = -D; k <= D; k += 2)
                    {
                        int x = GetForwardDPaths(A, B, D, k);
                        int y = x - k;
                        if (x >= N && y >= M)
                        {
                            return D;
                        }
                    }
                }

                //We should never get here if the algorithm is coded correctly.
                Debug.replacedert(false);
                return -1;
            }
            else if (m_arA.Length == 0)
            {
                return m_arB.Length;
            }
            else
            {
                return m_arA.Length;
            }
        }

19 View Source File : MyersDiff.cs
License : Apache License 2.0
Project Creator : AmpScm

public int GetReverseSESLength()
        {
            SubArray A = new SubArray(m_arA);
            SubArray B = new SubArray(m_arB);

            if (SetupFicreplacediousPoints(A, B))
            {
                int N = m_arA.Length;
                int M = m_arB.Length;
                int iDelta = N - M;

                for (int D = 0; D <= N + M; D++)
                {
                    for (int k = -D; k <= D; k += 2)
                    {
                        int x = GetReverseDPaths(A, B, D, k, iDelta);
                        int y = x - (k + iDelta);
                        if (x <= 0 && y <= 0)
                        {
                            return D;
                        }
                    }
                }

                //We should never get here if the algorithm is coded correctly.
                Debug.replacedert(false);
                return -1;
            }
            else if (m_arA.Length == 0)
            {
                return m_arB.Length;
            }
            else
            {
                return m_arA.Length;
            }
        }

19 View Source File : MyersDiff.cs
License : Apache License 2.0
Project Creator : AmpScm

private int FindMiddleSnake(SubArray A, SubArray B, out int iPathStartX, out int iPathEndX, out int iPathK)
        {
            //We don't have to check the result of this because the calling procedure
            //has already check the length preconditions.
            SetupFicreplacediousPoints(A, B);

            iPathStartX = -1;
            iPathEndX = -1;
            iPathK = 0;

            int iDelta = A.Length - B.Length;
            int iCeiling = (int)Math.Ceiling((A.Length + B.Length) / 2.0);

            for (int D = 0; D <= iCeiling; D++)
            {
                for (int k = -D; k <= D; k += 2)
                {
                    //Find the end of the furthest reaching forward D-path in diagonal k.
                    GetForwardDPaths(A, B, D, k);
                    //If iDelta is odd (i.e. remainder == 1 or -1) and ...
                    if ((iDelta % 2 != 0) && (k >= (iDelta - (D - 1)) && k <= (iDelta + (D - 1))))
                    {
                        //If the path overlaps the furthest reaching reverse (D-1)-path in diagonal k.
                        if (m_vecForward[k] >= m_vecReverse[k])
                        {
                            //The last snake of the forward path is the middle snake.
                            iPathK = k;
                            iPathEndX = m_vecForward[k];
                            iPathStartX = iPathEndX;
                            int iPathStartY = iPathStartX - iPathK;
                            while (iPathStartX > 0 && iPathStartY > 0 && A[iPathStartX] == B[iPathStartY])
                            {
                                iPathStartX--;
                                iPathStartY--;
                            }
                            //Length of an SES is 2D-1.
                            return 2 * D - 1;
                        }
                    }
                }

                for (int k = -D; k <= D; k += 2)
                {
                    //Find the end of the furthest reaching reverse D=path in diagonal k+iDelta
                    GetReverseDPaths(A, B, D, k, iDelta);
                    //If iDelta is even and ...
                    if ((iDelta % 2 == 0) && ((k + iDelta) >= -D && (k + iDelta) <= D))
                    {
                        //If the path overlaps the furthest reaching forward D-path in diagonal k+iDelta.
                        if (m_vecReverse[k + iDelta] <= m_vecForward[k + iDelta])
                        {
                            //The last snake of the reverse path is the middle snake.
                            iPathK = k + iDelta;
                            iPathStartX = m_vecReverse[iPathK];
                            iPathEndX = iPathStartX;
                            int iPathEndY = iPathEndX - iPathK;
                            while (iPathEndX < A.Length && iPathEndY < B.Length && A[iPathEndX + 1] == B[iPathEndY + 1])
                            {
                                iPathEndX++;
                                iPathEndY++;
                            }
                            //Length of an SES is 2D.
                            return 2 * D;
                        }
                    }
                }
            }

            //We should never get here if the algorithm is coded correctly.
            Debug.replacedert(false);
            return -1;
        }

19 View Source File : DiffOptions.cs
License : Apache License 2.0
Project Creator : AmpScm

public static Color GetColorForEditType(EditType ET)
        {
            switch (ET)
            {
                case EditType.Change:
                    return ChangedColor;
                case EditType.Insert:
                    return InsertedColor;
                case EditType.Delete:
                    return DeletedColor;
            }

            Debug.replacedert(false);
            return Color.Transparent;
        }

19 View Source File : OpenDocumentTracker.cs
License : Apache License 2.0
Project Creator : AmpScm

public void DoDispose(SccDoreplacedentData data)
        {
            if (data == null)
                throw new ArgumentNullException("data");

            Debug.replacedert(_docMap[data.Name] == data);

            _docMap.Remove(data.Name);

            if (data.Cookie != 0)
            {
                Debug.replacedert(_cookieMap[data.Cookie] == data);

                _cookieMap.Remove(data.Cookie);
                data.Cookie = 0;
            }
        }

19 View Source File : SvnSccProvider.Projects.cs
License : Apache License 2.0
Project Creator : AmpScm

protected override void OnSolutionClosed()
        {
            Debug.replacedert(ProjectMap.ProjectCount == 0);
            Debug.replacedert(ProjectMap.UniqueFileCount == 0);

            try
            {
                ProjectMap.Clear();
                _unreloadable.Clear();
                StatusCache.ClearCache();

                // Clear status for reopening solution
                _managedSolution = false;
                _isDirty = false;
                Translate_ClearState();

                IPendingChangesManager mgr = GetService<IPendingChangesManager>();
                if (mgr != null)
                    mgr.Clear();
            }
            finally
            {
                base.OnSolutionClosed();
            }
        }

19 View Source File : KeyedNotifyCollection.cs
License : Apache License 2.0
Project Creator : AmpScm

public IDisposable BatchUpdate()
        {
            Debug.replacedert(_updateMode == 0);
            if (_updateMode == 0)
            {
                _updateMode = 1;
                return _monitor.BatchUpdate(DoneUpdate);
            }
            else
            {
                return null;
            }
        }

19 View Source File : NotifyCollection.cs
License : Apache License 2.0
Project Creator : AmpScm

public IDisposable BatchUpdate()
        {
            Debug.replacedert(_updateMode == 0);
            if (_updateMode == 0)
            {
                _updateMode = 1;
                return _monitor.BatchUpdate(DoneUpdate);
            }
            else
                return null;
        }

19 View Source File : DiagonalVector.cs
License : Apache License 2.0
Project Creator : AmpScm

private int GetActualIndex(int iUserIndex)
        {
            int iIndex = iUserIndex + m_iMax;
            Debug.replacedert(iIndex >= 0 && iIndex < m_arData.Length);
            return iIndex;
        }

19 View Source File : Functions.cs
License : Apache License 2.0
Project Creator : AmpScm

public static bool AreFilesDifferent(FileInfo Info1, FileInfo Info2)
        {
            //Before we open the files, compare the sizes.
            //If they are different, then the files are
            //certainly different.
            if (Info1.Length != Info2.Length)
            {
                return true;
            }

            using (FileStream FS1 = Info1.OpenRead())
            {
                using (FileStream FS2 = Info2.OpenRead())
                {
                    //The previous length check should ensure these are equal.
                    Debug.replacedert(FS1.Length == FS2.Length);

                    //They have the same lengths, so we have
                    //to check byte-by-byte.  As soon as we
                    //find a difference, we can quit.
                    int iByte1, iByte2;
                    do
                    {
                        iByte1 = FS1.ReadByte();
                        iByte2 = FS2.ReadByte();

                        if (iByte1 != iByte2)
                        {
                            return true;
                        }
                    }
                    while (iByte1 >= 0 && iByte2 >= 0);

                    //The files were byte-by-byte equal.
                    return false;
                }
            }
        }

19 View Source File : SccProjectData.cs
License : Apache License 2.0
Project Creator : AmpScm

public void Load()
        {
            if (_loaded || !_opened)
                return;

            _loaded = true;
            _checkedProjectFile = false;
            _projectFile = null;
            _svnProjectInstance = null;

            if (ExcludedFromScc)
                return;

            _inLoad = true;
            try
            {
                Debug.replacedert(_files.Count == 0);

                ISccProjectWalker walker = GetService<ISccProjectWalker>();

                if (walker != null)
                {
                    Dictionary<string, uint> ids = new Dictionary<string, uint>(StringComparer.OrdinalIgnoreCase);
                    foreach (string file in walker.GetSccFiles(ProjectHierarchy, VSItemId.Root, ProjectWalkDepth.AllDescendantsInHierarchy, ids))
                    {
                        AddPath(file, ids); // GetSccFiles returns normalized paths
                    }
                }

                IFileStatusMonitor monitor = GetService<IFileStatusMonitor>();
                if (monitor != null)
                {
                    // Make sure we see all files as possible pending changes
                    monitor.ScheduleGlyphUpdate(GetAllFiles());
                }
                Hook(true);
            }
            finally
            {
                _inLoad = false;
            }
        }

19 View Source File : SvnItem.cs
License : Apache License 2.0
Project Creator : AmpScm

void ISvnItemUpdate.RefreshTo(NoSccStatus status, SvnNodeKind nodeKind)
        {
            Debug.replacedert(status != NoSccStatus.Unknown);
            _ticked = false;
            RefreshTo(status, nodeKind);
        }

19 View Source File : SvnItem.State.cs
License : Apache License 2.0
Project Creator : AmpScm

public SvnItemState GetState(SvnItemState flagsToGet)
        {
            SvnItemState unavailable = flagsToGet & ~_validState;

            if (unavailable == 0)
                return _currentState & flagsToGet; // We have everything we need

            if (0 != (unavailable & MaskRefreshTo))
            {
                Debug.replacedert(_statusDirty != XBool.False);
                RefreshStatus();

                unavailable = flagsToGet & ~_validState;

                Debug.replacedert((~_validState & MaskRefreshTo) == 0, "RefreshMe() set all attributes it should");
            }

            if (0 != (unavailable & MaskGetAttributes))
            {
                UpdateAttributeInfo();

                unavailable = flagsToGet & ~_validState;

                Debug.replacedert((~_validState & MaskGetAttributes) == 0, "UpdateAttributeInfo() set all attributes it should");
            }

            if (0 != (unavailable & MaskUpdateSolution))
            {
                UpdateSolutionInfo();

                unavailable = flagsToGet & ~_validState;

                Debug.replacedert((~_validState & MaskUpdateSolution) == 0, "UpdateSolution() set all attributes it should");
            }

            if (0 != (unavailable & MaskDoreplacedentInfo))
            {
                UpdateDoreplacedentInfo();

                unavailable = flagsToGet & ~_validState;

                Debug.replacedert((~_validState & MaskDoreplacedentInfo) == 0, "UpdateDoreplacedentInfo() set all attributes it should");
            }

            if (0 != (unavailable & MaskVersionable))
            {
                UpdateVersionable();

                unavailable = flagsToGet & ~_validState;

                Debug.replacedert((~_validState & MaskVersionable) == 0, "UpdateVersionable() set all attributes it should");
            }

            if (0 != (unavailable & MaskMustLock))
            {
                UpdateMustLock();

                unavailable = flagsToGet & ~_validState;

                Debug.replacedert((~_validState & MaskMustLock) == 0, "UpdateMustLock() set all attributes it should");
            }

            if (0 != (unavailable & MaskTextFile))
            {
                UpdateTextFile();

                unavailable = flagsToGet & ~_validState;

                Debug.replacedert((~_validState & MaskTextFile) == 0, "UpdateTextFile() set all attributes it should");
            }

            if (0 != (unavailable & MaskWCRoot))
            {
                UpdateWCRoot();

                unavailable = flagsToGet & ~_validState;

                Debug.replacedert((~_validState & MaskWCRoot) == 0, "UpdateWCRoot() set all attributes it should");
            }

            if (0 != (unavailable & MaskIsAdministrativeArea))
            {
                UpdateAdministrativeArea();

                unavailable = flagsToGet &~_validState;

                Debug.replacedert((~_validState & MaskIsAdministrativeArea) == 0, "UpdateIsAdministrativeArea() set all attributes it should");
            }

            if (unavailable != 0)
            {
                Trace.WriteLine(string.Format("Don't know how to retrieve {0:X} state; clearing dirty flag", (int)unavailable));

                _validState |= unavailable;
            }

            return _currentState & flagsToGet;
        }

19 View Source File : PendingChangesToolControl.cs
License : Apache License 2.0
Project Creator : AmpScm

void ShowPanel(PendingChangesPage page, bool select)
        {
            if (page == null)
                throw new ArgumentNullException("page");
            else if (page == _currentPage)
                return;

            bool foundPage = false;
            foreach (PendingChangesPage p in contentPanel.Controls)
            {
                if (p != page)
                {
                    p.Enabled = p.Visible = false;
                }
                else
                {
                    foundPage = true;
                    p.Enabled = p.Visible = true;

                    if (!p._alreadyThemed)
                    {
                        ThemePage(p);
                    }
                }
            }

            System.Diagnostics.Debug.replacedert(foundPage);

            _currentPage = page;

            if (page != _activatePage)
                _lastPage = page;

            fileChangesButton.Checked = (_lastPage == _commitsPage);
            issuesButton.Checked = (_lastPage == _issuesPage);
            recentChangesButton.Checked = (_lastPage == _changesPage);
            conflictsButton.Checked = (_lastPage == _conflictsPage);

            if (select)
                page.Select();

            if (Context != null)
            {
                IAnkhCommandService cmd = Context.GetService<IAnkhCommandService>();

                if (cmd != null)
                    cmd.UpdateCommandUI(false);

                UpdateCaption();
            }
        }

19 View Source File : AddProjectToSubversion.cs
License : Apache License 2.0
Project Creator : AmpScm

protected override void ValidateAdd(object sender, CancelEventArgs e)
        {
            base.ValidateAdd(sender, e);

            if (e.Cancel)
                return;

            Debug.replacedert(RepositoryAddUrl != null);

            IAnkhSolutionSettings ss = Context.GetService<IAnkhSolutionSettings>();

            // Error if the RepositoryAddUrl is below the url of the projectroot
            if (ss.ProjectRootUri.IsBaseOf(RepositoryAddUrl))
            {
                e.Cancel = true;

                errorProvider1.SetError(repositoryTree, "Please select a location that is not below the solution binding path, or move the project to a directory below the solution binding path on disk");
                return;
            }
        }

19 View Source File : ListViewShow.cs
License : Apache License 2.0
Project Creator : AmpScm

protected override void OnExecute(SmartListView list, CommandEventArgs e)
        {
            int n = (int)(e.Command - AnkhCommand.ListViewShow0);

            SmartColumn sc = list.AllColumns[n];
            int col = sc.Index;
            if (col > 0)
            {
                list.Columns.Remove(sc);

                if (!list.VirtualMode)
                {
                    Debug.replacedert(sc.Index < 0);

                    foreach (ListViewItem li in list.Items)
                    {
                        if (li.SubItems.Count > col)
                            li.SubItems.RemoveAt(col);
                    }
                }
            }
            else
            {
                list.Columns.Add(sc);

                if (!list.VirtualMode)
                {
                    col = sc.Index;
                    foreach (ListViewItem li in list.Items)
                    {
                        SmartListViewItem si = li as SmartListViewItem;

                        if (si != null)
                            si.SetValue(sc.AllColumnsIndex, si.GetValue(sc.AllColumnsIndex));
                    }
                }
            }            
        }

19 View Source File : AnkhViewFilter.cs
License : Apache License 2.0
Project Creator : AmpScm

int IOleCommandTarget.QueryStatus(ref Guid cmdGroup, uint cCmds, OLECMD[] prgCmds, IntPtr pCmdText)
        {
            /* TODO: Handle things that *must* be handled on every language service; bubble everything else
             *       up the chain */
            Debug.replacedert(cCmds == 1);

            int hr = QueryStatus(ref cmdGroup, ref prgCmds[0], pCmdText);

            if (hr != VSErr.E_FAIL)
                return hr;

            if (_fallThrough != null)
                return _fallThrough.QueryStatus(ref cmdGroup, cCmds, prgCmds, pCmdText);
            else
                return VSErr.E_FAIL; // delegate to next command target.
        }

19 View Source File : FileIconMapper.cs
License : Apache License 2.0
Project Creator : AmpScm

static string GetTypeNameForExtension(string extension)
        {
            Debug.replacedert(!string.IsNullOrEmpty(extension));

            string dummyPath = Path.Combine(Path.GetTempPath(), "Dummy." + extension);

            NativeMethods.SHFILEINFO fileinfo = new NativeMethods.SHFILEINFO();
            IntPtr rslt = NativeMethods.SHGetFileInfoW(dummyPath, (uint)(FileAttributes.Normal), ref fileinfo,
                (uint)Marshal.SizeOf(fileinfo), NativeMethods.SHGFI_TYPENAME | NativeMethods.SHGFI_USEFILEATTRIBUTES);

            if (rslt == IntPtr.Zero)
                return null;

            return fileinfo.szTypeName;
        }

19 View Source File : SplitDataSourceBase.cs
License : MIT License
Project Creator : amwx

public int IndexToIndexInOriginalVector(int index)
        {
            Debug.replacedert(index >= 0 && index < Size);
            return indicesInOriginalVector[index];
        }

19 View Source File : SplitDataSourceBase.cs
License : MIT License
Project Creator : amwx

public TVectorID GetVectorIDForItem(int index)
        {
            Debug.replacedert(index >= 0 && index < RawDataSize);
            return flags[index];
        }

19 View Source File : SplitDataSourceBase.cs
License : MIT License
Project Creator : amwx

public AttachedDataType AttachedData(int index)
        {
            Debug.replacedert(index >= 0 && index < RawDataSize);
            return _attachedData[index];
        }

19 View Source File : SplitDataSourceBase.cs
License : MIT License
Project Creator : amwx

public void AttachedData(int index, AttachedDataType attachedData)
        {
            Debug.replacedert(index >= 0 && index < RawDataSize);
            _attachedData[index] = attachedData;
        }

19 View Source File : SplitDataSourceBase.cs
License : MIT License
Project Creator : amwx

public void MoveItemsToVector(int start, int end, TVectorID newVectorID)
        {
            Debug.replacedert(start >= 0 && end <= RawDataSize);
            for (int i = start; i < end; i++)
            {
                MoveItemToVector(i, newVectorID);
            }
        }

19 View Source File : SplitDataSourceBase.cs
License : MIT License
Project Creator : amwx

public void MoveItemToVector(int index, TVectorID newVectorID)
        {
            Debug.replacedert(index >= 0 && index < RawDataSize);
            if (!flags[index].Equals(newVectorID))
            {
                // remove from the old vector
                var sv = GetVectorForItem(index);
                if (sv != null)
                    sv.RemoveAt(index);

                // change flag
                flags[index] = newVectorID;

                // insert item to vector which matches with the newVectorID
                var toVector = splitVectors[(int)(object)newVectorID];
                if (toVector != null)
                {
                    int pos = GetPreferIndex(index, newVectorID);
                    var value = GetAt(index);
                    toVector.InsertAt(pos, index, value);
                }
            }
        }

19 View Source File : SplitDataSourceBase.cs
License : MIT License
Project Creator : amwx

public void InsertAt(int preferIndex, int indexInOriginalVector, T value)
        {
            Debug.replacedert(preferIndex >= 0);
            Debug.replacedert(indexInOriginalVector >= 0);
            vector.Insert(preferIndex, value);
            indicesInOriginalVector.Insert(preferIndex, indexInOriginalVector);
        }

19 View Source File : SplitDataSourceBase.cs
License : MIT License
Project Creator : amwx

public void Replace(int indexInOriginalVector, T value)
        {
            Debug.replacedert(indexInOriginalVector >= 0);

            var index = IndexFromIndexInOriginalVector(indexInOriginalVector);
            var vect = vector;
            vect.RemoveAt(index);
            vect.Insert(index, value);
        }

19 View Source File : SplitDataSourceBase.cs
License : MIT License
Project Creator : amwx

public void RemoveAt(int indexInOriginalVector)
        {
            Debug.replacedert(indexInOriginalVector >= 0);
            var index = IndexFromIndexInOriginalVector(indexInOriginalVector);
            Debug.replacedert(index < indicesInOriginalVector.Count);
            vector.RemoveAt(index);
            indicesInOriginalVector.RemoveAt(index);
        }

19 View Source File : Program.cs
License : MIT License
Project Creator : anastasios-stamoulis

float[][] compute_embedding_matrix(FromKeras.Tokenizer tokenizer) {
      var embedding_matrix = new float[Constants.max_words][];
      var embeddings_index = preprocess_embeddings();
      foreach (var entry in tokenizer.word_index) {
        var word = entry.Key;
        var i = entry.Value;
        if (i>=Constants.max_words) { continue; }
        float[] embedding_vector;
        embeddings_index.TryGetValue(word, out embedding_vector);
        if (embedding_vector == null) {
          // Words not found in embedding index will be all-zeros.
          embedding_vector = new float[Constants.embedding_dim];
        }
        else {
          System.Diagnostics.Debug.replacedert(embedding_vector.Length == Constants.embedding_dim);
        }
        embedding_matrix[i] = embedding_vector;
      }
      for (int i=0; i<embedding_matrix.Length; i++) {
        if ( embedding_matrix[i]!=null ) { continue; }
        embedding_matrix[i] = new float[Constants.embedding_dim];
      }
      return embedding_matrix;
    }

19 View Source File : Program.cs
License : MIT License
Project Creator : anastasios-stamoulis

Dictionary<string, float[]> preprocess_embeddings() {
      var glove_dir = "C:\\Users\\anastasios\\Downloads\\glove.6B";
      var embeddings_index = new Dictionary<string, float[]>();
      var glove_path = System.IO.Path.Combine(glove_dir, "glove.6B.100d.txt");
      Console.WriteLine($"Processing {glove_path}");
      foreach(var line in System.IO.File.ReadLines(glove_path, Encoding.UTF8)) {
        var values = line.Split(' ');
        var word = values[0];
        var coefs = values.Skip(1).Select(v => Single.Parse(v)).ToArray();
        System.Diagnostics.Debug.replacedert(coefs.Length == Constants.embedding_dim);
        embeddings_index[word] = coefs;        
      }
      Console.WriteLine($"Found {embeddings_index.Keys.Count:n0} word vectors.");
      return embeddings_index;
    }

19 View Source File : Program.cs
License : MIT License
Project Creator : anastasios-stamoulis

void plotImages(IList<IList<float>> src_f) {
      var h = img_shape[0];
      var w = img_shape[1];
      System.Diagnostics.Debug.replacedert(w * h == src_f[0].Count);
      var matBuffer = new byte[src_f.Count * w * h];
      var gridLength = (int)Math.Sqrt(src_f.Count);
      for (int imageIndex = 0; imageIndex < src_f.Count; imageIndex++) {
        var img_f = src_f[imageIndex].ToArray();
        System.Diagnostics.Debug.replacedert(img_f.Length == w * h);

        var blockRow = imageIndex / gridLength;
        var blockColumn = imageIndex % gridLength;        
        for (int i = 0; i < img_f.Length; i++) {
          var v = (byte)(Math.Max(0, Math.Min(img_f[i], 1)) * 255);
          var digit_row = i / w;
          var digit_col = i % w;

          var row = blockRow * h + digit_row;
          var col = blockColumn * w + digit_col;

          var pos = row * gridLength * w + col;
          matBuffer[pos] = v;
        }
      }
    
      var mat = new OpenCvSharp.Mat(gridLength*h, gridLength*w, OpenCvSharp.MatType.CV_8UC1, matBuffer, gridLength*w);
      OpenCvSharp.Cv2.ImShow("Generated Images", mat);
      OpenCvSharp.Cv2.WaitKey(0);
    }

19 View Source File : Program.cs
License : MIT License
Project Creator : anastasios-stamoulis

void generateImages() {
      if ( model==null ) {
        System.Diagnostics.Debug.replacedert(System.IO.File.Exists(model_filename));
        model = CNTK.Function.Load(model_filename, computeDevice);
      }

      var node_z = model.FindByName("input_z");
      var decoder_start = Util.find_function_with_input(model, node_z);
      var z_sample_var = CNTK.Variable.InputVariable(node_z.Output.Shape, CNTK.DataType.Float, "z_sample");
      var replacements = new Dictionary<CNTK.Variable, CNTK.Variable>() { {node_z, z_sample_var } };
      var decoder = model.Clone(CNTK.ParameterCloningMethod.Freeze, replacements);

      var n = 15; // figure with 15x15 digits
      var xy_buffer = new float[n * n * 2];
      var sample_start = -2f;
      var sample_interval_width = 4f;
      for (int i=0, pos=0; i<n; i++) {
        for (int j=0; j<n; j++) {
          xy_buffer[pos++] = sample_start + (sample_interval_width / (n-1)) * i;
          xy_buffer[pos++] = sample_start + (sample_interval_width/ (n - 1)) * j;
        }
      }

      var ndArrayView = new CNTK.NDArrayView(new int[] {2, 1, xy_buffer.Length/2}, xy_buffer, computeDevice, true);
      var value = new CNTK.Value(ndArrayView);
      var inputs_dir = new Dictionary<CNTK.Variable, CNTK.Value>() { { z_sample_var, value} };
      var outputs_dir = new Dictionary<CNTK.Variable, CNTK.Value>() { { decoder.Output, null } };
      decoder.Evaluate(inputs_dir, outputs_dir, computeDevice);
      var values = outputs_dir[decoder.Output].GetDenseData<float>(decoder.Output);
      plotImages(values);
    }

19 View Source File : Program.cs
License : MIT License
Project Creator : anastasios-stamoulis

void load_data() {
      var num_images = 5000;
      var data_filename = "x_channels_first_8_5.bin";
      var num_bytes_per_image = sizeof(float) * channels * width * height;
      System.Diagnostics.Debug.replacedert(System.IO.File.Exists(data_filename));
      System.Diagnostics.Debug.replacedert(new System.IO.FileInfo(data_filename).Length == num_images * num_bytes_per_image);
      x_train = Util.load_binary_file(data_filename, num_images, channels * width * height);
    }

19 View Source File : Program.cs
License : MIT License
Project Creator : anastasios-stamoulis

float[][] compute_labels(CNTK.Function model, float[] target_image, float[] style_reference_image) {
      var input_shape = model.Arguments[0].Shape.Dimensions.ToArray();
      System.Diagnostics.Debug.replacedert(input_shape[0] * input_shape[1] * input_shape[2] == target_image.Length);
      System.Diagnostics.Debug.replacedert(target_image.Length == style_reference_image.Length);

#if false
      var cpuDevice = CNTK.DeviceDescriptor.CPUDevice;
      var target_image_nd = new CNTK.NDArrayView(input_shape, target_image, cpuDevice, readOnly: true);
      var style_reference_image_nd = new CNTK.NDArrayView(input_shape, style_reference_image, cpuDevice, readOnly: true);
      var batch_nd = new CNTK.NDArrayView[] { target_image_nd, style_reference_image_nd };
      var batch = CNTK.Value.Create(input_shape, batch_nd, computeDevice, readOnly: true);
#else
      var batch_buffer = new float[2 * target_image.Length];
      Array.Copy(target_image, 0, batch_buffer, 0, target_image.Length);
      Array.Copy(style_reference_image, 0, batch_buffer, target_image.Length, target_image.Length);
      var batch_nd = new CNTK.NDArrayView(new int[] { model.Arguments[0].Shape[0], model.Arguments[0].Shape[1], model.Arguments[0].Shape[2], 1, 2 }, batch_buffer, computeDevice);
      var batch = new CNTK.Value(batch_nd);
#endif
      var inputs = new Dictionary<CNTK.Variable, CNTK.Value>() { { model.Arguments[0], batch } };
      var outputs = new Dictionary<CNTK.Variable, CNTK.Value>();
      foreach (var output in model.Outputs) {
        outputs.Add(output, null);
      }
      model.Evaluate(inputs, outputs, computeDevice);

      float[][] labels = new float[model.Outputs.Count][];
      labels[0] = outputs[model.Outputs[0]].GetDenseData<float>(model.Outputs[0])[0].ToArray();
      for (int i = 1; i < labels.Length; i++) {
        labels[i] = outputs[model.Outputs[i]].GetDenseData<float>(model.Outputs[i])[1].ToArray();
      }

      return labels;
    }

19 View Source File : Capsules.cs
License : MIT License
Project Creator : anastasios-stamoulis

C.Function get_mask_and_infer_from_last_dimension(C.Function inputs, C.Function mask) {
      if (mask == null) {
        var inputs_shape = inputs.Output.Shape.Dimensions.ToArray();
        var ndims = inputs_shape.Length - 1;
        var x = CC.Sqrt(CC.ReduceSum(CC.Square(inputs), new C.Axis(ndims - 1)));
        x = CC.Squeeze(x);
        System.Diagnostics.Debug.replacedert(x.Output.Shape.Dimensions.Count == 1);
        x = CC.Argmax(x, new C.Axis(0));
        mask = CC.OneHotOp(x, numClreplaced: (uint)inputs_shape[0], outputSparse: false, axis: new C.Axis(0));
      }
      mask = CC.Reshape(mask, mask.Output.Shape.AppendShape(new int[] { 1 }));
      var masked = CC.ElementTimes(inputs, mask);
      masked = CC.Flatten(masked);
      masked = CC.Squeeze(masked);
      return masked;
    }

19 View Source File : Util.cs
License : MIT License
Project Creator : anastasios-stamoulis

public static float[] get_contiguous_buffer(float[][] data, int[] indices, int indices_begin, int indices_end) {
      var num_indices = indices_end - indices_begin;
      var buffer = new float[num_indices * data[0].Length];
      int pos = 0;
      for (int index = indices_begin; index != indices_end; index++) {
        var src = data[indices[index]];
        Array.Copy(src, 0, buffer, pos, src.Length);
        System.Diagnostics.Debug.replacedert(src.Length == data[0].Length);
        pos += src.Length;
      }
      return buffer;
    }

19 View Source File : Util.cs
License : MIT License
Project Creator : anastasios-stamoulis

public static T[] convert_jagged_array_to_single_dimensional_array<T>(T[][] src) where T : struct {
      var numRows = src.Length;
      var numColumns = src[0].Length;
      var numBytesInRow = numColumns * SizeOf<T>();
      var dst = new T[numRows * numColumns];
      var dstOffset = 0;
      for (int row = 0; row < numRows; row++) {
        System.Diagnostics.Debug.replacedert(src[row].Length == numColumns);
        System.Buffer.BlockCopy(src[row], 0, dst, dstOffset, numBytesInRow);
        dstOffset += numBytesInRow;
      }
      return dst;
    }

19 View Source File : Util.cs
License : MIT License
Project Creator : anastasios-stamoulis

public static void shuffle<T1, T2>(T1[] array1, T2[] array2) {
      System.Diagnostics.Debug.replacedert(array1.Length == array2.Length);
      lock (_rng) {
        var n = array1.Length;
        while (n > 1) {
          var k = _rng.Next(n--);
          swap(array1, n, k);
          swap(array2, n, k);
        }
      }
    }

19 View Source File : Util.cs
License : MIT License
Project Creator : anastasios-stamoulis

static public C.Function Embedding(C.Variable x, int shape, C.DeviceDescriptor computeDevice, float[][] weights = null, string name = "") {
      C.Function result;
      // based on the Embedding defined in https://github.com/Microsoft/CNTK/blob/master/bindings/python/cntk/layers/layers.py      
      if (weights == null) {
        var weight_shape = new int[] { shape, C.NDShape.InferredDimension };
        var E = new C.Parameter(
          weight_shape,
          C.DataType.Float,
          CC.GlorotUniformInitializer(),
          computeDevice, name: "embedding_" + name);
        result = CC.Times(E, x);
      }
      else {
        var weight_shape = new int[] { shape, x.Shape.Dimensions[0] };
        System.Diagnostics.Debug.replacedert(shape == weights[0].Length);
        System.Diagnostics.Debug.replacedert(weight_shape[1] == weights.Length);
        var w = Engine.convert_jagged_array_to_single_dimensional_array(weights);
        var ndArrayView = new C.NDArrayView(weight_shape, w, computeDevice, readOnly: true);
        var E = new C.Constant(ndArrayView, name: "fixed_embedding_" + name);
        result = CC.Times(E, x);
      }
      return result;
    }

19 View Source File : Util.cs
License : MIT License
Project Creator : anastasios-stamoulis

static public float[] translate(float[] src, int width, int height, int delta_x, int delta_y) {
      System.Diagnostics.Debug.replacedert(src.Length == width * height);
      var dst = new float[src.Length];
      for (int row=0; row<height; row++) {
        var src_row = row - delta_y;
        if ( (src_row<0) || (src_row>=height) ) { continue; }
        for (int col=0; col<width; col++) {
          var src_col = col - delta_x;
          if ( (src_col<0) || (src_col>=width) ) { continue; }
          var p = row * width + col;
          var src_p = src_row * width + src_col;
          dst[p] = src[src_p];
        }
      }
      return dst;
    }

19 View Source File : SimpleMeshSerializer.cs
License : MIT License
Project Creator : anderm

private static void WriteMesh(BinaryWriter writer, Mesh mesh, Transform transform = null)
        {
            SysDiag.Debug.replacedert(writer != null);

            // Write the mesh data.
            WriteMeshHeader(writer, mesh.vertexCount, mesh.triangles.Length);
            WriteVertices(writer, mesh.vertices, transform);
            WriteTriangleIndicies(writer, mesh.triangles);
        }

19 View Source File : SimpleMeshSerializer.cs
License : MIT License
Project Creator : anderm

private static Mesh ReadMesh(BinaryReader reader)
        {
            SysDiag.Debug.replacedert(reader != null);

            int vertexCount = 0;
            int triangleIndexCount = 0;

            // Read the mesh data.
            ReadMeshHeader(reader, out vertexCount, out triangleIndexCount);
            Vector3[] vertices = ReadVertices(reader, vertexCount);
            int[] triangleIndices = ReadTriangleIndicies(reader, triangleIndexCount);

            // Create the mesh.
            Mesh mesh = new Mesh();
            mesh.vertices = vertices;
            mesh.triangles = triangleIndices;
            // Reconstruct the normals from the vertices and triangles.
            mesh.RecalculateNormals();

            return mesh;
        }

19 View Source File : SimpleMeshSerializer.cs
License : MIT License
Project Creator : anderm

private static void WriteMeshHeader(BinaryWriter writer, int vertexCount, int triangleIndexCount)
        {
            SysDiag.Debug.replacedert(writer != null);

            writer.Write(vertexCount);
            writer.Write(triangleIndexCount);

        }

19 View Source File : SimpleMeshSerializer.cs
License : MIT License
Project Creator : anderm

private static void ReadMeshHeader(BinaryReader reader, out int vertexCount, out int triangleIndexCount)
        {
            SysDiag.Debug.replacedert(reader != null);

            vertexCount = reader.ReadInt32();
            triangleIndexCount = reader.ReadInt32();
        }

19 View Source File : SimpleMeshSerializer.cs
License : MIT License
Project Creator : anderm

private static void WriteVertices(BinaryWriter writer, Vector3[] vertices, Transform transform = null)
        {
            SysDiag.Debug.replacedert(writer != null);

            if (transform != null)
            {
                for (int v = 0, vLength = vertices.Length; v < vLength; ++v)
                {
                    Vector3 vertex = transform.TransformPoint(vertices[v]);
                    writer.Write(vertex.x);
                    writer.Write(vertex.y);
                    writer.Write(vertex.z);
                }
            }
            else
            {
                foreach (Vector3 vertex in vertices)
                {
                    writer.Write(vertex.x);
                    writer.Write(vertex.y);
                    writer.Write(vertex.z);
                }
            }
        }

19 View Source File : SimpleMeshSerializer.cs
License : MIT License
Project Creator : anderm

private static Vector3[] ReadVertices(BinaryReader reader, int vertexCount)
        {
            SysDiag.Debug.replacedert(reader != null);

            Vector3[] vertices = new Vector3[vertexCount];

            for (int i = 0; i < vertices.Length; i++)
            {
                vertices[i] = new Vector3(reader.ReadSingle(),
                                        reader.ReadSingle(),
                                        reader.ReadSingle());
            }

            return vertices;
        }

See More Examples