text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Numerics;
using System.Reactive;
using System.Reactive.Linq;
using System.Threading.Tasks;
using Avalonia;
using Avalonia.Media;
using Avalonia.Media.Imaging;
using DynamicData;
using DynamicData.Binding;
using OpenUtau.Core;
using OpenUtau.Core.Ustx;
using OpenUtau.Core.Util;
using ReactiveUI;
using ReactiveUI.Fody.Helpers;
using Serilog;

namespace OpenUtau.App.ViewModels {
    public class NotesRefreshEvent { }
    public class NotesSelectionEvent {
        public readonly UNote[] selectedNotes;
        public readonly UNote[] tempSelectedNotes;
        public NotesSelectionEvent(NoteSelectionViewModel selection) {
            selectedNotes = selection.ToArray();
            tempSelectedNotes = selection.TempSelectedNotes.ToArray();
        }
    }
    public class WaveformRefreshEvent { }

    public class NotesViewModel : ViewModelBase, ICmdSubscriber {
        [Reactive] public Rect Bounds { get; set; }
        public int TickCount => Part?.Duration ?? 480 * 4;
        public int TrackCount => ViewConstants.MaxTone;
        [Reactive] public double TickWidth { get; set; }
        public double TrackHeightMin => ViewConstants.NoteHeightMin;
        public double TrackHeightMax => ViewConstants.NoteHeightMax;
        [Reactive] public double TrackHeight { get; set; }
        [Reactive] public int TickOrigin { get; set; }
        [Reactive] public double TickOffset { get; set; }
        [Reactive] public double TrackOffset { get; set; }
        [Reactive] public int SnapDiv { get; set; }
        public ObservableCollectionExtended<int> SnapTicks { get; } = new ObservableCollectionExtended<int>();
        [Reactive] public double PlayPosX { get; set; }
        [Reactive] public double PlayPosHighlightX { get; set; }
        [Reactive] public double PlayPosHighlightWidth { get; set; }
        [Reactive] public bool PlayPosWaitingRendering { get; set; }
        [Reactive] public bool CursorTool { get; set; }
        [Reactive] public bool PenTool { get; set; }
        [Reactive] public bool PenPlusTool { get; set; }
        [Reactive] public bool EraserTool { get; set; }
        [Reactive] public bool DrawPitchTool { get; set; }
        [Reactive] public bool KnifeTool { get; set; }
        public ReactiveCommand<string, Unit> SelectToolCommand { get; }
        [Reactive] public bool ShowTips { get; set; }
        [Reactive] public bool PlayTone { get; set; }
        [Reactive] public bool ShowVibrato { get; set; }
        [Reactive] public bool ShowPitch { get; set; }
        [Reactive] public bool ShowFinalPitch { get; set; }
        [Reactive] public bool ShowWaveform { get; set; }
        [Reactive] public bool ShowPhoneme { get; set; }
        [Reactive] public bool IsSnapOn { get; set; }
        [Reactive] public string SnapDivText { get; set; }
        [Reactive] public Rect ExpBounds { get; set; }
        [Reactive] public string PrimaryKey { get; set; }
        [Reactive] public bool PrimaryKeyNotSupported { get; set; }
        [Reactive] public string SecondaryKey { get; set; }
        [Reactive] public double ExpTrackHeight { get; set; }
        [Reactive] public double ExpShadowOpacity { get; set; }
        [Reactive] public UVoicePart? Part { get; set; }
        [Reactive] public Bitmap? Portrait { get; set; }
        [Reactive] public IBrush? PortraitMask { get; set; }
        public double ViewportTicks => viewportTicks.Value;
        public double ViewportTracks => viewportTracks.Value;
        public double SmallChangeX => smallChangeX.Value;
        public double SmallChangeY => smallChangeY.Value;
        public double HScrollBarMax => Math.Max(0, TickCount - ViewportTicks);
        public double VScrollBarMax => Math.Max(0, TrackCount - ViewportTracks);
        public UProject Project => DocManager.Inst.Project;
        [Reactive] public List<MenuItemViewModel> SnapDivs { get; set; }

        public ReactiveCommand<int, Unit> SetSnapUnitCommand { get; set; }

        // See the comments on TracksViewModel.playPosXToTickOffset
        private double playPosXToTickOffset => ViewportTicks / Bounds.Width;

        private readonly ObservableAsPropertyHelper<double> viewportTicks;
        private readonly ObservableAsPropertyHelper<double> viewportTracks;
        private readonly ObservableAsPropertyHelper<double> smallChangeX;
        private readonly ObservableAsPropertyHelper<double> smallChangeY;

        public readonly NoteSelectionViewModel Selection = new NoteSelectionViewModel();

        internal NotesViewModelHitTest HitTest;
        private int _lastNoteLength = 480;
        private string? portraitSource;
        private readonly object portraitLock = new object();
        private int userSnapDiv = -2;

        public NotesViewModel() {
            SnapDivs = new List<MenuItemViewModel>();
            SetSnapUnitCommand = ReactiveCommand.Create<int>(div => {
                userSnapDiv = div;
                UpdateSnapDiv();
            });

            viewportTicks = this.WhenAnyValue(x => x.Bounds, x => x.TickWidth)
                .Select(v => v.Item1.Width / v.Item2)
                .ToProperty(this, x => x.ViewportTicks);
            viewportTracks = this.WhenAnyValue(x => x.Bounds, x => x.TrackHeight)
                .Select(v => v.Item1.Height / v.Item2)
                .ToProperty(this, x => x.ViewportTracks);
            smallChangeX = this.WhenAnyValue(x => x.ViewportTicks)
                .Select(w => w / 8)
                .ToProperty(this, x => x.SmallChangeX);
            smallChangeY = this.WhenAnyValue(x => x.ViewportTracks)
                .Select(h => h / 8)
                .ToProperty(this, x => x.SmallChangeY);
            this.WhenAnyValue(x => x.Bounds)
                .Subscribe(_ => {
                    OnXZoomed(new Point(), 0);
                    OnYZoomed(new Point(), 0);
                });

            this.WhenAnyValue(x => x.TickWidth)
                .Subscribe(tickWidth => {
                    UpdateSnapDiv();
                    SetPlayPos(DocManager.Inst.playPosTick, false);
                });
            this.WhenAnyValue(x => x.TickOffset)
                .Subscribe(tickOffset => {
                    SetPlayPos(DocManager.Inst.playPosTick, false);
                });
            this.WhenAnyValue(x => x.ExpBounds, x => x.PrimaryKey)
                .Subscribe(t => {
                    if (t.Item2 != null &&
                        Project.expressions.TryGetValue(t.Item2, out var descriptor) &&
                        descriptor.type == UExpressionType.Options &&
                        descriptor.options.Length > 0) {
                        ExpTrackHeight = t.Item1.Height / descriptor.options.Length;
                        ExpShadowOpacity = 0;
                    } else {
                        ExpTrackHeight = 0;
                        ExpShadowOpacity = 0.3;
                    }
                });
            this.WhenAnyValue(x => x.Project)
                .Subscribe(project => {
                    if (project == null) {
                        return;
                    }
                    SnapDivs.Clear();
                    SnapDivs.Add(new MenuItemViewModel {
                        Header = ThemeManager.GetString("pianoroll.toggle.snap.auto"),
                        Command = SetSnapUnitCommand,
                        CommandParameter = -2,
                    });
                    SnapDivs.Add(new MenuItemViewModel {
                        Header = ThemeManager.GetString("pianoroll.toggle.snap.autotriplet"),
                        Command = SetSnapUnitCommand,
                        CommandParameter = -3,
                    });
                    SnapDivs.AddRange(MusicMath.GetSnapDivs(project.resolution)
                        .Select(div => new MenuItemViewModel {
                            Header = $"1/{div}",
                            Command = SetSnapUnitCommand,
                            CommandParameter = div,
                        }));
                });

            CursorTool = false;
            PenTool = true;
            PenPlusTool = false;
            EraserTool = false;
            DrawPitchTool = false;
            KnifeTool = false;
            SelectToolCommand = ReactiveCommand.Create<string>(index => {
                CursorTool = index == "1";
                PenTool = index == "2";
                PenPlusTool = index == "2+";
                EraserTool = index == "3";
                DrawPitchTool = index == "4";
                KnifeTool = index == "5";
            });

            ShowTips = Preferences.Default.ShowTips;
            PlayTone = true;
            ShowVibrato = true;
            ShowPitch = true;
            ShowFinalPitch = true;
            ShowWaveform = true;
            ShowPhoneme = true;
            IsSnapOn = true;
            SnapDivText = string.Empty;

            TickWidth = ViewConstants.PianoRollTickWidthDefault;
            TrackHeight = ViewConstants.NoteHeightDefault;
            TrackOffset = 4 * 12 + 6;
            if (Preferences.Default.ShowTips) {
                Preferences.Default.ShowTips = false;
                Preferences.Save();
            }
            PrimaryKey = Core.Format.Ustx.VEL;
            SecondaryKey = Core.Format.Ustx.VOL;

            HitTest = new NotesViewModelHitTest(this);
            DocManager.Inst.AddSubscriber(this);
        }

        private void UpdateSnapDiv() {
            if (userSnapDiv > 0) {
                SnapDiv = userSnapDiv;
                SnapDivText = $"1/{userSnapDiv}";
                return;
            }
            MusicMath.GetSnapUnit(
                Project.resolution,
                ViewConstants.PianoRollMinTicklineWidth / TickWidth,
                userSnapDiv % 3 == 0,
                out int ticks,
                out int div);
            SnapDiv = div;
            SnapDivText = $"(1/{div})";
        }

        public void OnXZoomed(Point position, double delta) {
            bool recenter = true;
            if (TickOffset == 0 && position.X < 0.1) {
                recenter = false;
            }
            double center = TickOffset + position.X * ViewportTicks;
            double tickWidth = TickWidth * (1.0 + delta * 2);
            tickWidth = Math.Clamp(tickWidth, ViewConstants.PianoRollTickWidthMin, ViewConstants.PianoRollTickWidthMax);
            tickWidth = Math.Max(tickWidth, Bounds.Width / TickCount);
            TickWidth = tickWidth;
            double tickOffset = recenter
                    ? center - position.X * ViewportTicks
                    : TickOffset;
            TickOffset = Math.Clamp(tickOffset, 0, HScrollBarMax);
            Notify();
        }

        public void OnYZoomed(Point position, double delta) {
            double center = TrackOffset + position.Y * ViewportTracks;
            double trackHeight = TrackHeight * (1.0 + delta * 2);
            trackHeight = Math.Clamp(trackHeight, ViewConstants.NoteHeightMin, ViewConstants.NoteHeightMax);
            trackHeight = Math.Max(trackHeight, Bounds.Height / TrackCount);
            TrackHeight = trackHeight;
            double trackOffset = center - position.Y * ViewportTracks;
            TrackOffset = Math.Clamp(trackOffset, 0, VScrollBarMax);
            Notify();
        }

        private void Notify() {
            this.RaisePropertyChanged(nameof(TickCount));
            this.RaisePropertyChanged(nameof(HScrollBarMax));
            this.RaisePropertyChanged(nameof(ViewportTicks));
            this.RaisePropertyChanged(nameof(TrackCount));
            this.RaisePropertyChanged(nameof(VScrollBarMax));
            this.RaisePropertyChanged(nameof(ViewportTracks));
        }

        public int PointToTick(Point point) {
            return (int)(point.X / TickWidth + TickOffset);
        }

        public void TickToLineTick(int tick, out int left, out int right) {
            if (SnapTicks.Count == 0) {
                left = 0;
                right = Project.resolution;
                return;
            }
            int index = SnapTicks.BinarySearch(tick + TickOrigin);
            if (index < 0) {
                index = ~index - 1;
            }
            if (0 >= SnapTicks.Count - 2) {
                left = right = tick;
                return;
            }
            index = Math.Clamp(index, 0, SnapTicks.Count - 2);
            left = SnapTicks[index] - TickOrigin;
            right = SnapTicks[index + 1] - TickOrigin;
        }

        public void PointToLineTick(Point point, out int left, out int right) {
            int tick = PointToTick(point);
            TickToLineTick(tick, out left, out right);
        }

        public int PointToTone(Point point) {
            return ViewConstants.MaxTone - 1 - (int)(point.Y / TrackHeight + TrackOffset);
        }
        public double PointToToneDouble(Point point) {
            return ViewConstants.MaxTone - 1 - (point.Y / TrackHeight + TrackOffset) + 0.5;
        }
        public Point TickToneToPoint(double tick, double tone) {
            return new Point(
                (tick - TickOffset) * TickWidth,
                (ViewConstants.MaxTone - 1 - tone - TrackOffset) * TrackHeight);
        }
        public Point TickToneToPoint(Vector2 tickTone) {
            return TickToneToPoint(tickTone.X, tickTone.Y);
        }
        public Size TickToneToSize(double ticks, double tone) {
            return new Size(ticks * TickWidth, tone * TrackHeight);
        }

        public UNote? MaybeAddNote(Point point, bool useLastLength) {
            if (Part == null) {
                return null;
            }
            var project = DocManager.Inst.Project;
            int tone = PointToTone(point);
            if (tone >= ViewConstants.MaxTone || tone < 0) {
                return null;
            }
            int snapUnit = project.resolution * 4 / SnapDiv;
            int tick = PointToTick(point);
            int snappedTick = (int)Math.Floor((double)tick / snapUnit) * snapUnit;
            UNote note = project.CreateNote(tone, snappedTick,
                useLastLength ? _lastNoteLength : IsSnapOn ? snappedTick : 15);
            DocManager.Inst.ExecuteCmd(new AddNoteCommand(Part, note));
            return note;
        }

        private void LoadPart(UPart part, UProject project) {
            if (!(part is UVoicePart)) {
                return;
            }
            UnloadPart();
            Part = part as UVoicePart;
            OnPartModified();
            LoadPortrait(part, project);
        }

        private void LoadPortrait(UPart? part, UProject? project) {
            if (part == null || project == null) {
                lock (portraitLock) {
                    Portrait = null;
                    portraitSource = null;
                }
                return;
            }
            var singer = project.tracks[part.trackNo].Singer;
            if (singer == null || string.IsNullOrEmpty(singer.Portrait) || !Preferences.Default.ShowPortrait) {
                lock (portraitLock) {
                    Portrait = null;
                    portraitSource = null;
                }
                return;
            }
            if (portraitSource != singer.Portrait) {
                lock (portraitLock) {
                    Portrait = null;
                    portraitSource = null;
                }
                PortraitMask = new SolidColorBrush(Colors.White, singer.PortraitOpacity);
                Task.Run(() => {
                    lock (portraitLock) {
                        try {
                            Portrait?.Dispose();
                            var data = singer.LoadPortrait();
                            if (data == null) {
                                Portrait = null;
                                portraitSource = null;
                            } else {
                                using (var stream = new MemoryStream(data)) {
                                    var portrait = new Bitmap(stream);
                                    if (portrait.Size.Height > 800) {
                                        int width = (int)Math.Round(800 * portrait.Size.Width / portrait.Size.Height);
                                        portrait = portrait.CreateScaledBitmap(new PixelSize(width, 800));
                                    }
                                    Portrait = portrait;
                                    portraitSource = singer.Portrait;
                                }
                            }
                        } catch (Exception e) {
                            Portrait?.Dispose();
                            Portrait = null;
                            portraitSource = null;
                            Log.Error(e, $"Failed to load Portrait {singer.Portrait}");
                        }
                    }
                });
            }
        }

        private void UnloadPart() {
            DeselectNotes();
            Part = null;
            LoadPortrait(null, null);
        }

        private void OnPartModified() {
            if (Part == null) {
                return;
            }
            TickOrigin = Part.position;
            Notify();
        }

        private void DeselectNote(UNote note) {
            if (Selection.Remove(note)) {
                MessageBus.Current.SendMessage(new NotesSelectionEvent(Selection));
            }
        }

        public void DeselectNotes() {
            Selection.SelectNone();
            MessageBus.Current.SendMessage(new NotesSelectionEvent(Selection));
        }

        public void ToggleSelectNote(UNote note) {
            if (Part == null) {
                return;
            }
            if (Selection.Contains(note)) {
                DeselectNote(note);
            } else {
                SelectNote(note);
            }
        }

        public void SelectNote(UNote note) {
            SelectNote(note, true);
        }
        public void SelectNote(UNote note, bool deselectExisting) {
            if (Part == null) {
                return;
            }
            if (deselectExisting ? Selection.Select(note) : Selection.Add(note)) {
                MessageBus.Current.SendMessage(new NotesSelectionEvent(Selection));
            }
        }
        public void MoveSelection(int delta) {
            if (Selection.Move(delta)) {
                MessageBus.Current.SendMessage(new NotesSelectionEvent(Selection));
                ScrollIntoView(Selection.Head!);
            };
        }
        public void ExtendSelection(int delta) {
            if (Selection.Resize(delta)) {
                MessageBus.Current.SendMessage(new NotesSelectionEvent(Selection));
                ScrollIntoView(Selection.Head!);
            };
        }
        public void ExtendSelection(UNote note) {
            if (Selection.SelectTo(note)) {
                MessageBus.Current.SendMessage(new NotesSelectionEvent(Selection));
            };
        }

        public void MoveCursor(int delta) {
            if (!Selection.IsEmpty) {
                MoveSelection(delta);
                return;
            }
            var target = Part!.notes.FirstOrDefault();
            if (target == null) {
                return;
            }
            var centerTick = TickOffset + ViewportTicks * 0.5;
            // get closest note to center, without going over
            while (target.Next != null && (target!.position < TickOffset || target!.Next.position < centerTick)) {
                target = target.Next;
            }
            SelectNote(target);
            ScrollIntoView(target);
        }

        public void SelectAllNotes() {
            if (Part == null) {
                return;
            }
            Selection.Select(Part);
            MessageBus.Current.SendMessage(new NotesSelectionEvent(Selection));
        }

        public void SelectNotesUntil(UNote note) {
            if (Part == null) {
                return;
            }
            if (Part.notes.Intersect(Selection).ToList().Count == 0) {
                SelectNote(note);
                return;
            }
            var thisIndex = Part.notes.IndexOf(note);
            if (thisIndex < 0) {
                return;
            }
            var firstSelectedNote = Part.notes.FirstOrDefault(x => Selection.Contains(x));
            if (firstSelectedNote == null) {
                return;
            }
            var rangeStart = Part.notes.IndexOf(firstSelectedNote);
            var lastSelectedNote = Part.notes.LastOrDefault(x => Selection.Contains(x));
            if (lastSelectedNote == null) {
                return;
            }
            var rangeEndInclusive = Part.notes.IndexOf(lastSelectedNote);
            int rangeToAddStart;
            int rangeToAddEndInclusive;
            if (thisIndex < rangeStart) {
                rangeToAddStart = thisIndex;
                rangeToAddEndInclusive = rangeEndInclusive;
            } else if (thisIndex > rangeEndInclusive) {
                rangeToAddStart = rangeStart;
                rangeToAddEndInclusive = thisIndex;
            } else {
                rangeToAddStart = rangeStart;
                rangeToAddEndInclusive = rangeEndInclusive;
            }
            var notesToAdd = Part.notes.ToList().GetRange(rangeToAddStart, rangeToAddEndInclusive - rangeToAddStart + 1);
            var changed = Selection.Add(notesToAdd);
            if (changed) {
                MessageBus.Current.SendMessage(new NotesSelectionEvent(Selection));
            }
        }

        public void TempSelectNotes(int x0, int x1, int y0, int y1) {
            if (Part == null) {
                return;
            }
            var tempNotes = Part.notes
                .Where(note => note.End > x0 && note.position < x1 && note.tone > y0 && note.tone <= y1)
                .ToList();

            Selection.SetTemporarySelection(tempNotes);
            MessageBus.Current.SendMessage(new NotesSelectionEvent(Selection));
        }

        public void CommitTempSelectNotes() {
            Selection.CommitTemporarySelection();
            MessageBus.Current.SendMessage(new NotesSelectionEvent(Selection));
        }

        public void CleanupSelectedNotes() {
            if (Part == null) {
                return;
            }
            var toCleanup = Selection.Except(Part.notes).ToList();
            Selection.Remove(toCleanup);
        }

        public void InsertNote() {
            if(Part == null) {
                return;
            }

            var project = DocManager.Inst.Project;
            int snapUnit = project.resolution * 4 / SnapDiv;

            var fromNote = Selection.LastOrDefault();
            int DEFAULT_TONE = 12 * 5; // C4
            int tone = fromNote?.tone ?? DEFAULT_TONE;
            int tick = fromNote?.RightBound ?? (int)TickOffset;
            int dur = fromNote?.duration ?? snapUnit;
            DocManager.Inst.StartUndoGroup();
            UNote note = DocManager.Inst.Project.CreateNote(tone, tick, dur);
            DocManager.Inst.ExecuteCmd(new AddNoteCommand(Part, note));
            SelectNote(note);
            DocManager.Inst.EndUndoGroup();
        }

        public void TransposeSelection(int deltaNoteNum) {
            if (Selection.IsEmpty) {
                return;
            }
            var selectedNotes = Selection.ToList();
            if (selectedNotes.Any(note => note.tone + deltaNoteNum <= 0 || note.tone + deltaNoteNum >= ViewConstants.MaxTone)) {
                return;
            }
            DocManager.Inst.StartUndoGroup();
            DocManager.Inst.ExecuteCmd(new MoveNoteCommand(Part, selectedNotes, 0, deltaNoteNum));
            DocManager.Inst.EndUndoGroup();
        }
        public void MoveSelectedNotes(int deltaTicks) {
            if (Selection.IsEmpty || Part == null) {
                return;
            }
            var selectedNotes = Selection.ToList();
            // TODO REVIEW should the end be clamped to end of part? or allow to go over?
            //var delta = Math.Clamp(deltaTicks, -1 * selectedNotes.First().position, Part.End - selectedNotes.Last().position);
            var delta = Math.Max(deltaTicks, -1 * selectedNotes.First().position);

            DocManager.Inst.StartUndoGroup();
            DocManager.Inst.ExecuteCmd(new MoveNoteCommand(Part, selectedNotes, delta, 0));
            DocManager.Inst.EndUndoGroup();
        }

        public void ResizeSelectedNotes(int deltaTicks) {
            if (Selection.IsEmpty || Part == null) {
                return;
            }

            var selectedNotes = Selection.ToList();

            // ignore if change would make a note smaller than minimal size
            if (deltaTicks < 0) {
                int smallestDuration = selectedNotes.Select(n => n.duration).Min();

                var project = DocManager.Inst.Project;
                int snapUnit = project.resolution * 4 / SnapDiv;
                int minNoteTicks = IsSnapOn ? snapUnit : 15;

                if (smallestDuration + deltaTicks < minNoteTicks) {
                    return;
                }
            }
            DocManager.Inst.StartUndoGroup();
            DocManager.Inst.ExecuteCmd(new ResizeNoteCommand(Part, selectedNotes, deltaTicks));
            DocManager.Inst.EndUndoGroup();
        }

        internal void DeleteSelectedNotes() {
            if (Selection.IsEmpty) {
                return;
            }
            DocManager.Inst.StartUndoGroup();
            DocManager.Inst.ExecuteCmd(new RemoveNoteCommand(Part, Selection.ToList()));
            DocManager.Inst.EndUndoGroup();
        }

        public void CopyNotes() {
            if (!Selection.IsEmpty) {
                var selectedNotes = Selection.ToList();
                DocManager.Inst.NotesClipboard = selectedNotes.Select(note => note.Clone()).ToList();
            }
        }

        public void CutNotes() {
            if (!Selection.IsEmpty) {
                var selectedNotes = Selection.ToList();
                DocManager.Inst.NotesClipboard = selectedNotes.Select(note => note.Clone()).ToList();
                DocManager.Inst.StartUndoGroup();
                DocManager.Inst.ExecuteCmd(new RemoveNoteCommand(Part, selectedNotes));
                DocManager.Inst.EndUndoGroup();
            }
        }

        public void PasteNotes() {
            if (Part != null && DocManager.Inst.NotesClipboard != null && DocManager.Inst.NotesClipboard.Count > 0) {
                int snapUnit = DocManager.Inst.Project.resolution * 4 / SnapDiv;
                int left = (DocManager.Inst.playPosTick / snapUnit) * snapUnit;
                int minPosition = DocManager.Inst.NotesClipboard.Select(note => note.position).Min();
                //If PlayPos is before the beginning of the part, don't paste.
                if (left >= Part.position) {
                    int offset = left - minPosition - Part.position;
                    var notes = DocManager.Inst.NotesClipboard.Select(note => note.Clone()).ToList();
                    notes.ForEach(note => note.position += offset);
                    DocManager.Inst.StartUndoGroup();
                    DocManager.Inst.ExecuteCmd(new AddNoteCommand(Part, notes));
                    int minDurTick = Part.GetMinDurTick(Project);
                    if (Part.Duration < minDurTick) {
                        DocManager.Inst.ExecuteCmd(new ResizePartCommand(Project, Part, minDurTick));
                    }
                    DocManager.Inst.EndUndoGroup();
                    Selection.Select(notes);
                    MessageBus.Current.SendMessage(new NotesSelectionEvent(Selection));

                    TickOffset = left - Part.position;
                }
            }
        }

        public void ToggleVibrato(UNote note) {
            var vibrato = note.vibrato;
            DocManager.Inst.StartUndoGroup();
            DocManager.Inst.ExecuteCmd(new VibratoLengthCommand(Part, note, vibrato.length == 0 ? NotePresets.Default.DefaultVibrato.VibratoLength : 0));
            DocManager.Inst.EndUndoGroup();
        }

        private void SetPlayPos(int tick, bool waitingRendering) {
            PlayPosWaitingRendering = waitingRendering;
            if (waitingRendering) {
                return;
            }
            tick -= Part?.position ?? 0;
            PlayPosX = TickToneToPoint(tick, 0).X;
            TickToLineTick(tick, out int left, out int right);
            PlayPosHighlightX = TickToneToPoint(left, 0).X;
            PlayPosHighlightWidth = (right - left) * TickWidth;
        }

        private void FocusNote(UNote note) {
            TickOffset = TickOffset = Math.Clamp(note.position + note.duration * 0.5 - ViewportTicks * 0.5, 0, HScrollBarMax);
            TrackOffset = Math.Clamp(ViewConstants.MaxTone - note.tone + 2 - ViewportTracks * 0.5, 0, VScrollBarMax);
        }

        private void ScrollIntoView(UNote note) {
            if (note.position < TickOffset || note.RightBound > TickOffset + ViewportTicks) {
                AutoScroll(TickToneToPoint(note.position, 0).X);
            }
            var toneMargin = 4;
            var noteOffset = ViewConstants.MaxTone - note.tone - 1;
            if (noteOffset < TrackOffset + toneMargin) {
                TrackOffset = Math.Max(noteOffset - toneMargin, 0);
            } else if (noteOffset > TrackOffset + ViewportTracks - toneMargin) {
                TrackOffset = Math.Min(noteOffset + toneMargin - ViewportTracks, VScrollBarMax);
            }
        }

        internal (UNote[], string[]) PrepareInsertLyrics() {
            var first = Selection.FirstOrDefault();
            var last = Selection.LastOrDefault();
            List<UNote> notes = new List<UNote>();
            var note = first;
            while (note != last) {
                notes.Add(note);
                note = note.Next;
            }
            notes.Add(note);
            var lyrics = notes.Select(n => n.lyric).ToArray();
            while (note.Next != null) {
                note = note.Next;
                notes.Add(note);
            }
            return (notes.ToArray(), lyrics);
        }

        bool IsExpSupported(string expKey) {
            if (Project == null || Part == null) {
                return true;
            }
            var track = Project.tracks[Part.trackNo];
            if (track.RendererSettings.Renderer == null) {
                return true;
            }
            if (Project.expressions.TryGetValue(expKey, out var descriptor)) {
                return track.RendererSettings.Renderer.SupportsExpression(descriptor);
            }
            if (expKey == track.VoiceColorExp.abbr) {
                return track.RendererSettings.Renderer.SupportsExpression(track.VoiceColorExp);
            }
            return true;
        }

        public void OnNext(UCommand cmd, bool isUndo) {
            if (cmd is UNotification notif) {
                if (cmd is LoadPartNotification loadPart) {
                    LoadPart(loadPart.part, loadPart.project);
                    double tickOffset = loadPart.tick - loadPart.part.position - Bounds.Width / TickWidth / 2;
                    TickOffset = Math.Clamp(tickOffset, 0, HScrollBarMax);
                    PrimaryKeyNotSupported = !IsExpSupported(PrimaryKey);
                } else if (cmd is LoadProjectNotification) {
                    UnloadPart();
                    LoadPortrait(null, null);
                    PrimaryKeyNotSupported = !IsExpSupported(PrimaryKey);
                } else if (cmd is SelectExpressionNotification selectExp) {
                    SecondaryKey = PrimaryKey;
                    PrimaryKey = selectExp.ExpKey;
                    PrimaryKeyNotSupported = !IsExpSupported(PrimaryKey);
                } else if (cmd is SetPlayPosTickNotification setPlayPosTick) {
                    SetPlayPos(setPlayPosTick.playPosTick, setPlayPosTick.waitingRendering);
                    MaybeAutoScroll(PlayPosX);
                } else if (cmd is FocusNoteNotification focusNote) {
                    if (focusNote.part == Part) {
                        FocusNote(focusNote.note);
                        if (Selection.Count <= 1) {
                            SelectNote(focusNote.note);
                        }
                    }
                } else if (cmd is ValidateProjectNotification
                    || cmd is SingersRefreshedNotification
                    || cmd is PhonemizedNotification) {
                    OnPartModified();
                    MessageBus.Current.SendMessage(new NotesRefreshEvent());
                } else if (notif is PartRenderedNotification && notif.part == Part) {
                    MessageBus.Current.SendMessage(new WaveformRefreshEvent());
                }
            } else if (cmd is PartCommand partCommand) {
                if (cmd is ReplacePartCommand replacePart) {
                    if (!isUndo) {
                        LoadPart(replacePart.newPart, replacePart.project);
                    } else {
                        LoadPart(replacePart.part, replacePart.project);
                    }
                }
                if (partCommand.part != Part) {
                    return;
                }
                if (cmd is RemovePartCommand) {
                    if (!isUndo) {
                        UnloadPart();
                    }
                } else if (cmd is AddPartCommand addPart) {
                    if (isUndo && addPart.part == Part) {
                        UnloadPart();
                    }
                } else if (cmd is ResizePartCommand) {
                    OnPartModified();
                } else if (cmd is MovePartCommand) {
                    OnPartModified();
                }
            } else if (cmd is NoteCommand noteCommand) {
                CleanupSelectedNotes();
                if (noteCommand.Part == Part) {
                    MessageBus.Current.SendMessage(new NotesRefreshEvent());

                    if (noteCommand is RemoveNoteCommand && isUndo) {
                        if (Selection.Select(noteCommand.Notes)) {
                            MessageBus.Current.SendMessage(new NotesSelectionEvent(Selection));
                        }
                    }
                }
            } else if (cmd is ExpCommand) {
                MessageBus.Current.SendMessage(new NotesRefreshEvent());
            } else if (cmd is TrackCommand) {
                if (cmd is RemoveTrackCommand removeTrack) {
                    if (removeTrack.removedParts.Contains(Part)) {
                        UnloadPart();
                    }
                }
                MessageBus.Current.SendMessage(new NotesRefreshEvent());
                if (cmd is TrackChangeSingerCommand trackChangeSinger) {
                    if (Part != null && trackChangeSinger.track.TrackNo == Part.trackNo) {
                        LoadPortrait(Part, Project);
                    }
                }
                PrimaryKeyNotSupported = !IsExpSupported(PrimaryKey);
            }
        }

        private void MaybeAutoScroll(double positionX) {
            var autoScrollPreference = Convert.ToBoolean(Preferences.Default.PlaybackAutoScroll);
            if (autoScrollPreference) {
                AutoScroll(positionX);
            }
        }

        private void AutoScroll(double positionX) {
            double scrollDelta = GetScrollValueDelta(positionX);
            TickOffset = Math.Clamp(TickOffset + scrollDelta, 0, HScrollBarMax);
        }

        private double GetScrollValueDelta(double positionX) {
            var pageScroll = Preferences.Default.PlaybackAutoScroll == 2;
            if (pageScroll) {
                return GetPageScrollScrollValueDelta(positionX);
            }
            return GetStationaryCursorScrollValueDelta(positionX);
        }

        private double GetStationaryCursorScrollValueDelta(double positionX) {
            double rightMargin = Preferences.Default.PlayPosMarkerMargin * Bounds.Width;
            if (positionX > rightMargin) {
                return (positionX - rightMargin) * playPosXToTickOffset;
            } else if (positionX < 0) {
                return positionX * playPosXToTickOffset;
            }
            return 0;
        }

        private double GetPageScrollScrollValueDelta(double positionX) {
            double leftMargin = (1 - Preferences.Default.PlayPosMarkerMargin) * Bounds.Width;
            if (positionX > Bounds.Width) {
                return (Bounds.Width - leftMargin) * playPosXToTickOffset;
            } else if (positionX < 0) {
                return (positionX - leftMargin) * playPosXToTickOffset;
            }
            return 0;
        }
    }
}


text:
import logging
import os
import sys
from settings import PACKAGE_ROOT

#------------------------------------------------------------------------------
# prepare environment for loading latino (Python.net interpreter should be used)
# see: http://pythonnet.sourceforge.net/
#------------------------------------------------------------------------------

dllPath = os.path.join(PACKAGE_ROOT, 'bin')
sys.path.append(dllPath)

try:
    import clr
    import System
    #import CrossBee
    from CrossBeeInterfaces import *
    import CrossBeeInterfaces
    #from System.Reflection import Assembly
    #Assembly.LoadFile(os.path.join(dllPath, 'CrossBeePrebuilt.dll'))
except Exception:
    logging.warning("DotNet assemblies could not be loaded! Probable reasons: missing dlls or wrong interpreter (see http://pythonnet.sourceforge.net). "
                    "Other functionality of ClowdFlows (besides .Net assemblies) should be OK!")
    pass

redpajama_set_name: RedPajamaGithub


text:
@interface ATSurveyParser : NSObject
- (NSError *)parserError;

- (ATSurvey *)surveyWithInteraction:(ATInteraction *)interaction;

@end


text:
title: "Power of Survey Research in Evidence-Based Policymaking"
collection: talks
type: "Conference Session Coordinator"
# permalink: /talks/2017-07-18-esra
venue: "The 7th Conference of the European Survey Research Association"
date: 2017-07-18
location: "Lisbon, Portugal"
---

Evidence-based policymaking (EBP) involves the use of evidence collected by scientifically rigorous methods to inform the decision-making process. EBP has been utilized by both the U.S. and UK governments in the last few decades to replace the ideology-based policymaking process. In developing countries, EBP is less implemented due to the lack of resources and limited civil liberty. We utilize data visualization to complement the evidence-based approach to addressing policy issues in developing countries.


text:
const pkg = require('./package');

// ensure production mode
process.env.NODE_ENV = 'production';

// Injected to pkg via electron-builder extraMetadata configuration.
process.env.SENTRY_DSN = pkg.SENTRY_DSN;

require('./lib');


text:
package edu.clemson.cs.rsrg.treewalk;

import edu.clemson.cs.rsrg.absyn.*;
import java.util.Iterator;
import java.util.LinkedList;

public abstract class TreeWalkerStackVisitor extends TreeWalkerVisitor {

    // ===========================================================
    // Member Fields
    // ===========================================================

    private LinkedList<ResolveConceptualElement> myVisitStack =
        new LinkedList<>();

    private ResolveConceptualElement myParent;

    // ===========================================================
    // Public Methods
    // ===========================================================

    public void preAnyStack(ResolveConceptualElement data) {}

    public void postAnyStack(ResolveConceptualElement data) {}

    public final void preAny(ResolveConceptualElement data) {
        preAnyStack(data);
        myParent = data;
        pushParent();
    }

    public final void postAny(ResolveConceptualElement data) {
        popParent();
        postAnyStack(data);
    }

    // ===========================================================
    // Protected Methods
    // ===========================================================

    protected final ResolveConceptualElement getParent() {
        return myVisitStack.peek();
    }

    protected final ResolveConceptualElement getAncestor(int index) {
        return myVisitStack.get(index);
    }

    protected final int getAncestorSize() {
        return myVisitStack.size();
    }

    protected final Iterator<ResolveConceptualElement> getAncestorInterator() {
        return myVisitStack.iterator();
    }

    // ===========================================================
    // Private Methods
    // ===========================================================

    private final void pushParent() {
        myVisitStack.push(myParent);
    }

    private final void popParent() {
        myVisitStack.pop();
    }

}


text:
import React from 'react';
import _ from 'underscore';
import {withGoogleMap, GoogleMap, Marker, InfoWindow} from 'react-google-maps';
import co from 'co';
import $ from 'jquery';
import PlaceService from '../services/PlaceService';

const NossoLixoMap = withGoogleMap(props => (
  <GoogleMap
    zoom={props.zoom}
    center={props.currentLocation}
  >
    {props.markers.map((place, index) => (
      <Marker
        title={place.name}
        position={place.position}
        key={index}
        icon='/public/images/icon.svg'
        defaultAnimation={4}
        onClick={ () => props.onMarkerClick(index) }
      >
        {place.requestedInfo && (
          <InfoWindow
            onDomReady={props.onInfoWindowReady}
            >
            <div style={{ display: `none` }}>

{place.name}

{place.description}

{place.street}, {place.number} - {place.district}. {place.city}/{place.state}

{place.phone_number}

{place.email}

{place.site}

Coleta

{place.categories.map(category => category.name).join(', ')}

          </InfoWindow>
        )}
      </Marker>
    ))}
  </GoogleMap>
));

export default class Map extends React.Component {
  constructor () {
    super();
    this.state = { markers: [], currentLocation: this.defaultLocation(), zoom: 4 };
    this.isUnmounted = false;

    _.bindAll(this, 'buildMarkers', 'getLocation', 'locationCallback', 'handleMarkerClick');
  }

  componentDidMount() {
    var fn = co.wrap(function* (val) {
      return yield Promise.resolve(val);
    });

    this.getLocation();

    var placeService = new PlaceService();
    fn(placeService.all())
      .then(this.buildMarkers)
      .catch(this.rescueError);
  }

  componentWillUnmount() {
    this.isUnmounted = true;
  }

  buildMarkers(response) {
    var markers = [];
    response.body.forEach(function(place) {
      place.position = { lat: Number.parseFloat(place.lat), lng: Number.parseFloat(place.lng) };
      place.requestedInfo = false;
      markers.push(place);
    })
    this.setState({ markers: markers });
  }

  rescueError(err) {
    console.error(err.stack);
  }

  defaultLocation() {
    return {
      lat: -11.996921,
      lng: -51.957208
    }
  }

  getLocation() {
    if (!_.isUndefined(navigator) && navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(this.locationCallback);
    }
  }

  locationCallback(position) {
    if (this.isUnmounted) {
      return;
    }

    this.setState({
      currentLocation: { lat: position.coords.latitude, lng: position.coords.longitude },
      zoom: 12
    });
  }

  handleMarkerClick(placeIndex) {
    var self = this;

    this.state.markers.forEach(function(marker, index) {
      if (index == placeIndex) {
        marker.requestedInfo = true;
      } else {
        marker.requestedInfo = false;
      }
      self.state.markers[index] = marker;
    });

    this.setState({ markers: this.state.markers });
  }

  handleInfoWindowReady() {
    $(this.content).find('div').fadeIn();
  }

  render() {
    return (
      <NossoLixoMap
        containerElement={
          <div style={{ width: `100%`, height: `100%` }} />
        }
        mapElement={
          <div style={{ height: `100%` }} />
        }
        zoom={this.state.zoom}
        currentLocation={this.state.currentLocation}
        markers={this.state.markers}
        onMarkerClick={this.handleMarkerClick}
        onInfoWindowReady={this.handleInfoWindowReady}
      />
    );
  }
}


text:
package org.apereo.portal.groups.pags.testers;

import java.util.regex.Pattern;
import org.apereo.portal.groups.pags.dao.IPersonAttributesGroupTestDefinition;

/**
 * A tester for matching the possibly multiple values of an attribute (made lower case) against a
 * regular expression. The match function attempts to match the entire region against the pattern
 * specified.
 *
 *
For example, if the pattern is specified as "^02([a-d])*":
 *
 *

 *

 *    Input	Matches
 *

 *

 *    02A	Yes
 *

 *

 *    02ABCD	Yes
 *

 *

 *    A02D	No
 *

 *

 *    02	Yes
 *

 *

 *    02MisMatch	No
 *

 *

 *    PatternWillNeverMatch	No
 *

 *

 *
 *
 * @see org.apereo.portal.groups.pags.testers.EagerRegexTester
 */
public class LowercasedRegexTester extends AbstractStringTester {
    protected Pattern pattern;

    /** @since 4.3 */
    public LowercasedRegexTester(IPersonAttributesGroupTestDefinition definition) {
        super(definition);
        this.pattern = Pattern.compile(definition.getTestValue());
    }

    @Override
    public boolean test(String att) {
        return pattern.matcher(att.toLowerCase()).matches();
    }
}


text:
import re
import time
import threading

import cv2
import imageio
import numpy as np
from websocket import create_connection

import uiautomator2 as u2

def iter_image_from_minicap(uri):
    ws = create_connection(uri)
    try:
        while True:
            msg = ws.recv()
            if isinstance(msg, str):
                print("<-", msg)
            else:
                yield msg
    finally:
        ws.close()

class Screenrecord:
    def __init__(self, d: u2.Device):
        self._d = d
        self._running = False
        self._stop_event = threading.Event()
        self._done_event = threading.Event()
        self._filename = None
        self._fps = 20  # initial value

    def __call__(self, *args, **kwargs):
        self._start(*args, **kwargs)
        return self

    def _iter_minicap(self):
        http_url = self._d.path2url("/minicap")
        ws_url = re.sub("^http", "ws", http_url)
        ws = create_connection(ws_url)
        try:
            while not self._stop_event.is_set():
                msg = ws.recv()
                if isinstance(msg, str):
                    # print("<-", msg)
                    pass
                else:
                    yield msg
        finally:
            ws.close()

    def _resize_to(self, im, framesize):
        """
        framesize: tuple of (height, width)
        """
        vh, vw = framesize
        h, w = im.shape[:2]
        frame = np.zeros((vh, vw, 3),
                         dtype=np.uint8)  # create black background canvas
        sh = vh / h
        sw = vw / w
        if sh < sw:
            h, w = vh, int(sh * w)
        else:
            h, w = int(sw * h), vw
        left, top = (vw - w) // 2, (vh - h) // 2
        frame[top:top + h, left:left + w, :] = cv2.resize(im, dsize=(w, h))
        return frame

    def _pipe_resize(self, image_iter):
        """ image to same size """
        firstim = next(image_iter)
        yield firstim
        vh, vw = firstim.shape[:2]
        for im in image_iter:
            if im.shape != firstim.shape:
                im = self._resize_to(im, (vh, vw))
            yield im

    def _pipe_convert(self, raw_iter):
        # raw data -> imageio
        for raw in raw_iter:
            yield imageio.imread(raw)

    def _pipe_limit(self, raw_iter):
        findex = 0
        fstart = time.time()
        for raw in raw_iter:
            elapsed = time.time() - fstart
            fcount = int(elapsed * self._fps)
            for _ in range(fcount - findex):
                yield raw
            findex = fcount

    def _run(self):
        pipelines = [self._pipe_limit, self._pipe_convert, self._pipe_resize]
        _iter = self._iter_minicap()
        for p in pipelines:
            _iter = p(_iter)

        with imageio.get_writer(self._filename, fps=self._fps) as wr:
            for im in _iter:
                wr.append_data(im)
        self._done_event.set()

    def _start(self, filename: str, fps: int = 20):
        if self._running:
            raise RuntimeError("screenrecord is already started")

        assert isinstance(fps, int)
        self._filename = filename
        self._fps = fps

        self._running = True
        th = threading.Thread(name="image2video", target=self._run)
        th.daemon = True
        th.start()

    def stop(self):
        """
        stop record and finish write video
        Returns:
            bool: whether video is recorded.
        """
        if not self._running:
            raise RuntimeError("screenrecord is not started")
        self._stop_event.set()
        ret = self._done_event.wait(10.0)

        # reset
        self._stop_event.clear()
        self._done_event.clear()
        self._running = False
        return ret


text:
package com.twu.biblioteca;

import com.twu.model.Biblioteca;

import java.io.PrintStream;
import java.util.Scanner;

public class BibliotecaApp {

    private static PrintStream printStream = new PrintStream(System.out);
    private static Scanner scanner = new Scanner(System.in);

    public static void main(String[] args) {
        Biblioteca biblioteca = new Biblioteca();
        welcome();
        while (!biblioteca.getIsQuit()) {
            printStream.println(biblioteca.getOutput());
            biblioteca.operate(getInput());
        }
    }

    private static void welcome() {
        printStream.println("Welcome to Biblioteca!");
    }

    public static String getInput() {
        return scanner.nextLine();
    }

}


text:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval">
    <solid android:color="@color/deviant_art" />
</shape>


text:
<!doctype html>

  <title>{% if result %}{% block title %}{{title}}{% endblock %}{% else %}Error{% endif %} | {{name}}'s mailpile</title>
  {% include("partials/head.html") %}
  {% block head %}{% endblock %}

{% if result.complete %}
{% include("partials/topbar.html") %}
{% else %}
{% include("partials/topbar_setup.html") %}

{% endif %}

  {% block content %}{{results}}{% endblock %}
  {% include("setup/modals.html") %}


text:
require "tmpdir"
require "fileutils"

RSpec.describe AwsAsCode::Task::Upload do
  let(:config) do
    OpenStruct.new json_dir: "/home/user/cfn-compiled",
                   stack: "staging",
                   bucket: "test-bucket",
                   version: "VERSION"
  end

  let(:instance) { described_class.new config }

  describe "#execute" do
    subject { instance.execute }

    let(:first) { double("FIRST FILE") }
    let(:second) { double("SECOND FILE") }
    let(:third) { double("THIRD FILE") }

    before do
      allow(instance)
        .to receive(:input_files)
        .and_return [first, second, third]
    end

    it "uploads every input file" do
      expect(instance)
        .to receive(:upload_single_file)
        .with(first)

      expect(instance)
        .to receive(:upload_single_file)
        .with(second)

      expect(instance)
        .to receive(:upload_single_file)
        .with(third)

      instance.execute
    end
  end

  describe "#upload_single_file" do
    let(:filename) { "/home/user/cfn-compiled/subdir/file.json" }
    subject(:action) { instance.send :upload_single_file, filename }

    before do
      allow(instance)
        .to receive_message_chain(:bucket, :object, :upload_file)
    end

    it "uploads a file to S3 bucket" do
      expect(instance)
        .to receive_message_chain(:bucket, :object, :upload_file)
        .with(filename)

      action
    end

    it "users a relative path and stack name as a name for the new S3 object" do
      expect(instance)
        .to receive_message_chain(:bucket, :object)
        .with("staging/VERSION/subdir/file.json")

      action
    end
  end

  describe "#bucket" do
    subject(:action) { instance.send :bucket }

    let(:bucket) { double("bucket") }

    before do
      allow(Aws::S3::Resource)
        .to receive_message_chain(:new, :bucket)
        .and_return bucket
    end

    it "uses configured bucket name to access S3" do
      expect(Aws::S3::Resource)
        .to receive_message_chain(:new, :bucket)
        .with("test-bucket")

      action
    end

    it "return S3 bucket" do
      expect(subject).to eq bucket
    end
  end

  describe "#input_files" do
    subject(:action) { instance.send :input_files }

    let(:json_dir) { Dir.mktmpdir }

    let(:config) do
      OpenStruct.new json_dir: json_dir
    end

    before do
      FileUtils.touch File.join(json_dir, "1.json")
      FileUtils.touch File.join(json_dir, "2.txt")
      FileUtils.touch File.join(json_dir, "3.json")
    end

    after do
      FileUtils.remove_entry_secure json_dir
    end

    it "lists all json files in the configured dir" do
      expected = [
        File.join(json_dir, "1.json"),
        File.join(json_dir, "3.json")
      ]
      expect(action).to match_array expected
    end
  end
end


text:
var pmConfig = angular.module('publicMarket.config', ['ngSanitize']);

pmConfig.constant('DATA_ROOT_PATH', 'http://traeg.org/proj/mobilemarket/data/');


text:
function temp_jhu_update_p02()
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%     Copyright 2014 University of Memphis
%
% Licensed under the Apache License, Version 2.0 (the "License");
% you may not use this file except in compliance with the License.
% You may obtain a copy of the License at
%
%     http://www.apache.org/licenses/LICENSE-2.0
%
% Unless required by applicable law or agreed to in writing, software
% distributed under the License is distributed on an "AS IS" BASIS,
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
% See the License for the specific language governing permissions and
% limitations under the License.
%%
files=dir('C:\DataProcessingFramework\data\JHU\formatteddata\p02*');
for i=1:length(files)
    load(['C:\DataProcessingFramework\data\JHU\formatteddata\' files(i).name]);
    newsid=sprintf('s%02d',i)
    oldsid=D.METADATA.SID

    D.METADATA.SID=newsid;
    D.NAME=strrep(D.NAME,oldsid,newsid);
    newfilename=strrep(files(i).name,oldsid,newsid);
    save(['C:\DataProcessingFramework\data\JHU\formatteddata\' newfilename],'D');
    delete(['C:\DataProcessingFramework\data\JHU\formatteddata\' files(i).name]);
end
end


text:
{{ partial "header.html" . }}

  Unsere Philosophie

Nur wer Freude verspürt, kann Kreativität versprühen! Frei nach diesem Motto steht bei uns der Mensch im Mittelpunkt. Sowohl in unseren Räumen als auch im Umgang mit unseren Kunden und Dienstleistern. Das Resultat: Ein inspirierendes Arbeitsklima und tiefgehende Beziehungen, aus denen heraus kraftvolle Arbeiten entstehen.

    Unser Team

{{ with .Params.menschen.mensch }}

  {{ range . }}

{{ .name }}

{{ replace .job "\n" "
" | safeHTML }}

  {{ end }}

{{ end }}

      Stimmen

"FFI – das sind vor allem auch die Menschen. Die Kollegen. Die Kunden. Die Lieferanten. Nur gemeinsam können wir überzeugend und richtungsweisend sein."

Ruben Maier-Gerber

Geschäftsführer bei ffi

    {{ partial "srcset" (dict "meta" . "title" "Ruben Maier-Gerber" "image" "/img/ruben.jpg" "class" "circle" "sizes" (dict "default" "225px" "641px" "28vw" "1025px" "290px") ) }}

Ihr Ansprechpartner

Ruben Maier-Gerber

Nachhaltige Zusammenarbeit und kurze Wege. Dafür stehen wir bei FFI. Anrufen. Mailen. Termin ausmachen. Wir haben guten Kaffee! Und viele Köpfe voller Ideen.

      {{ partial "button" (dict "title" "E-Mail schreiben" "url" "/anfrage-mail-handler.php" ) }}

+49 7522 978 43 0

{{ partialCached "footer.html" . }}


text:
package com.suscipio_solutions.consecro_mud.WebMacros;

import java.util.Enumeration;

import com.suscipio_solutions.consecro_mud.Areas.interfaces.Area;
import com.suscipio_solutions.consecro_mud.core.CMLib;
import com.suscipio_solutions.consecro_web.interfaces.HTTPRequest;

@SuppressWarnings("rawtypes")
public class RoomNext extends StdWebMacro
{
	@Override public String name() { return "RoomNext"; }

	@Override
	public String runMacro(HTTPRequest httpReq, String parm)
	{
		final java.util.Map<String,String> parms=parseParms(parm);
		final String area=httpReq.getUrlParameter("AREA");
		if((area==null)||(CMLib.map().getArea(area)==null))
			return " @break@";
		final Area A=CMLib.map().getArea(area);
		final String last=httpReq.getUrlParameter("ROOM");
		if(parms.containsKey("RESET"))
		{
			if(last!=null) httpReq.removeUrlParameter("ROOM");
			return "";
		}
		String lastID="";

		for(final Enumeration d=A.getProperRoomnumbers().getRoomIDs();d.hasMoreElements();)
		{
			final String roomid=(String)d.nextElement();
			if((last==null)||((last.length()>0)&&(last.equals(lastID))&&(!roomid.equals(lastID))))
			{
				httpReq.addFakeUrlParameter("ROOM",roomid);
				return "";
			}
			lastID=roomid;
		}
		httpReq.addFakeUrlParameter("ROOM","");
		if(parms.containsKey("EMPTYOK"))
			return "<!--EMPTY-->";
		return " @break@";
	}
}


text:
I18nRoutingBundle, generate your I18N Routes for Symfony2
=========================================================

If you have a website multilingual, this bundle avoids of copy paste your routes
for different languages. Additionally it allows to translate given routing parameters
between languages in Router#match and UrlGenerator#generate using either a Symfony Translator
or a Doctrine DBAL (+Cache) based backend.

[![Build Status](https://secure.travis-ci.org/BeSimple/BeSimpleI18nRoutingBundle.png?branch=master)](http://travis-ci.org/BeSimple/BeSimpleI18nRoutingBundle)

## Information

When you create an I18N route and you go on it with your browser, the locale will be updated.

## Installation

### Add I18nRoutingBundle to your vendor/bundles dir

    git submodule add git://github.com/BeSimple/BeSimpleI18nRoutingBundle.git vendor/bundles/BeSimple/I18nRoutingBundle

### Add I18nRoutingBundle to your application kernel

    // app/AppKernel.php
    public function registerBundles()
    {
        return array(
            // ...
            new BeSimple\I18nRoutingBundle\BeSimpleI18nRoutingBundle(),
            // ...
        );
    }

### Register the BeSimple namespace

    // app/autoload.php
    $loader->registerNamespaces(array(
        'BeSimple' => __DIR__.'/../vendor/bundles',
        // your other namespaces
    ));

### Update your configuration

    // app/config/config.yml
    be_simple_i18n_routing: ~

## Create your routing

To define internationalized routes in XML or YAML, you need to import the
routing file by using the ``be_simple_i18n`` type:

    my_yaml_i18n_routes:
        resource: "@MyWebsiteBundle/Resources/config/routing/i18n.yml"
        type: be_simple_i18n
    my_xml_i18n_routes:
        resource: "@MyWebsiteBundle/Resources/config/routing/i18n.xml"
        type: be_simple_i18n

### Yaml routing file

    homepage:
        locales:  { en: "/welcome", fr: "/bienvenue", de: "/willkommen" }
        defaults: { _controller: MyWebsiteBundle:Frontend:index }

### XML routing file

    <?xml version="1.0" encoding="UTF-8" ?>

    <routes xmlns="http://besim.pl/schema/i18n_routing"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://besim.pl/schema/i18n_routing http://besim.pl/schema/i18n_routing/routing-1.0.xml">

        <route id="homepage">
            <locale key="en">/welcome</locale>
            <locale key="fr">/bienvenue</locale>
            <locale key="de">/willkommen</locale>
            <default key="_controller">MyWebsiteBundle:Frontend:index</default>
        </route>
    </routes>

Note that the XML file uses a different namespace than when using the core
loader: ``http://besim.pl/schema/i18n_routing``.

### PHP routing file

    <?php

    use BeSimple\I18nRoutingBundle\Routing\I18nRoute;
    use Symfony\Component\Routing\RouteCollection;

    $collection = new RouteCollection();
    $route      = new I18nRoute('homepage',
        array('en' => '/welcome', 'fr' => '/bienvenue', 'de' => '/willkommen'),
        array('_controller' => 'MyWebsiteBundle:Frontend:index')
    );
    $collection->addCollection($route->getCollection());

    return $collection;

### You can insert classic route in your routing

#### Yaml routing file

    homepage:
        locales:  { en: "/en/", fr: "/fr/", de: "/de/" }
        defaults: { _controller: HelloBundle:Frontend:homepage }

    welcome:
        locales:  { en: "/welcome/{name}", fr: "/bienvenue/{name}", de: "/willkommen/{name}" }
        defaults: { _controller: MyWebsiteBundle:Frontend:welcome }

#### XML routing file

    <?xml version="1.0" encoding="UTF-8" ?>

    <routes xmlns="http://besim.pl/schema/i18n_routing"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://besim.pl/schema/i18n_routing http://besim.pl/schema/i18n_routing/routing-1.0.xml">

        <route id="hello" pattern="/hello/{name}">
            <default key="_controller">HelloBundle:Hello:index</default>
        </route>

        <route id="homepage">
            <locale key="en">/welcome/{name}</locale>
            <locale key="fr">/bienvenue/{name}</locale>
            <locale key="de">/willkommen/{name}</locale>
            <default key="_controller">MyWebsiteBundle:Frontend:index</default>
        </route>
    </routes>

#### PHP routing file

    <?php

    use BeSimple\I18nRoutingBundle\Routing\I18nRoute;
    use Symfony\Component\Routing\Route;
    use Symfony\Component\Routing\RouteCollection;

    $collection = new RouteCollection();
    $collection->add('hello', new Route('/hello/{name}', array(
        '_controller' => 'HelloBundle:Hello:index',
    )));
    $route = new I18nRoute('homepage',
        array('en' => '/welcome/{name}', 'fr' => '/bienvenue/{name}', 'de' => '/willkommen/{name}'),
        array('_controller' => 'MyWebsiteBundle:Frontend:index',)
    );
    $collection->addCollection($route->getCollection());

    return $collection;

## Generate a route in your templates

### Specify a locale

#### Twig

    {{ path('homepage.en') }}
    {{ path('homepage', { 'locale': 'en' }) }}
    {{ path('homepage.fr') }}
    {{ path('homepage', { 'locale': 'fr' }) }}
    {{ path('homepage.de') }}
    {{ path('homepage', { 'locale': 'de' }) }}

#### PHP

    <?php echo $view['router']->generate('homepage.en') ?>
    <?php echo $view['router']->generate('homepage', array('locale' => 'en')) ?>
    <?php echo $view['router']->generate('homepage.fr') ?>
    <?php echo $view['router']->generate('homepage', array('locale' => 'fr')) ?>
    <?php echo $view['router']->generate('homepage.de') ?>
    <?php echo $view['router']->generate('homepage', array('locale' => 'de')) ?>

### Use current locale of user

#### Twig

    {{ path('homepage') }}

#### PHP

    <?php echo $view['router']->generate('homepage') ?>

## Translating the route attributes

If the static parts of your routes are translated you get to the point really
fast when dynamic parts such as product slugs, category names or other dynamic
routing parameters should be translated. The bundle provides 2 implementations.

After configuring the backend you want to use (see below for each one), you
can define a to be translated attribute in your route defaults:

    product_view:
        locales: { en: "/product/{slug}", de: "/produkt/{slug}" }
        defaults: { _controller: "ShopBundle:Product:view", _translate: "slug" }
    product_view2:
        locales: { en: "/product/{category}/{slug}", de: "/produkt/{category}/{slug}" }
        defaults:
            _controller: "ShopBundle:Product:view"
            _translate: ["slug", "category"]

The same goes with generating routes, now backwards:

    {{ path("product_view", {"slug": product.slug, "translate": "slug"}) }}
    {{ path("product_view2", {"slug": product.slug, "translate": ["slug", "category]}) }}

The reverse translation is only necessary if you have the "original" values
in your templates. If you have access to the localized value of the current
locale then you can just pass this and do not hint to translate it with the
"translate" key.

### Doctrine DBAL Backend

Configure the use of the DBAL backend

    // app/config/config.yml
    be_simple_i18n_routing:
        attribute_translator:
            type: doctrine_dbal
            connection: default # Doctrine DBAL connection name. Using null (default value) will use the default connection
            cache: apc

The Doctrine Backend has the following table structure:

    CREATE TABLE routing_translations (
        id INT NOT NULL,
        route VARCHAR(255) NOT NULL,
        locale VARCHAR(255) NOT NULL,
        attribute VARCHAR(255) NOT NULL,
        localized_value VARCHAR(255) NOT NULL,
        original_value VARCHAR(255) NOT NULL,
        UNIQUE INDEX UNIQ_291BA3522C420794180C698FA7AEFFB (route, locale, attribute),
        INDEX IDX_291BA352D951F3E4 (localized_value),
        PRIMARY KEY(id)
    ) ENGINE = InnoDB;

Lookups are made through the combination of route name, locale and attribute
of the route to be translated.

Every lookup is cached in a Doctrine\Common\Cache\Cache instance that you
should configure to be APC, Memcache or Xcache for performance reasons.

If you are using Doctrine it automatically registers a listener for SchemaTool
to create the routing_translations table for your database backend, you only
have to call:

    ./app/console doctrine:schema:update --dump-sql
    ./app/console doctrine:schema:update --force

### Translator backend

This implementation uses the Symfony2 translator to translate the attributes.
The translation domain will be created using the pattern `<route name>_<attribute name>`

    // app/config/config.yml
    be_simple_i18n_routing:
        attribute_translator:
            type: translator

### Custom backend

If you want to use a different implementation, simply create a service implementing
`BeSimple\I18nRoutingBundle\Routing\Translator\AttributeTranslatorInterface`.

    // app/config/config.yml
    be_simple_i18n_routing:
        attribute_translator:
            type: service
            id: my_attribute_translator

## License

This bundle is under the MIT license. See the complete license in the bundle:

    Resources/meta/LICENSE


text:
<!--
  Copyright 2012 Google Inc.

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
  -->
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:iosched="http://schemas.android.com/apk/res/at.devfest.app"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="@dimen/element_spacing_normal"
    android:layout_marginBottom="@dimen/element_spacing_normal">

    <com.google.android.apps.iosched.ui.widget.BezelImageView android:id="@+id/speaker_image"
        android:scaleType="centerCrop"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_width="@dimen/speaker_image_size"
        android:layout_height="@dimen/speaker_image_size"
        android:layout_marginRight="@dimen/speaker_image_padding"
        android:clickable="true"
        android:focusable="true"
        iosched:borderDrawable="@drawable/bezel_border"
        android:src="@drawable/person_image_empty" />

    <TextView android:id="@+id/speaker_header"
        android:layout_toRightOf="@id/speaker_image"
        android:layout_alignParentTop="true"
        android:layout_alignParentRight="true"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        style="@style/TextHeader3" />

    <TextView android:id="@+id/speaker_abstract"
        android:layout_below="@id/speaker_header"
        android:layout_alignLeft="@id/speaker_header"
        android:layout_alignRight="@id/speaker_header"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        style="@style/TextBody" />
</RelativeLayout>


text:
SuburiMongrel-rack-handler
==========================

Rack handler to deploy Mongrel server in an suburi.

Use
---

1. Install gem

    `gem install SuburiMongrel-rack-handler`

2. Configure suburi in `ENV['RAILS_RELATIVE_URL_ROOT']` (maybe in your code?)

    `ENV['RAILS_RELATIVE_URL_ROOT'] = '/my/own/url/path'`

3. Start Rails application with Bundle

    `bundle exec rails server SuburiMongrel`

Redmine users
-------------

If you are using this gem to serve your redmine server in an deep uri then you can
put Step 2 in your `<redmine>/config/environments/<your_environment_file>.rb`. Remenber
to add:

```ruby
# Path to deploy redmine of this environment in web server
ENV['RAILS_RELATIVE_URL_ROOT'] = '/my/own/url/path'
config.relative_url_root = ENV['RAILS_RELATIVE_URL_ROOT']
```


text:
module Twig
module Parsing

module Assignment
  include Treetop::Runtime

  def root
    @root ||= :assignment
  end

  include Identifier

  include Whitespace

  include Expression

  module Assignment0
    def identifier
      elements[0]
    end

    def expression
      elements[4]
    end
  end

  def _nt_assignment
    start_index = index
    if node_cache[:assignment].has_key?(index)
      cached = node_cache[:assignment][index]
      if cached
        node_cache[:assignment][index] = cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
        @index = cached.interval.end
      end
      return cached
    end

    i0, s0 = index, []
    r1 = _nt_identifier
    s0 << r1
    if r1
      s2, i2 = [], index
      loop do
        r3 = _nt_ws
        if r3
          s2 << r3
        else
          break
        end
      end
      r2 = instantiate_node(SyntaxNode,input, i2...index, s2)
      s0 << r2
      if r2
        if (match_len = has_terminal?("=", false, index))
          r4 = true
          @index += match_len
        else
          terminal_parse_failure('"="')
          r4 = nil
        end
        s0 << r4
        if r4
          s5, i5 = [], index
          loop do
            r6 = _nt_ws
            if r6
              s5 << r6
            else
              break
            end
          end
          r5 = instantiate_node(SyntaxNode,input, i5...index, s5)
          s0 << r5
          if r5
            r7 = _nt_expression
            s0 << r7
          end
        end
      end
    end
    if s0.last
      r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
      r0.extend(Assignment0)
    else
      @index = i0
      r0 = nil
    end

    node_cache[:assignment][start_index] = r0

    r0
  end

end

class AssignmentParser < Treetop::Runtime::CompiledParser
  include Assignment
end

end
end


text:
using System;
using FlatBuffers;

namespace droid.Runtime.Messaging.FBS
{
  public struct FReactions : IFlatbufferObject
{
  private Table __p;
  public ByteBuffer ByteBuffer { get { return this.__p.bb; } }
  public static FReactions GetRootAsFReactions(ByteBuffer _bb) { return GetRootAsFReactions(_bb, new FReactions()); }
  public static FReactions GetRootAsFReactions(ByteBuffer _bb, FReactions obj) { return (obj.__assign(_bb.GetInt(_bb.Position) + _bb.Position, _bb)); }
  public static bool FReactionsBufferHasIdentifier(ByteBuffer _bb) { return Table.__has_identifier(_bb, "XREA"); }
  public void __init(int _i, ByteBuffer _bb) { this.__p.bb_pos = _i; this.__p.bb = _bb; }
  public FReactions __assign(int _i, ByteBuffer _bb) { this.__init(_i, _bb); return this; }

  public FReaction? Reactions(int j) { int o = this.__p.__offset(4); return o != 0 ? (FReaction?)(new FReaction()).__assign(this.__p.__indirect(this.__p.__vector(o) + j * 4), this.__p.bb) : null; }
  public int ReactionsLength { get { int o = this.__p.__offset(4); return o != 0 ? this.__p.__vector_len(o) : 0; } }
  public FReaction? ReactionsByKey(string key) { int o = this.__p.__offset(4); return o != 0 ? FReaction.__lookup_by_key(this.__p.__vector(o), key, this.__p.bb) : null; }
  public string ApiVersion { get { int o = this.__p.__offset(6); return o != 0 ? this.__p.__string(o + this.__p.bb_pos) : null; } }
#if ENABLE_SPAN_T
  public Span<byte> GetApiVersionBytes() { return __p.__vector_as_span(6); }
#else
  public ArraySegment<byte>? GetApiVersionBytes() { return this.__p.__vector_as_arraysegment(6); }
#endif
  public byte[] GetApiVersionArray() { return this.__p.__vector_as_array<byte>(6); }
  public FSimulatorConfiguration? SimulatorConfiguration { get { int o = this.__p.__offset(8); return o != 0 ? (FSimulatorConfiguration?)(new FSimulatorConfiguration()).__assign(o + this.__p.bb_pos, this.__p.bb) : null; } }
  public bool Close { get { int o = this.__p.__offset(10); return o != 0 ? 0!=this.__p.bb.Get(o + this.__p.bb_pos) : (bool)false; } }

  public static void StartFReactions(FlatBufferBuilder builder) { builder.StartObject(4); }
  public static void AddReactions(FlatBufferBuilder builder, VectorOffset reactionsOffset) { builder.AddOffset(0, reactionsOffset.Value, 0); }
  public static VectorOffset CreateReactionsVector(FlatBufferBuilder builder, Offset<FReaction>[] data) { builder.StartVector(4, data.Length, 4); for (int i = data.Length - 1; i >= 0; i--) builder.AddOffset(data[i].Value); return builder.EndVector(); }
  public static VectorOffset CreateReactionsVectorBlock(FlatBufferBuilder builder, Offset<FReaction>[] data) { builder.StartVector(4, data.Length, 4); builder.Add(data); return builder.EndVector(); }
  public static void StartReactionsVector(FlatBufferBuilder builder, int numElems) { builder.StartVector(4, numElems, 4); }
  public static void AddApiVersion(FlatBufferBuilder builder, StringOffset apiVersionOffset) { builder.AddOffset(1, apiVersionOffset.Value, 0); }
  public static void AddSimulatorConfiguration(FlatBufferBuilder builder, Offset<FSimulatorConfiguration> simulatorConfigurationOffset) { builder.AddStruct(2, simulatorConfigurationOffset.Value, 0); }
  public static void AddClose(FlatBufferBuilder builder, bool close) { builder.AddBool(3, close, false); }
  public static Offset<FReactions> EndFReactions(FlatBufferBuilder builder) {
    int o = builder.EndObject();
    return new Offset<FReactions>(o);
  }
  public static void FinishFReactionsBuffer(FlatBufferBuilder builder, Offset<FReactions> offset) { builder.Finish(offset.Value, "XREA"); }
  public static void FinishSizePrefixedFReactionsBuffer(FlatBufferBuilder builder, Offset<FReactions> offset) { builder.FinishSizePrefixed(offset.Value, "XREA"); }
};

}


text:
#ifndef STXXL_IO_CREATE_FILE_HEADER
#define STXXL_IO_CREATE_FILE_HEADER

#include <stxxl/bits/io/file.h>
#include <stxxl/bits/namespace.h>

#include <string>

STXXL_BEGIN_NAMESPACE

//! create fileio object from io_impl string and a few parameters
file * create_file(const std::string& io_impl,
                   const std::string& filename,
                   int options,
                   int physical_device_id = file::DEFAULT_QUEUE,
                   int disk_allocator_id = file::NO_ALLOCATOR);

// prototype
class disk_config;

//! create fileio object from disk_config parameter
file * create_file(disk_config& config, int mode,
                   int disk_allocator_id = file::NO_ALLOCATOR);

STXXL_END_NAMESPACE

#endif // !STXXL_IO_CREATE_FILE_HEADER
// vim: et:ts=4:sw=4


text:
package de.tum.in.niedermr.ta.core.artifacts.exceptions;

/** Iterator exception. */
public class IteratorException extends Exception {

	/** Serial version UID. */
	private static final long serialVersionUID = 1L;

	/** Constructor. */
	public IteratorException(String message, Throwable t) {
		super(message, t);
	}
}


text:
Ici nous allons placer les fonctions qui permettent d'interragir avec l'API

Par exemple la gestion des offerings ou la gestion des requetes


text:
require 'spec_helper'

class A
  def initialize a
    @a = a
  end

  def to_s
    @a
  end
end

describe "Object#to_js" do
  it "should return quoted string for string" do
    "Hello".to_js.should == "\"Hello\""
  end

  it "should return string representation for fixnum" do
    5.to_js.should == "5"
  end

  it "should return string representation for float" do
    5.5.to_js.should == "5.5"
  end

  it "should return string representation for bigint" do
    (1000**1000).to_js.should == (1000**1000).to_s
  end

  it "should return undefined for nil" do
    nil.to_js.should == "undefined"
  end

  it "should return js array literal for array" do
    [1, 2, "Hello"].to_js.should == "[1, 2, \"Hello\"]"
  end

  it "should return js array literal for set", :ruby => 1.9 do
    Set.new([1, 2, "Hello"]).to_js.should == "[1, 2, \"Hello\"]"
  end

  it "should return js object literal for hash", :ruby => 1.9 do
    {:a => "hello", :b => 5, "c" => "world"}.to_js.should == "{a: \"hello\", b: 5, c: \"world\"}"
  end

  it "should return js object literal for hash", :ruby => 1.8 do
    require 'active_support/ordered_hash'
    ActiveSupport::OrderedHash[
      :a, "hello", :b, 5, "c", "world"
    ].to_js.should == "{a: \"hello\", b: 5, c: \"world\"}"
  end

  it "should return to_s representation of object" do
    A.new("Hello").to_js.should == "Hello"
  end

  it "should return direct to_s representation of symbol" do
    :hello.to_js.should == "hello"
  end

  it "should return string without graves to string with graves" do
    "`Hello`".to_js.should == "Hello"
  end

  it "should return date wrapped as string" do
    Date.new(2012, 12, 21).to_js.should == "\"2012-12-21\""
  end

  it "should return time wrapped as string" do
    moment = Time.at(0)
    moment.to_js.should == "\"#{moment.to_s}\""
  end

end


text:
#pragma once

#include <common/err_common.hpp>
#include <common/dispatch.hpp>
#include <common/util.hpp>

#include <algorithm>
#include <iomanip>
#include <mutex>
#include <string>
#include <unordered_map>
#include <vector>

namespace common
{
typedef std::recursive_mutex mutex_t;
typedef std::lock_guard<mutex_t> lock_guard_t;

const unsigned MAX_BUFFERS   = 1000;
const size_t ONE_GB = 1 << 30;

template<typename T>
class MemoryManager
{
    typedef struct
    {
        bool manager_lock;
        bool user_lock;
        size_t bytes;
    } locked_info;

    using locked_t = typename std::unordered_map<void *, locked_info>;
    using locked_iter = typename locked_t::iterator;

    typedef std::unordered_map<size_t, std::vector<void *> >free_t;
    typedef free_t::iterator free_iter;

    typedef struct memory_info
    {
        locked_t locked_map;
        free_t   free_map;

        size_t lock_bytes;
        size_t lock_buffers;
        size_t total_bytes;
        size_t total_buffers;
        size_t max_bytes;

        memory_info()
        {
            // Calling getMaxMemorySize() here calls the virtual function that returns 0
            // Call it from outside the constructor.
            max_bytes     = ONE_GB;
            total_bytes   = 0;
            total_buffers = 0;
            lock_bytes    = 0;
            lock_buffers  = 0;
        }
    } memory_info;

    size_t mem_step_size;
    unsigned max_buffers;
    std::vector<memory_info> memory;
    bool debug_mode;

    memory_info& getCurrentMemoryInfo()
    {
        return memory[this->getActiveDeviceId()];
    }

    inline int getActiveDeviceId()
    {
        return static_cast<T*>(this)->getActiveDeviceId();
    }

    inline size_t getMaxMemorySize(int id)
    {
        return static_cast<T*>(this)->getMaxMemorySize(id);
    }

    void cleanDeviceMemoryManager(int device)
    {
        if (this->debug_mode) return;

        lock_guard_t lock(this->memory_mutex);
        memory_info& current = memory[device];

        // Return if all buffers are locked
        if (current.total_buffers == current.lock_buffers) return;

        for (auto &kv : current.free_map) {
            size_t num_ptrs = kv.second.size();
            //Free memory by popping the last element
            for (int n = num_ptrs-1; n >= 0; n--) {
                this->nativeFree(kv.second[n]);
                current.total_bytes -= kv.first;
                current.total_buffers--;
                kv.second.pop_back();
            }
        }
        current.free_map.clear();
    }

    public:
    MemoryManager(int num_devices, unsigned max_buffers, bool debug)
        : mem_step_size(1024), max_buffers(max_buffers), memory(num_devices), debug_mode(debug)
    {
        // Check for environment variables

        // Debug mode
        std::string env_var = getEnvVar("AF_MEM_DEBUG");
        if (!env_var.empty()) this->debug_mode = env_var[0] != '0';
        if (this->debug_mode) mem_step_size = 1;

        // Max Buffer count
        env_var = getEnvVar("AF_MAX_BUFFERS");
        if (!env_var.empty()) this->max_buffers = std::max(1, std::stoi(env_var));
    }

    // Intended to be used with OpenCL backend, where
    // users are allowed to add external devices(context, device pair)
    // to the list of devices automatically detected by the library
    void addMemoryManagement(int device)
    {
        // If there is a memory manager allocated for
        // this device id, we might as well use it and the
        // buffers allocated for it
        if (static_cast<size_t>(device) < memory.size())
            return;

        // Assuming, device need not be always the next device
        // Lets resize to current_size + device + 1
        // +1 is to account for device being 0-based index of devices
        memory.resize(memory.size()+device+1);
    }

    // Intended to be used with OpenCL backend, where
    // users are allowed to add external devices(context, device pair)
    // to the list of devices automatically detected by the library
    void removeMemoryManagement(int device)
    {
        if ((size_t)device>=memory.size())
            AF_ERROR("No matching device found", AF_ERR_ARG);

        // Do garbage collection for the device and leave
        // the memory_info struct from the memory vector intact
        cleanDeviceMemoryManager(device);
    }

    void setMaxMemorySize()
    {
        for (unsigned n = 0; n < memory.size(); n++) {
            // Calls garbage collection when:
            // total_bytes > memsize * 0.75 when memsize <  4GB
            // total_bytes > memsize - 1 GB when memsize >= 4GB
            // If memsize returned 0, then use 1GB
            size_t memsize = this->getMaxMemorySize(n);
            memory[n].max_bytes = memsize == 0 ? ONE_GB :
                std::max(memsize * 0.75, (double)(memsize - ONE_GB));
        }
    }

    void *alloc(const size_t bytes, bool user_lock)
    {
        lock_guard_t lock(this->memory_mutex);

        void *ptr = NULL;
        size_t alloc_bytes = this->debug_mode ? bytes : (divup(bytes, mem_step_size) * mem_step_size);

        if (bytes > 0) {
            memory_info& current = this->getCurrentMemoryInfo();

            // There is no memory cache in debug mode
            if (!this->debug_mode) {

                // FIXME: Add better checks for garbage collection
                // Perhaps look at total memory available as a metric
                if (this->checkMemoryLimit()) {
                    this->garbageCollect();
                }

                free_iter iter = current.free_map.find(alloc_bytes);

                if (iter != current.free_map.end() && !iter->second.empty()) {
                    ptr = iter->second.back();
                    iter->second.pop_back();
                }

            }

            // Only comes here if buffer size not found or in debug mode
            if (ptr == NULL) {
                // Perform garbage collection if memory can not be allocated
                try {
                    ptr = this->nativeAlloc(alloc_bytes);
                } catch (AfError &ex) {
                    // If out of memory, run garbage collect and try again
                    if (ex.getError() != AF_ERR_NO_MEM) throw;
                    this->garbageCollect();
                    ptr = this->nativeAlloc(alloc_bytes);
                }
                // Increment these two only when it succeeds to come here.
                current.total_bytes += alloc_bytes;
                current.total_buffers += 1;
            }

            locked_info info = {!user_lock, user_lock, alloc_bytes};
            current.locked_map[ptr] = info;
            current.lock_bytes += alloc_bytes;
            current.lock_buffers++;
        }
        return ptr;
    }

    size_t allocated(void *ptr)
    {
        if (!ptr) return 0;
        memory_info& current = this->getCurrentMemoryInfo();
        locked_iter iter = current.locked_map.find((void *)ptr);
        if (iter == current.locked_map.end()) return 0;
        return (iter->second).bytes;
    }

    void unlock(void *ptr, bool user_unlock)
    {
        // Shortcut for empty arrays
        if (!ptr) return;

        lock_guard_t lock(this->memory_mutex);
        memory_info& current = this->getCurrentMemoryInfo();

        locked_iter iter = current.locked_map.find((void *)ptr);

        // Pointer not found in locked map
        if (iter == current.locked_map.end()) {
            // Probably came from user, just free it
            this->nativeFree(ptr);
            return;
        }

        if (user_unlock) {
            (iter->second).user_lock = false;
        } else {
            (iter->second).manager_lock = false;
        }

        // Return early if either one is locked
        if ((iter->second).user_lock || (iter->second).manager_lock) return;

        size_t bytes = iter->second.bytes;
        current.lock_bytes -= iter->second.bytes;
        current.lock_buffers--;

        if (this->debug_mode) {
            // Just free memory in debug mode
            if ((iter->second).bytes > 0) {
                this->nativeFree(iter->first);
                current.total_buffers--;
                current.total_bytes -= iter->second.bytes;
            }
        } else {
            // In regular mode, move buffer to free map
            free_iter fiter = current.free_map.find(bytes);
            if (fiter != current.free_map.end()) {
                // If found, push back
                fiter->second.push_back(ptr);
            } else {
                // If not found, create new vector for this size
                std::vector<void *> ptrs;
                ptrs.push_back(ptr);
                current.free_map[bytes] = ptrs;
            }
        }

        current.locked_map.erase(iter);
    }

    void garbageCollect()
    {
        cleanDeviceMemoryManager(this->getActiveDeviceId());
    }

    void printInfo(const char *msg, const int device)
    {
        lock_guard_t lock(this->memory_mutex);
        const memory_info& current = this->getCurrentMemoryInfo();

        printf("%s\n", msg);
        printf("---------------------------------------------------------\n"
               "|     POINTER      |    SIZE    |  AF LOCK  | USER LOCK |\n"
               "---------------------------------------------------------\n");

        for(auto& kv : current.locked_map) {
            const char* status_mngr = "Yes";
            const char* status_user = "Unknown";
            if(kv.second.user_lock)     status_user = "Yes";
            else                        status_user = " No";

            const char* unit = "KB";
            double size = (double)(kv.second.bytes) / 1024;
            if(size >= 1024) {
                size = size / 1024;
                unit = "MB";
            }

            printf("|  %14p  |  %6.f %s | %9s | %9s |\n",
                   kv.first, size, unit, status_mngr, status_user);
        }

        for(auto &kv : current.free_map) {

            const char* status_mngr = "No";
            const char* status_user = "No";

            const char* unit = "KB";
            double size = (double)(kv.first) / 1024;
            if(size >= 1024) {
                size = size / 1024;
                unit = "MB";
            }

            for (auto &ptr : kv.second) {
              printf("|  %14p  |  %6.f %s | %9s | %9s |\n",
                     ptr, size, unit, status_mngr, status_user);
            }
        }

        printf("---------------------------------------------------------\n");
    }

    void bufferInfo(size_t *alloc_bytes, size_t *alloc_buffers,
                    size_t *lock_bytes,  size_t *lock_buffers)
    {
        lock_guard_t lock(this->memory_mutex);
        const memory_info& current = this->getCurrentMemoryInfo();
        if (alloc_bytes   ) *alloc_bytes   = current.total_bytes;
        if (alloc_buffers ) *alloc_buffers = current.total_buffers;
        if (lock_bytes    ) *lock_bytes    = current.lock_bytes;
        if (lock_buffers  ) *lock_buffers  = current.lock_buffers;
    }

    void userLock(const void *ptr)
    {
        memory_info& current = this->getCurrentMemoryInfo();

        lock_guard_t lock(this->memory_mutex);

        locked_iter iter = current.locked_map.find(const_cast<void *>(ptr));

        if (iter != current.locked_map.end()) {
            iter->second.user_lock = true;
        } else {
            locked_info info = {false,
                true,
                100}; //This number is not relevant

            current.locked_map[(void *)ptr] = info;
        }
    }

    void userUnlock(const void *ptr)
    {
        this->unlock(const_cast<void *>(ptr), true);
    }

    bool isUserLocked(const void *ptr)
    {
        memory_info& current = this->getCurrentMemoryInfo();
        lock_guard_t lock(this->memory_mutex);
        locked_iter iter = current.locked_map.find(const_cast<void *>(ptr));
        if (iter != current.locked_map.end()) {
            return iter->second.user_lock;
        } else {
            return false;
        }
    }

    size_t getMemStepSize()
    {
        lock_guard_t lock(this->memory_mutex);
        return this->mem_step_size;
    }

    size_t getMaxBytes()
    {
        lock_guard_t lock(this->memory_mutex);
        return this->getCurrentMemoryInfo().max_bytes;
    }

    unsigned getMaxBuffers()
    {
        return this->max_buffers;
    }

    void setMemStepSize(size_t new_step_size)
    {
        lock_guard_t lock(this->memory_mutex);
        this->mem_step_size = new_step_size;
    }

    inline void *nativeAlloc(const size_t bytes)
    {
        return static_cast<T*>(this)->nativeAlloc(bytes);
    }

    inline void nativeFree(void *ptr)
    {
        static_cast<T*>(this)->nativeFree(ptr);
    }

    virtual ~MemoryManager() {}

    bool checkMemoryLimit()
    {
        const memory_info& current = this->getCurrentMemoryInfo();
        return current.lock_bytes >= current.max_bytes || current.total_buffers >= this->max_buffers;
    }

    protected:
    mutex_t memory_mutex;
};

}


text:
<?php
/**
 * Register image sizes added by user in backend
 * included in main plugin file.
 *
 * Created by PhpStorm.
 * User: alpipego
 * Date: 26.06.2017
 * Time: 17:01
 */
add_action('after_setup_theme', function () {
    $userSizes = get_option('resizefly_user_sizes', []);
    if (! empty($userSizes)) {
        foreach ($userSizes as $size) {
            if (! is_array($size['crop']) || 2 !== count($size['crop'])) {
                $size['crop'] = (bool) $size['crop'];
            }
            add_image_size($size['name'], (int) $size['width'], (int) $size['height'], $size['crop']);
        }
    }
});


text:
@interface OEXMockPFInstallation : NSObject

@property (strong, nonatomic) NSString* deviceToken;
@property (copy, nonatomic) NSArray* channels;

@property (strong, nonatomic) NSMutableDictionary* data;

@property (assign, nonatomic) BOOL saved;

@end

@implementation OEXMockPFInstallation

- (NSString*)tokenStringWithData:(NSData*)deviceToken {
    NSCharacterSet* allowedCharacters = [NSCharacterSet alphanumericCharacterSet];
    return [deviceToken.description stringByTrimmingCharactersInSet:[allowedCharacters invertedSet]];
}

- (void)setDeviceTokenFromData:(NSData *)deviceToken {
    self.deviceToken = [self tokenStringWithData:deviceToken];
}

- (BFTask*)saveEventually {
    self.saved = YES;
    return nil;
}

- (void)setObject:(id)object forKey:(id)key {
    if(self.data == nil) {
        self.data = [[NSMutableDictionary alloc] init];
    }
    self.data[key] = object;
}

@end

@interface OEXParsePushProviderTests : XCTestCase

@property (strong, nonatomic) OEXMockPFInstallation* installation;
@property (strong, nonatomic) id <OEXRemovable> defaultsMockRemover;
@property (strong, nonatomic) OCMockObject* installationClassMock;
@property (strong, nonatomic) OEXParsePushProvider* provider;

@end

@implementation OEXParsePushProviderTests

- (void)setUp {
    self.installation = [[OEXMockPFInstallation alloc] init];
    self.installationClassMock = OCMStrictClassMock([PFInstallation class]);
    id installationStub = [self.installationClassMock stub];
    [installationStub currentInstallation];
    [installationStub andReturn:self.installation];

    OEXMockUserDefaults* defaults = [[OEXMockUserDefaults alloc] init];
    self.defaultsMockRemover = [defaults installAsStandardUserDefaults];

    self.provider = [[OEXParsePushProvider alloc] init];
}

- (void)tearDown {
    [self.defaultsMockRemover remove];
    [self.installationClassMock stopMocking];
    self.provider = nil;
}

- (void)testMock {
    XCTAssertEqualObjects(self.installation, [PFInstallation currentInstallation]);
}

- (void)testRegistration {
    char tokenBytes[] = {0x12, 0x34, 0x56, 0x78};
    NSData* tokenData = [NSData dataWithBytes:tokenBytes length:4];
    [self.provider didRegisterForRemoteNotificationsWithDeviceToken:tokenData];

    XCTAssertEqualObjects(self.installation.deviceToken, @"12345678");
    XCTAssertTrue(self.installation.saved);
    XCTAssertEqualObjects(self.installation.data[@"preferredLanguage"], [NSBundle mainBundle].oex_displayLanguage);
}

- (NSArray*)changeCourses {
    NSArray* courses = [NSArray oex_arrayWithCount:4 generator:^id(NSUInteger index) {
        return [OEXCourse freshCourseWithDiscussionsEnabled:true accessible:true];
    }];

    [[NSNotificationCenter defaultCenter]
     postNotificationName:OEXCourseListChangedNotification
     object:nil
     userInfo:@{
                OEXCourseListKey : courses
                }];

    return courses;
}

- (void)testCourseUpdateSession {
    OEXUserDetails* userDetails = [OEXUserDetails freshUser];
    OEXPushSettingsManager* settingsManager = [[OEXPushSettingsManager alloc] init];
    [self.provider sessionStartedWithUserDetails:userDetails settingsManager:settingsManager];

    NSArray* expectedChannels = [[self changeCourses] oex_map:^id(OEXCourse* course) {
        return course.subscription_id;
    }];
    XCTAssertEqualObjects([NSSet setWithArray:self.installation.channels], [NSSet setWithArray:expectedChannels]);
    XCTAssertTrue(self.installation.saved);
}

- (void)testCourseUpdateNoSession {
    OEXUserDetails* userDetails = [OEXUserDetails freshUser];
    OEXPushSettingsManager* settingsManager = [[OEXPushSettingsManager alloc] init];
    [self.provider sessionStartedWithUserDetails:userDetails settingsManager:settingsManager];
    [self changeCourses];

    self.installation.saved = NO;

    [self.provider sessionEnded];

    XCTAssertEqual(self.installation.channels.count, 0);
    XCTAssertTrue(self.installation.saved);
}

- (void)testDisabledCourseFiltered {
    OEXUserDetails* userDetails = [OEXUserDetails freshUser];
    OEXPushSettingsManager* settingsManager = [[OEXPushSettingsManager alloc] init];
    [self.provider sessionStartedWithUserDetails:userDetails settingsManager:settingsManager];
    NSArray* courses = [self changeCourses];

    OEXCourse* course = courses.firstObject;
    XCTAssertNotNil(course.subscription_id);

    [settingsManager setPushDisabled:YES forCourseID:course.course_id];

    XCTAssertFalse([self.installation.channels containsObject:course.subscription_id]);
    XCTAssertEqual(self.installation.channels.count + 1, courses.count);
}

- (void)testSignOut {
    OEXUserDetails* userDetails = [OEXUserDetails freshUser];
    OEXPushSettingsManager* settingsManager = [[OEXPushSettingsManager alloc] init];
    [self.provider sessionStartedWithUserDetails:userDetails settingsManager:settingsManager];
    [self.provider didRegisterForRemoteNotificationsWithDeviceToken:[@"token" dataUsingEncoding:NSUTF8StringEncoding]];
    [self changeCourses];

    XCTAssertNotNil(self.installation.deviceToken);
    XCTAssertGreaterThan(self.installation.channels.count, 0);

    [self.provider sessionEnded];

    XCTAssertEqual(self.installation.deviceToken.length, 0);
    XCTAssertNotNil(self.installation.deviceToken, @"Parse can't save nil objects");
    XCTAssertEqual(self.installation.channels.count, 0);
}

@end


text:
const std::string PauseState::s_pauseID = "PAUSE";

void PauseState::update()
{
    for (int i = 0; i < m_gameObjects.size(); i++)
    {
        m_gameObjects[i]->update();
    }
}

void PauseState::render()
{
    for (int i = 0; i < m_gameObjects.size(); i++)
    {
        m_gameObjects[i]->draw();
    }
}

bool PauseState::onEnter()
{
    // Parse the states file
    StateParser stateParser;
    stateParser.parseState("assets/states-config.xml", s_pauseID, &m_gameObjects, &m_textureIDList);

    m_callbacks.push_back(NULL);
    m_callbacks.push_back(s_pauseToMain);
    m_callbacks.push_back(s_resumePlay);

    setCallbacks(m_callbacks);

    std::cout << "Entering PauseState" << std::endl;
    return true;
}

bool PauseState::onExit()
{
    for (GameObject *pGameObject : m_gameObjects)
    {
        pGameObject->clean();
    }
    m_gameObjects.clear();

    // Clear the texture manager
    for (std::string textureID : m_textureIDList)
    {
        TextureManager::Instance()->clearFromTextureMap(textureID);
    }

    // reset the mouse button states to false
    InputHandler::Instance()->reset();

    std::cout << "Exiting PauseState" << std::endl;
    return true;
}

void PauseState::setCallbacks(const std::vector<Callback>& callbacks)
{
    // Go through the game objects
    for (int i = 0; i < m_gameObjects.size(); i++)
    {
        // If they are of type MenuButton, then assign a callback
        // based on the id passed in from the file
        if (dynamic_cast<MenuButton*>(m_gameObjects[i]))
        {
            MenuButton *pButton =
                dynamic_cast<MenuButton*>(m_gameObjects[i]);
            pButton->setCallback(callbacks[pButton->getCallBackID()]);
        }
    }
}

void PauseState::s_pauseToMain()
{
    Game::Instance()->getStateMachine()->changeState(new MainMenuState());
}

void PauseState::s_resumePlay()
{
    Game::Instance()->getStateMachine()->popState();
}