/**
      Copyright (C) 2005  Michael Ahlberg, Måns Rullgård

      Permission is hereby granted, free of charge, to any person
      obtaining a copy of this software and associated documentation
      files (the "Software"), to deal in the Software without
      restriction, including without limitation the rights to use, copy,
      modify, merge, publish, distribute, sublicense, and/or sell copies
      of the Software, and to permit persons to whom the Software is
      furnished to do so, subject to the following conditions:

      The above copyright notice and this permission notice shall be
      included in all copies or substantial portions of the Software.

      THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
      EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
      MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
      NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
      HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
      WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
      OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
      DEALINGS IN THE SOFTWARE.
**/

#include <stdlib.h>
#include "libavutil/avstring.h"
#include "libavutil/bswap.h"
#include "libavcodec/get_bits.h"
#include "libavcodec/bytestream.h"
#include "avformat.h"
#include "oggdec.h"

static int ogm_chapter(AVFormatContext *as, uint8_t *key, uint8_t *val)
{
    int i, cnum, h, m, s, ms, keylen = strlen(key);
    AVChapter *chapter = NULL;

    if (keylen < 9 || sscanf(key, "CHAPTER%02d", &cnum) != 1)
        return 0;

    if (keylen == 9) {
        if (sscanf(val, "%02d:%02d:%02d.%03d", &h, &m, &s, &ms) < 4)
            return 0;

        ff_new_chapter(as, cnum, (AVRational){1,1000},
                       ms + 1000*(s + 60*(m + 60*h)),
                       AV_NOPTS_VALUE, NULL);
        av_free(val);
    } else if (!strcmp(key+9, "NAME")) {
        for(i = 0; i < as->nb_chapters; i++)
            if (as->chapters[i]->id == cnum) {
                chapter = as->chapters[i];
                break;
            }
        if (!chapter)
            return 0;

        av_metadata_set2(&chapter->metadata, "title", val,
                         AV_METADATA_DONT_STRDUP_VAL);
    } else
        return 0;

    av_free(key);
    return 1;
}

int
ff_vorbis_comment(AVFormatContext * as, AVMetadata **m, const uint8_t *buf, int size)
{
    const uint8_t *p = buf;
    const uint8_t *end = buf + size;
    unsigned n, j;
    int s;

    if (size < 8) /* must have vendor_length and user_comment_list_length */
        return -1;

    s = bytestream_get_le32(&p);

    if (end - p - 4 < s || s < 0)
        return -1;

    p += s;

    n = bytestream_get_le32(&p);

    while (end - p >= 4 && n > 0) {
        const char *t, *v;
        int tl, vl;

        s = bytestream_get_le32(&p);

        if (end - p < s || s < 0)
            break;

        t = p;
        p += s;
        n--;

        v = memchr(t, '=', s);
        if (!v)
            continue;

        tl = v - t;
        vl = s - tl - 1;
        v++;

        if (tl && vl) {
            char *tt, *ct;

            tt = av_malloc(tl + 1);
            ct = av_malloc(vl + 1);
            if (!tt || !ct) {
                av_freep(&tt);
                av_freep(&ct);
                av_log(as, AV_LOG_WARNING, "out-of-memory error. skipping VorbisComment tag.\n");
                continue;
            }

            for (j = 0; j < tl; j++)
                tt[j] = toupper(t[j]);
            tt[tl] = 0;

            memcpy(ct, v, vl);
            ct[vl] = 0;

            if (!ogm_chapter(as, tt, ct))
                av_metadata_set2(m, tt, ct,
                                   AV_METADATA_DONT_STRDUP_KEY |
                                   AV_METADATA_DONT_STRDUP_VAL);
        }
    }

    if (p != end)
        av_log(as, AV_LOG_INFO, "%ti bytes of comment header remain\n", end-p);
    if (n > 0)
        av_log(as, AV_LOG_INFO,
               "truncated comment header, %i comments not found\n", n);

    return 0;
}

/** Parse the vorbis header
 * Vorbis Identification header from Vorbis_I_spec.html#vorbis-spec-codec
 * [vorbis_version] = read 32 bits as unsigned integer | Not used
 * [audio_channels] = read 8 bit integer as unsigned | Used
 * [audio_sample_rate] = read 32 bits as unsigned integer | Used
 * [bitrate_maximum] = read 32 bits as signed integer | Not used yet
 * [bitrate_nominal] = read 32 bits as signed integer | Not used yet
 * [bitrate_minimum] = read 32 bits as signed integer | Used as bitrate
 * [blocksize_0] = read 4 bits as unsigned integer | Not Used
 * [blocksize_1] = read 4 bits as unsigned integer | Not Used
 * [framing_flag] = read one bit | Not Used
 *    */

struct oggvorbis_private {
    unsigned int len[3];
    unsigned char *packet[3];
};

static unsigned int
fixup_vorbis_headers(AVFormatContext * as, struct oggvorbis_private *priv,
                     uint8_t **buf)
{
    int i,offset, len;
    unsigned char *ptr;

    len = priv->len[0] + priv->len[1] + priv->len[2];
    ptr = *buf = av_mallocz(len + len/255 + 64);

    ptr[0] = 2;
    offset = 1;
    offset += av_xiphlacing(&ptr[offset], priv->len[0]);
    offset += av_xiphlacing(&ptr[offset], priv->len[1]);
    for (i = 0; i < 3; i++) {
        memcpy(&ptr[offset], priv->packet[i], priv->len[i]);
        offset += priv->len[i];
        av_freep(&priv->packet[i]);
    }
    *buf = av_realloc(*buf, offset + FF_INPUT_BUFFER_PADDING_SIZE);
    return offset;
}

static int
vorbis_header (AVFormatContext * s, int idx)
{
    struct ogg *ogg = s->priv_data;
    struct ogg_stream *os = ogg->streams + idx;
    AVStream *st = s->streams[idx];
    struct oggvorbis_private *priv;
    int pkt_type = os->buf[os->pstart];

    if (!(pkt_type & 1))
        return 0;

    if (!os->private) {
        os->private = av_mallocz(sizeof(struct oggvorbis_private));
        if (!os->private)
            return 0;
    }

    if (os->psize < 1 || pkt_type > 5)
        return -1;

    priv = os->private;
    priv->len[pkt_type >> 1] = os->psize;
    priv->packet[pkt_type >> 1] = av_mallocz(os->psize);
    memcpy(priv->packet[pkt_type >> 1], os->buf + os->pstart, os->psize);
    if (os->buf[os->pstart] == 1) {
        const uint8_t *p = os->buf + os->pstart + 7; /* skip "\001vorbis" tag */
        unsigned blocksize, bs0, bs1;

        if (os->psize != 30)
            return -1;

        if (bytestream_get_le32(&p) != 0) /* vorbis_version */
            return -1;

        st->codec->channels = bytestream_get_byte(&p);
        st->codec->sample_rate = bytestream_get_le32(&p);
        p += 4; // skip maximum bitrate
        st->codec->bit_rate = bytestream_get_le32(&p); // nominal bitrate
        p += 4; // skip minimum bitrate

        blocksize = bytestream_get_byte(&p);
        bs0 = blocksize & 15;
        bs1 = blocksize >> 4;

        if (bs0 > bs1)
            return -1;
        if (bs0 < 6 || bs1 > 13)
            return -1;

        if (bytestream_get_byte(&p) != 1) /* framing_flag */
            return -1;

        st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
        st->codec->codec_id = CODEC_ID_VORBIS;

        st->time_base.num = 1;
        st->time_base.den = st->codec->sample_rate;
    } else if (os->buf[os->pstart] == 3) {
        if (os->psize > 8)
            ff_vorbis_comment (s, &st->metadata, os->buf + os->pstart + 7, os->psize - 8);
    } else {
        st->codec->extradata_size =
            fixup_vorbis_headers(s, priv, &st->codec->extradata);
    }

    return 1;
}

const struct ogg_codec ff_vorbis_codec = {
    .magic = "\001vorbis",
    .magicsize = 7,
    .header = vorbis_header
};

{'repo_name': 'havlenapetr/FFMpeg', 'stars': '877', 'repo_language': 'C', 'file_name': 'Android.mk', 'mime_type': 'text/plain', 'hash': 5119760717702992768, 'source_dataset': 'data'}


// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information.

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Threading;

using Microsoft.Scripting;
using Microsoft.Scripting.Actions;
using Microsoft.Scripting.Runtime;
using Microsoft.Scripting.Utils;

using IronPython.Runtime;
using IronPython.Runtime.Binding;

using MSAst = System.Linq.Expressions;

namespace IronPython.Compiler.Ast {
    using Ast = MSAst.Expression;
    using AstUtils = Microsoft.Scripting.Ast.Utils;

    public abstract class ScopeStatement : Statement {
        private bool _importStar;                   // from module import *
        private bool _unqualifiedExec;              // exec "code"
        private bool _nestedFreeVariables;          // nested function with free variable
        private bool _locals;                       // The scope needs locals dictionary
                                                    // due to "exec" or call to dir, locals, eval, vars...
        private bool _hasLateboundVarSets;          // calls code which can assign to variables
        private bool _containsExceptionHandling;    // true if this block contains a try/with statement
        private bool _forceCompile;                 // true if this scope should always be compiled

        private FunctionCode _funcCode;             // the function code object created for this scope

        private Dictionary<string, PythonVariable> _variables;          // mapping of string to variables
        private ClosureInfo[] _closureVariables;                        // closed over variables, bool indicates if we accessed it in this scope.
        private List<PythonVariable> _freeVars;                         // list of variables accessed from outer scopes
        private List<string> _globalVars;                               // global variables accessed from this scope
        private List<string> _cellVars;                                 // variables accessed from nested scopes
        private Dictionary<string, PythonReference> _references;        // names of all variables referenced, null after binding completes

        internal Dictionary<PythonVariable, MSAst.Expression> _variableMapping = new Dictionary<PythonVariable, MSAst.Expression>();
        private MSAst.ParameterExpression _localParentTuple;                                        // parent's tuple local saved locally
        private readonly DelayedFunctionCode _funcCodeExpr = new DelayedFunctionCode();             // expression that refers to the function code for this scope

        internal static MSAst.ParameterExpression LocalCodeContextVariable = Ast.Parameter(typeof(CodeContext), "$localContext");
        private static MSAst.ParameterExpression _catchException = Ast.Parameter(typeof(Exception), "$updException");
        internal const string NameForExec = "module: <exec>";

        internal bool ContainsImportStar {
            get { return _importStar; }
            set { _importStar = value; }
        }

        internal bool ContainsExceptionHandling {
            get {
                return _containsExceptionHandling;
            }
            set {
                _containsExceptionHandling = value;
            }
        }

        internal bool ContainsUnqualifiedExec {
            get { return _unqualifiedExec; }
            set { _unqualifiedExec = value; }
        }

        internal virtual bool IsGeneratorMethod {
            get {
                return false;
            }
        }

        /// <summary>
        /// The variable used to hold out parents closure tuple in our local scope.
        /// </summary>
        internal MSAst.ParameterExpression LocalParentTuple {
            get {
                return _localParentTuple;
            }
        }

        /// <summary>
        /// Gets the expression associated with the local CodeContext.  If the function
        /// doesn't have a local CodeContext then this is the global context.
        /// </summary>
        internal virtual MSAst.Expression LocalContext {
            get {
                return LocalCodeContextVariable;
            }
        }

        /// <summary>
        /// True if this scope accesses a variable from an outer scope.
        /// </summary>
        internal bool IsClosure {
            get { return FreeVariables != null && FreeVariables.Count > 0; }
        }

        /// <summary>
        /// True if an inner scope is accessing a variable defined in this scope.
        /// </summary>
        internal bool ContainsNestedFreeVariables {
            get { return _nestedFreeVariables; }
            set { _nestedFreeVariables = value; }
        }

        /// <summary>
        /// True if we are forcing the creation of a dictionary for storing locals.
        ///
        /// This occurs for calls to locals(), dir(), vars(), unqualified exec, and
        /// from ... import *.
        /// </summary>
        internal bool NeedsLocalsDictionary {
            get { return _locals; }
            set { _locals = value; }
        }

        public virtual string Name {
            get {
                return "<unknown>";
            }
        }

        internal virtual string Filename {
            get {
                return GlobalParent.SourceUnit.Path ?? "<string>";
            }
        }

        /// <summary>
        /// True if variables can be set in a late bound fashion that we don't
        /// know about at code gen time - for example via from foo import *.
        ///
        /// This is tracked independently of the ContainsUnqualifiedExec/NeedsLocalsDictionary
        /// </summary>
        internal virtual bool HasLateBoundVariableSets {
            get {
                return _hasLateboundVarSets;
            }
            set {
                _hasLateboundVarSets = value;
            }
        }

        internal Dictionary<string, PythonVariable> Variables {
            get { return _variables; }
        }

        internal virtual bool IsGlobal {
            get { return false; }
        }

        internal bool NeedsLocalContext {
            get {
                return NeedsLocalsDictionary || ContainsNestedFreeVariables;
            }
        }

        internal virtual string[] ParameterNames {
            get {
                return ArrayUtils.EmptyStrings;
            }
        }

        internal virtual int ArgCount {
            get {
                return 0;
            }
        }

        internal virtual FunctionAttributes Flags {
            get {
                return FunctionAttributes.None;
            }
        }

        internal abstract Microsoft.Scripting.Ast.LightLambdaExpression GetLambda();

        /// <summary>
        /// Gets or creates the FunctionCode object for this FunctionDefinition.
        /// </summary>
        internal FunctionCode GetOrMakeFunctionCode() {
            if (_funcCode == null) {
                Interlocked.CompareExchange(ref _funcCode, new FunctionCode(GlobalParent.PyContext, OriginalDelegate, this, ScopeDocumentation, null, true), null);
            }
            return _funcCode;
        }

        internal virtual string ScopeDocumentation {
            get {
                return null;
            }
        }

        internal virtual Delegate OriginalDelegate {
            get {
                return null;
            }
        }

        internal virtual IList<string> GetVarNames() {
            List<string> res = new List<string>();

            AppendVariables(res);

            return res;
        }

        internal void AddFreeVariable(PythonVariable variable, bool accessedInScope) {
            if (_freeVars == null) {
                _freeVars = new List<PythonVariable>();
            }

            if(!_freeVars.Contains(variable)) {
                _freeVars.Add(variable);
            }
        }

        internal bool ShouldInterpret {
            get {
                if (_forceCompile) {
                    return false;
                } else if (GlobalParent.CompilationMode == CompilationMode.Lookup) {
                    return true;
                }
                CompilerContext context = GlobalParent.CompilerContext;

                return ((PythonContext)context.SourceUnit.LanguageContext).ShouldInterpret((PythonCompilerOptions)context.Options, context.SourceUnit);
            }
            set {
                _forceCompile = !value;
            }
        }

        internal string AddReferencedGlobal(string name) {
            if (_globalVars == null) {
                _globalVars = new List<string>();
            }
            if (!_globalVars.Contains(name)) {
                _globalVars.Add(name);
            }
            return name;
        }

        internal void AddCellVariable(PythonVariable variable) {
            if (_cellVars == null) {
                _cellVars = new List<string>();
            }

            if (!_cellVars.Contains(variable.Name)) {
                _cellVars.Add(variable.Name);
            }
        }

        internal List<string> AppendVariables(List<string> res) {
            if (Variables != null) {
                foreach (var variable in Variables) {
                    if (variable.Value.Kind != VariableKind.Local) {
                        continue;
                    }

                    if (CellVariables == null || !CellVariables.Contains(variable.Key)) {
                        res.Add(variable.Key);
                    }
                }
            }
            return res;
        }

        /// <summary>
        /// Variables that are bound in an outer scope - but not a global scope
        /// </summary>
        internal IList<PythonVariable> FreeVariables {
            get {
                return _freeVars;
            }
        }

        /// <summary>
        /// Variables that are bound to the global scope
        /// </summary>
        internal IList<string> GlobalVariables {
            get {
                return _globalVars;
            }
        }

        /// <summary>
        /// Variables that are referred to from a nested scope and need to be
        /// promoted to cells.
        /// </summary>
        internal IList<string> CellVariables {
            get {
                return _cellVars;
            }
        }

        internal Type GetClosureTupleType() {
            if (TupleCells > 0) {
                Type[] args = new Type[TupleCells];
                for (int i = 0; i < TupleCells; i++) {
                    args[i] = typeof(ClosureCell);
                }
                return MutableTuple.MakeTupleType(args);
            }
            return null;
        }

        internal virtual int TupleCells {
            get {
                if (_closureVariables == null) {
                    return 0;
                }

                return _closureVariables.Length;
            }
        }

        internal abstract bool ExposesLocalVariable(PythonVariable variable);

        internal virtual MSAst.Expression GetParentClosureTuple() {
            // PythonAst will never call this.
            throw new NotSupportedException();
        }

        private bool TryGetAnyVariable(string name, out PythonVariable variable) {
            if (_variables != null) {
                return _variables.TryGetValue(name, out variable);
            } else {
                variable = null;
                return false;
            }
        }

        internal bool TryGetVariable(string name, out PythonVariable variable) {
            if (TryGetAnyVariable(name, out variable)) {
                return true;
            } else {
                variable = null;
                return false;
            }
        }

        internal virtual bool TryBindOuter(ScopeStatement from, PythonReference reference, out PythonVariable variable) {
            // Hide scope contents by default (only functions expose their locals)
            variable = null;
            return false;
        }

        internal abstract PythonVariable BindReference(PythonNameBinder binder, PythonReference reference);

        internal virtual void Bind(PythonNameBinder binder) {
            if (_references != null) {
                foreach (var reference in _references.Values) {
                    PythonVariable variable;
                    reference.PythonVariable = variable = BindReference(binder, reference);

                    // Accessing outer scope variable which is being deleted?
                    if (variable != null) {
                        if (variable.Deleted && variable.Scope != this && !variable.Scope.IsGlobal) {

                            // report syntax error
                            binder.ReportSyntaxError(
                                String.Format(
                                    System.Globalization.CultureInfo.InvariantCulture,
                                    "can not delete variable '{0}' referenced in nested scope",
                                    reference.Name
                                    ),
                                this);
                        }
                    }
                }
            }
        }

        internal virtual void FinishBind(PythonNameBinder binder) {
            List<ClosureInfo> closureVariables = null;

            if (FreeVariables != null && FreeVariables.Count > 0) {
                _localParentTuple = Ast.Parameter(Parent.GetClosureTupleType(), "$tuple");

                foreach (var variable in _freeVars) {
                    var parentClosure = Parent._closureVariables;
                    Debug.Assert(parentClosure != null);

                    for (int i = 0; i < parentClosure.Length; i++) {
                        if (parentClosure[i].Variable == variable) {
                            _variableMapping[variable] = new ClosureExpression(variable, Ast.Property(_localParentTuple, String.Format("Item{0:D3}", i)), null);
                            break;
                        }
                    }
                    Debug.Assert(_variableMapping.ContainsKey(variable));

                    if (closureVariables == null) {
                        closureVariables = new List<ClosureInfo>();
                    }
                    closureVariables.Add(new ClosureInfo(variable, !(this is ClassDefinition)));
                }
            }

            if (Variables != null) {
                foreach (PythonVariable variable in Variables.Values) {
                    if (!HasClosureVariable(closureVariables, variable) &&
                        !variable.IsGlobal && (variable.AccessedInNestedScope || ExposesLocalVariable(variable))) {
                        if (closureVariables == null) {
                            closureVariables = new List<ClosureInfo>();
                        }
                        closureVariables.Add(new ClosureInfo(variable, true));
                    }

                    if (variable.Kind == VariableKind.Local) {
                        Debug.Assert(variable.Scope == this);

                        if (variable.AccessedInNestedScope || ExposesLocalVariable(variable)) {
                            _variableMapping[variable] = new ClosureExpression(variable, Ast.Parameter(typeof(ClosureCell), variable.Name), null);
                        } else {
                            _variableMapping[variable] = Ast.Parameter(typeof(object), variable.Name);
                        }
                    }
                }
            }

            if (closureVariables != null) {
                _closureVariables = closureVariables.ToArray();
            }

            // no longer needed
            _references = null;
        }

        private static bool HasClosureVariable(List<ClosureInfo> closureVariables, PythonVariable variable) {
            if (closureVariables == null) {
                return false;
            }

            for (int i = 0; i < closureVariables.Count; i++) {
                if (closureVariables[i].Variable == variable) {
                    return true;
                }
            }

            return false;
        }

        private void EnsureVariables() {
            if (_variables == null) {
                _variables = new Dictionary<string, PythonVariable>(StringComparer.Ordinal);
            }
        }

        internal void AddGlobalVariable(PythonVariable variable) {
            EnsureVariables();
            _variables[variable.Name] = variable;
        }

        internal PythonReference Reference(string name) {
            if (_references == null) {
                _references = new Dictionary<string, PythonReference>(StringComparer.Ordinal);
            }
            PythonReference reference;
            if (!_references.TryGetValue(name, out reference)) {
                _references[name] = reference = new PythonReference(name);
            }
            return reference;
        }

        internal bool IsReferenced(string name) {
            PythonReference reference;
            return _references != null && _references.TryGetValue(name, out reference);
        }

        internal PythonVariable/*!*/ CreateVariable(string name, VariableKind kind) {
            EnsureVariables();
            Debug.Assert(!_variables.ContainsKey(name));
            PythonVariable variable;
            _variables[name] = variable = new PythonVariable(name, kind, this);
            return variable;
        }

        internal PythonVariable/*!*/ EnsureVariable(string name) {
            PythonVariable variable;
            if (!TryGetVariable(name, out variable)) {
                return CreateVariable(name, VariableKind.Local);
            }
            return variable;
        }

        internal PythonVariable DefineParameter(string name) {
            return CreateVariable(name, VariableKind.Parameter);
        }

        internal PythonContext PyContext {
            get {
                return (PythonContext)GlobalParent.CompilerContext.SourceUnit.LanguageContext;
            }
        }

        #region Debug Info Tracking

        private MSAst.SymbolDocumentInfo Document {
            get {
                return GlobalParent.Document;
            }
        }

        internal MSAst.Expression/*!*/ AddDebugInfo(MSAst.Expression/*!*/ expression, SourceLocation start, SourceLocation end) {
            if (PyContext.PythonOptions.GCStress != null) {
                expression = Ast.Block(
                    Ast.Call(
                        typeof(GC).GetMethod("Collect", new[] { typeof(int) }),
                        Ast.Constant(PyContext.PythonOptions.GCStress.Value)
                    ),
                    expression
                );
            }

            return AstUtils.AddDebugInfo(expression, Document, start, end);
        }

        internal MSAst.Expression/*!*/ AddDebugInfo(MSAst.Expression/*!*/ expression, SourceSpan location) {
            return AddDebugInfo(expression, location.Start, location.End);
        }

        internal MSAst.Expression/*!*/ AddDebugInfoAndVoid(MSAst.Expression/*!*/ expression, SourceSpan location) {
            if (expression.Type != typeof(void)) {
                expression = AstUtils.Void(expression);
            }
            return AddDebugInfo(expression, location);
        }

        #endregion

        #region Runtime Line Number Tracing

        /// <summary>
        /// Gets the expression for updating the dynamic stack trace at runtime when an
        /// exception is thrown.
        /// </summary>
        internal MSAst.Expression GetUpdateTrackbackExpression(MSAst.ParameterExpression exception) {
            if (!_containsExceptionHandling) {
                Debug.Assert(Name != null);
                Debug.Assert(exception.Type == typeof(Exception));
                return UpdateStackTrace(exception);
            }

            return GetSaveLineNumberExpression(exception, true);
        }

        private MSAst.Expression UpdateStackTrace(MSAst.ParameterExpression exception) {
            return Ast.Call(
                AstMethods.UpdateStackTrace,
                exception,
                LocalContext,
                _funcCodeExpr,
                LineNumberExpression
            );
        }

        /// <summary>
        /// Gets the expression for the actual updating of the line number for stack traces to be available
        /// </summary>
        internal MSAst.Expression GetSaveLineNumberExpression(MSAst.ParameterExpression exception, bool preventAdditionalAdds) {
            Debug.Assert(exception.Type == typeof(Exception));
            return Ast.Block(
                AstUtils.If(
                    Ast.Not(
                        LineNumberUpdated
                    ),
                    UpdateStackTrace(exception)
                ),
                Ast.Assign(
                    LineNumberUpdated,
                    AstUtils.Constant(preventAdditionalAdds)
                ),
                AstUtils.Empty()
            );
        }

        /// <summary>
        /// Wraps the body of a statement which should result in a frame being available during
        /// exception handling.  This ensures the line number is updated as the stack is unwound.
        /// </summary>
        internal MSAst.Expression/*!*/ WrapScopeStatements(MSAst.Expression/*!*/ body, bool canThrow) {
            if (canThrow) {
                body = Ast.Block(
                    new[] { LineNumberExpression, LineNumberUpdated },
                    Ast.TryCatch(
                        body,
                        Ast.Catch(
                            _catchException,
                            Ast.Block(
                                GetUpdateTrackbackExpression(_catchException),
                                Ast.Rethrow(body.Type)
                            )
                        )
                    )
                );
            }

            return body;
        }

        #endregion

        /// <summary>
        /// Provides a place holder for the expression which represents
        /// a FunctionCode.  For functions/classes this gets updated after
        /// the AST has been generated because the FunctionCode needs to
        /// know about the tree which gets generated.  For modules we
        /// immediately have the value because it always comes in as a parameter.
        /// </summary>
        class DelayedFunctionCode : MSAst.Expression {
            private MSAst.Expression _funcCode;

            public override bool CanReduce {
                get {
                    return true;
                }
            }

            public MSAst.Expression Code {
                get {
                    return _funcCode;
                }
                set {
                    _funcCode = value;
                }
            }

            public override Type Type {
                get {
                    return typeof(FunctionCode);
                }
            }

            protected override MSAst.Expression VisitChildren(MSAst.ExpressionVisitor visitor) {
                if (_funcCode != null) {
                    MSAst.Expression funcCode = visitor.Visit(_funcCode);
                    if (funcCode != _funcCode) {
                        DelayedFunctionCode res = new DelayedFunctionCode();
                        res._funcCode = funcCode;
                        return res;
                    }
                }
                return this;
            }

            public override MSAst.Expression Reduce() {
                Debug.Assert(_funcCode != null);
                return _funcCode;
            }

            public override MSAst.ExpressionType NodeType {
                get {
                    return MSAst.ExpressionType.Extension;
                }
            }
        }

        internal MSAst.Expression FuncCodeExpr {
            get {
                return _funcCodeExpr.Code;
            }
            set {
                _funcCodeExpr.Code = value;
            }
        }

        internal MSAst.MethodCallExpression CreateLocalContext(MSAst.Expression parentContext) {
            var closureVariables = _closureVariables;
            if (_closureVariables == null) {
                closureVariables = new ClosureInfo[0];
            }
            return Ast.Call(
                AstMethods.CreateLocalContext,
                parentContext,
                MutableTuple.Create(ArrayUtils.ConvertAll(closureVariables, x => GetClosureCell(x))),
                Ast.Constant(ArrayUtils.ConvertAll(closureVariables, x => x.AccessedInScope ? x.Variable.Name : null))
            );
        }

        private MSAst.Expression GetClosureCell(ClosureInfo variable) {
            return ((ClosureExpression)GetVariableExpression(variable.Variable)).ClosureCell;
        }

        internal virtual MSAst.Expression GetVariableExpression(PythonVariable variable) {
            if (variable.IsGlobal) {
                return GlobalParent.ModuleVariables[variable];
            }

            Debug.Assert(_variableMapping.ContainsKey(variable));
            return _variableMapping[variable];
        }

        internal void CreateVariables(ReadOnlyCollectionBuilder<MSAst.ParameterExpression> locals, List<MSAst.Expression> init) {
            if (Variables != null) {
                foreach (PythonVariable variable in Variables.Values) {
                    if(variable.Kind != VariableKind.Global) {
                        if (GetVariableExpression(variable) is ClosureExpression closure) {
                            init.Add(closure.Create());
                            locals.Add((MSAst.ParameterExpression)closure.ClosureCell);
                        } else if (variable.Kind == VariableKind.Local) {
                            locals.Add((MSAst.ParameterExpression)GetVariableExpression(variable));
                            if (variable.ReadBeforeInitialized) {
                                init.Add(
                                    AssignValue(
                                        GetVariableExpression(variable),
                                        MSAst.Expression.Field(null, typeof(Uninitialized).GetField("Instance"))
                                    )
                                );
                            }
                        }
                    }
                }
            }

            if (IsClosure) {
                Type tupleType = Parent.GetClosureTupleType();
                Debug.Assert(tupleType != null);

                init.Add(
                    MSAst.Expression.Assign(
                        LocalParentTuple,
                        MSAst.Expression.Convert(
                            GetParentClosureTuple(),
                            tupleType
                        )
                    )
                );

                locals.Add(LocalParentTuple);
            }
        }

        internal MSAst.Expression AddDecorators(MSAst.Expression ret, IList<Expression> decorators) {
            // add decorators
            if (decorators != null) {
                for (int i = decorators.Count - 1; i >= 0; i--) {
                    Expression decorator = decorators[i];
                    ret = Parent.Invoke(
                        new CallSignature(1),
                        Parent.LocalContext,
                        decorator,
                        ret
                    );
                }
            }
            return ret;
        }

        internal MSAst.Expression/*!*/ Invoke(CallSignature signature, params MSAst.Expression/*!*/[]/*!*/ args) {
            PythonInvokeBinder invoke = PyContext.Invoke(signature);
            switch (args.Length) {
                case 1: return GlobalParent.CompilationMode.Dynamic(invoke, typeof(object), args[0]);
                case 2: return GlobalParent.CompilationMode.Dynamic(invoke, typeof(object), args[0], args[1]);
                case 3: return GlobalParent.CompilationMode.Dynamic(invoke, typeof(object), args[0], args[1], args[2]);
                case 4: return GlobalParent.CompilationMode.Dynamic(invoke, typeof(object), args[0], args[1], args[2], args[3]);
                default:
                    return GlobalParent.CompilationMode.Dynamic(
                        invoke,
                        typeof(object),
                        args
                    );
            }
        }

        internal ScopeStatement CopyForRewrite() {
            return (ScopeStatement)MemberwiseClone();
        }

        internal virtual void RewriteBody(MSAst.ExpressionVisitor visitor) {
            _funcCode = null;
        }

        struct ClosureInfo {
            public PythonVariable Variable;
            public bool AccessedInScope;

            public ClosureInfo(PythonVariable variable, bool accessedInScope) {
                Variable = variable;
                AccessedInScope = accessedInScope;
            }
        }

        internal virtual bool PrintExpressions {
            get {
                return false;
            }
        }

        #region Profiling Support

        internal virtual string ProfilerName {
            get {
                return Name;
            }
        }

        /// <summary>
        /// Reducible node so that re-writing for profiling does not occur until
        /// after the script code has been completed and is ready to be compiled.
        ///
        /// Without this extra node profiling would force reduction of the node
        /// and we wouldn't have setup our constant access correctly yet.
        /// </summary>
        class DelayedProfiling : MSAst.Expression {
            private readonly ScopeStatement _ast;
            private readonly MSAst.Expression _body;
            private readonly MSAst.ParameterExpression _tick;

            public DelayedProfiling(ScopeStatement ast, MSAst.Expression body, MSAst.ParameterExpression tick) {
                _ast = ast;
                _body = body;
                _tick = tick;
            }

            public override bool CanReduce {
                get {
                    return true;
                }
            }

            public override Type Type {
                get {
                    return _body.Type;
                }
            }

            protected override MSAst.Expression VisitChildren(MSAst.ExpressionVisitor visitor) {
                return visitor.Visit(_body);
            }

            public override MSAst.Expression Reduce() {
                string profilerName = _ast.ProfilerName;
                bool unique = (profilerName == NameForExec);
                return Ast.Block(
                    new[] { _tick },
                    _ast.GlobalParent._profiler.AddProfiling(_body, _tick, profilerName, unique)
                );
            }

            public override MSAst.ExpressionType NodeType {
                get {
                    return MSAst.ExpressionType.Extension;
                }
            }
        }

        internal MSAst.Expression AddProfiling(MSAst.Expression/*!*/ body) {
            if (GlobalParent._profiler != null) {
                MSAst.ParameterExpression tick = Ast.Variable(typeof(long), "$tick");
                return new DelayedProfiling(this, body, tick);
            }
            return body;
        }

        #endregion
    }
}

{'repo_name': 'IronLanguages/ironpython2', 'stars': '748', 'repo_language': 'Python', 'file_name': 'interop.net.event.html', 'mime_type': 'text/html', 'hash': 2435727933684938654, 'source_dataset': 'data'}


// SPDX-License-Identifier: LGPL-3.0-or-later

import QtQuick 2.12
import "../../Base"

HCheckBox {
    text: qsTr("Encrypt messages")
    subtitle.textFormat: Text.StyledText
    subtitle.text:
        qsTr("Only you and those you trust will be able to read the " +
             "conversation") +
        `<br><font color="${theme.colors.warningText}">` +
        qsTr("Cannot be disabled later!") +
        "</font>"
}

{'repo_name': 'mirukana/mirage', 'stars': '110', 'repo_language': 'QML', 'file_name': 'mirage.desktop', 'mime_type': 'text/plain', 'hash': 5271698184636862902, 'source_dataset': 'data'}


// Ceres Solver - A fast non-linear least squares minimizer
// Copyright 2015 Google Inc. All rights reserved.
// http://ceres-solver.org/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
//   this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice,
//   this list of conditions and the following disclaimer in the documentation
//   and/or other materials provided with the distribution.
// * Neither the name of Google Inc. nor the names of its contributors may be
//   used to endorse or promote products derived from this software without
//   specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
// Author: sameeragarwal@google.com (Sameer Agarwal)
//
// Solve dense rectangular systems Ax = b using the QR factorization.
#ifndef CERES_INTERNAL_DENSE_QR_SOLVER_H_
#define CERES_INTERNAL_DENSE_QR_SOLVER_H_

#include "ceres/linear_solver.h"
#include "ceres/internal/eigen.h"
#include "ceres/internal/macros.h"

namespace ceres {
namespace internal {

class DenseSparseMatrix;

// This class implements the LinearSolver interface for solving
// rectangular/unsymmetric (well constrained) linear systems of the
// form
//
//   Ax = b
//
// Since there does not usually exist a solution that satisfies these
// equations, the solver instead solves the linear least squares
// problem
//
//   min_x |Ax - b|^2
//
// The solution strategy is based on computing the QR decomposition of
// A, i.e.
//
//   A = QR
//
// Where Q is an orthonormal matrix and R is an upper triangular
// matrix. Then
//
//     Ax = b
//    QRx = b
//  Q'QRx = Q'b
//     Rx = Q'b
//      x = R^{-1} Q'b
//
// If the PerSolveOptions struct has a non-null array D, then the
// augmented/regularized linear system
//
//   [    A    ]x = [b]
//   [ diag(D) ]    [0]
//
// is solved.
//
// This class uses the dense QR factorization routines from the Eigen
// library. This solver always returns a solution, it is the user's
// responsibility to judge if the solution is good enough for their
// purposes.
class DenseQRSolver: public DenseSparseMatrixSolver {
 public:
  explicit DenseQRSolver(const LinearSolver::Options& options);

 private:
  virtual LinearSolver::Summary SolveImpl(
      DenseSparseMatrix* A,
      const double* b,
      const LinearSolver::PerSolveOptions& per_solve_options,
      double* x);

  LinearSolver::Summary SolveUsingEigen(
      DenseSparseMatrix* A,
      const double* b,
      const LinearSolver::PerSolveOptions& per_solve_options,
      double* x);

  LinearSolver::Summary SolveUsingLAPACK(
      DenseSparseMatrix* A,
      const double* b,
      const LinearSolver::PerSolveOptions& per_solve_options,
      double* x);

  const LinearSolver::Options options_;
  ColMajorMatrix lhs_;
  Vector rhs_;
  Vector work_;
  CERES_DISALLOW_COPY_AND_ASSIGN(DenseQRSolver);
};

}  // namespace internal
}  // namespace ceres

#endif  // CERES_INTERNAL_DENSE_QR_SOLVER_H_

{'repo_name': 'openMVG/openMVG', 'stars': '2956', 'repo_language': 'C++', 'file_name': 'README.md', 'mime_type': 'text/plain', 'hash': -549613734352852185, 'source_dataset': 'data'}


//! Anthony Deschamps
//!
//!   - **Date:** November 13, 2017 (recorded October 27, 2017)
//!   - [**Audio**][mp3]
//!
//! [mp3]: https://www.podtrac.com/pts/redirect.mp3/cdn.newrustacean.com/file/newrustacean/interview/rbr/anthony_deschamps.mp3
//!
//! <audio style="width: 100%" title="Rust Belt Rust 2017: Colin Dean" controls preload=metadata>
//!   <source src="https://www.podtrac.com/pts/redirect.mp3/cdn.newrustacean.com/file/newrustacean/interview/rbr/anthony_deschamps.mp3">
//! </audio>

#[doc(include = "../docs/rbr_2017/anthony-deschamps.md")]
pub struct Transcript;

{'repo_name': 'chriskrycho/newrustacean.com', 'stars': '154', 'repo_language': 'Rust', 'file_name': 'media-playback.css', 'mime_type': 'text/plain', 'hash': -2252179143117033379, 'source_dataset': 'data'}


Higgs classification
---------------------------

You can find the full data from this here (`Link`__)

The data has been produced using Monte Carlo simulations. The first 21 features (columns 2-22) are kinematic properties measured by the particle detectors in the accelerator. The last seven features are functions of the first 21 features; these are high-level features derived by physicists to help discriminate between the two classes. There is an interest in using deep learning methods to obviate the need for physicists to manually develop such features. Benchmark results using Bayesian Decision Trees from a standard physics package and 5-layer neural networks are presented in the original paper. The last 500,000 examples are used as a test set.

.. __: https://archive.ics.uci.edu/ml/datasets/HIGGS

{'repo_name': 'aksnzhy/xlearn', 'stars': '2716', 'repo_language': 'C++', 'file_name': 'xlearn.Rd', 'mime_type': 'text/plain', 'hash': 7385267606947356542, 'source_dataset': 'data'}


<map id="vst" name="vst">
<area shape="rect" id="node4" href="dir_85853d1f2c321934b2d0b4b8cda6e5c5.html" title="adelay" alt="" coords="1111,61,1183,109"/>
<area shape="rect" id="node5" href="dir_5ffc5b65933164afb77ebc5b5eb628d9.html" title="again" alt="" coords="1015,61,1087,109"/>
<area shape="rect" id="node6" href="dir_6e70dddd8efe192a200442b707c5a654.html" title="channelcontext" alt="" coords="889,61,991,109"/>
<area shape="rect" id="node7" href="dir_25155a3fac66965a025910ca5a9dd925.html" title="common" alt="" coords="428,157,500,205"/>
<area shape="rect" id="node8" href="dir_7a4e78622845ac8e2d8be874b02fb572.html" title="hostchecker" alt="" coords="778,61,864,109"/>
<area shape="rect" id="node9" href="dir_a8e36a444327f87643906ead2e71d6f1.html" title="InterAppAudio" alt="" coords="657,61,753,109"/>
<area shape="rect" id="node10" href="dir_49976055b6bc2e03b4acc62441be6b92.html" title="mda-vst3" alt="" coords="560,61,632,109"/>
<area shape="rect" id="node11" href="dir_0140fa053d2e858593a0f7abc2b650ff.html" title="note_expression_synth" alt="" coords="392,61,536,109"/>
<area shape="rect" id="edge4-headlabel" href="dir_000007_000015.html" title="3" alt="" coords="469,132,476,146"/>
<area shape="rect" id="node12" href="dir_b39eac9c57979fc2d284d85f699e7720.html" title="pitchnames" alt="" coords="285,61,368,109"/>
<area shape="rect" id="node13" href="dir_12f6b7b17c5635ab054371ff76a5507c.html" title="prefetchablesupport" alt="" coords="134,61,260,109"/>
<area shape="rect" id="node14" href="dir_504f3f6582c88869dcb0e7c0fcff5bdc.html" title="validator" alt="" coords="37,61,109,109"/>
<area shape="rect" id="graph3" href="dir_5898a34b900eeb5b54fd3cf30212c70a.html" alt="" coords="27,51,1289,216"/>
<area shape="rect" id="graph2" href="dir_14ae8cef5b4cd5ebc5413814d7bbe8ce.html" title="samples" alt="" coords="16,16,1300,227"/>
</map>

{'repo_name': 'creativeintent/temper', 'stars': '112', 'repo_language': 'HTML', 'file_name': 'all_1.html', 'mime_type': 'text/html', 'hash': -4250810316402611243, 'source_dataset': 'data'}


<?php
/**
 *
 * PHP 5
 *
 * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
 * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
 *
 * Licensed under The MIT License
 * Redistributions of files must retain the above copyright notice.
 *
 * @copyright     Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
 * @link          http://cakephp.org CakePHP(tm) Project
 * @package       Cake.View.Errors
 * @since         CakePHP(tm) v 0.10.0.1076
 * @license       MIT License (http://www.opensource.org/licenses/mit-license.php)
 */
?>

<?php echo __d('cake_dev', 'Missing View'); ?>

	<?php echo __d('cake_dev', 'Error'); ?>:
	<?php echo __d('cake_dev', 'The view for %1$s%2$s was not found.', '' . Inflector::camelize($this->request->controller) . 'Controller::', '' . $this->request->action . '()'); ?>

	<?php echo __d('cake_dev', 'Error'); ?>:
	<?php echo __d('cake_dev', 'Confirm you have created the file: %s', $file); ?>

	<?php echo __d('cake_dev', 'Notice'); ?>:
	<?php echo __d('cake_dev', 'If you want to customize this error message, create %s', APP_DIR . DS . 'View' . DS . 'Errors' . DS . 'missing_view.ctp'); ?>

<?php echo $this->element('exception_stack_trace'); ?>

{'repo_name': 'infinitas/infinitas', 'stars': '124', 'repo_language': 'PHP', 'file_name': 'cherokee.conf', 'mime_type': 'text/plain', 'hash': 6833280654167482532, 'source_dataset': 'data'}


// Copyright 2012 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// +build !windows

package test

// Session functional tests.

import (
	"bytes"
	"errors"
	"io"
	"strings"
	"testing"

	"golang.org/x/crypto/ssh"
)

func TestRunCommandSuccess(t *testing.T) {
	server := newServer(t)
	defer server.Shutdown()
	conn := server.Dial(clientConfig())
	defer conn.Close()

	session, err := conn.NewSession()
	if err != nil {
		t.Fatalf("session failed: %v", err)
	}
	defer session.Close()
	err = session.Run("true")
	if err != nil {
		t.Fatalf("session failed: %v", err)
	}
}

func TestHostKeyCheck(t *testing.T) {
	server := newServer(t)
	defer server.Shutdown()

	conf := clientConfig()
	hostDB := hostKeyDB()
	conf.HostKeyCallback = hostDB.Check

	// change the keys.
	hostDB.keys[ssh.KeyAlgoRSA][25]++
	hostDB.keys[ssh.KeyAlgoDSA][25]++
	hostDB.keys[ssh.KeyAlgoECDSA256][25]++

	conn, err := server.TryDial(conf)
	if err == nil {
		conn.Close()
		t.Fatalf("dial should have failed.")
	} else if !strings.Contains(err.Error(), "host key mismatch") {
		t.Fatalf("'host key mismatch' not found in %v", err)
	}
}

func TestRunCommandStdin(t *testing.T) {
	server := newServer(t)
	defer server.Shutdown()
	conn := server.Dial(clientConfig())
	defer conn.Close()

	session, err := conn.NewSession()
	if err != nil {
		t.Fatalf("session failed: %v", err)
	}
	defer session.Close()

	r, w := io.Pipe()
	defer r.Close()
	defer w.Close()
	session.Stdin = r

	err = session.Run("true")
	if err != nil {
		t.Fatalf("session failed: %v", err)
	}
}

func TestRunCommandStdinError(t *testing.T) {
	server := newServer(t)
	defer server.Shutdown()
	conn := server.Dial(clientConfig())
	defer conn.Close()

	session, err := conn.NewSession()
	if err != nil {
		t.Fatalf("session failed: %v", err)
	}
	defer session.Close()

	r, w := io.Pipe()
	defer r.Close()
	session.Stdin = r
	pipeErr := errors.New("closing write end of pipe")
	w.CloseWithError(pipeErr)

	err = session.Run("true")
	if err != pipeErr {
		t.Fatalf("expected %v, found %v", pipeErr, err)
	}
}

func TestRunCommandFailed(t *testing.T) {
	server := newServer(t)
	defer server.Shutdown()
	conn := server.Dial(clientConfig())
	defer conn.Close()

	session, err := conn.NewSession()
	if err != nil {
		t.Fatalf("session failed: %v", err)
	}
	defer session.Close()
	err = session.Run(`bash -c "kill -9 $$"`)
	if err == nil {
		t.Fatalf("session succeeded: %v", err)
	}
}

func TestRunCommandWeClosed(t *testing.T) {
	server := newServer(t)
	defer server.Shutdown()
	conn := server.Dial(clientConfig())
	defer conn.Close()

	session, err := conn.NewSession()
	if err != nil {
		t.Fatalf("session failed: %v", err)
	}
	err = session.Shell()
	if err != nil {
		t.Fatalf("shell failed: %v", err)
	}
	err = session.Close()
	if err != nil {
		t.Fatalf("shell failed: %v", err)
	}
}

func TestFuncLargeRead(t *testing.T) {
	server := newServer(t)
	defer server.Shutdown()
	conn := server.Dial(clientConfig())
	defer conn.Close()

	session, err := conn.NewSession()
	if err != nil {
		t.Fatalf("unable to create new session: %s", err)
	}

	stdout, err := session.StdoutPipe()
	if err != nil {
		t.Fatalf("unable to acquire stdout pipe: %s", err)
	}

	err = session.Start("dd if=/dev/urandom bs=2048 count=1024")
	if err != nil {
		t.Fatalf("unable to execute remote command: %s", err)
	}

	buf := new(bytes.Buffer)
	n, err := io.Copy(buf, stdout)
	if err != nil {
		t.Fatalf("error reading from remote stdout: %s", err)
	}

	if n != 2048*1024 {
		t.Fatalf("Expected %d bytes but read only %d from remote command", 2048, n)
	}
}

func TestKeyChange(t *testing.T) {
	server := newServer(t)
	defer server.Shutdown()
	conf := clientConfig()
	hostDB := hostKeyDB()
	conf.HostKeyCallback = hostDB.Check
	conf.RekeyThreshold = 1024
	conn := server.Dial(conf)
	defer conn.Close()

	for i := 0; i < 4; i++ {
		session, err := conn.NewSession()
		if err != nil {
			t.Fatalf("unable to create new session: %s", err)
		}

		stdout, err := session.StdoutPipe()
		if err != nil {
			t.Fatalf("unable to acquire stdout pipe: %s", err)
		}

		err = session.Start("dd if=/dev/urandom bs=1024 count=1")
		if err != nil {
			t.Fatalf("unable to execute remote command: %s", err)
		}
		buf := new(bytes.Buffer)
		n, err := io.Copy(buf, stdout)
		if err != nil {
			t.Fatalf("error reading from remote stdout: %s", err)
		}

		want := int64(1024)
		if n != want {
			t.Fatalf("Expected %d bytes but read only %d from remote command", want, n)
		}
	}

	if changes := hostDB.checkCount; changes < 4 {
		t.Errorf("got %d key changes, want 4", changes)
	}
}

func TestInvalidTerminalMode(t *testing.T) {
	server := newServer(t)
	defer server.Shutdown()
	conn := server.Dial(clientConfig())
	defer conn.Close()

	session, err := conn.NewSession()
	if err != nil {
		t.Fatalf("session failed: %v", err)
	}
	defer session.Close()

	if err = session.RequestPty("vt100", 80, 40, ssh.TerminalModes{255: 1984}); err == nil {
		t.Fatalf("req-pty failed: successful request with invalid mode")
	}
}

func TestValidTerminalMode(t *testing.T) {
	server := newServer(t)
	defer server.Shutdown()
	conn := server.Dial(clientConfig())
	defer conn.Close()

	session, err := conn.NewSession()
	if err != nil {
		t.Fatalf("session failed: %v", err)
	}
	defer session.Close()

	stdout, err := session.StdoutPipe()
	if err != nil {
		t.Fatalf("unable to acquire stdout pipe: %s", err)
	}

	stdin, err := session.StdinPipe()
	if err != nil {
		t.Fatalf("unable to acquire stdin pipe: %s", err)
	}

	tm := ssh.TerminalModes{ssh.ECHO: 0}
	if err = session.RequestPty("xterm", 80, 40, tm); err != nil {
		t.Fatalf("req-pty failed: %s", err)
	}

	err = session.Shell()
	if err != nil {
		t.Fatalf("session failed: %s", err)
	}

	stdin.Write([]byte("stty -a && exit\n"))

	var buf bytes.Buffer
	if _, err := io.Copy(&buf, stdout); err != nil {
		t.Fatalf("reading failed: %s", err)
	}

	if sttyOutput := buf.String(); !strings.Contains(sttyOutput, "-echo ") {
		t.Fatalf("terminal mode failure: expected -echo in stty output, got %s", sttyOutput)
	}
}

func TestWindowChange(t *testing.T) {
	server := newServer(t)
	defer server.Shutdown()
	conn := server.Dial(clientConfig())
	defer conn.Close()

	session, err := conn.NewSession()
	if err != nil {
		t.Fatalf("session failed: %v", err)
	}
	defer session.Close()

	stdout, err := session.StdoutPipe()
	if err != nil {
		t.Fatalf("unable to acquire stdout pipe: %s", err)
	}

	stdin, err := session.StdinPipe()
	if err != nil {
		t.Fatalf("unable to acquire stdin pipe: %s", err)
	}

	tm := ssh.TerminalModes{ssh.ECHO: 0}
	if err = session.RequestPty("xterm", 80, 40, tm); err != nil {
		t.Fatalf("req-pty failed: %s", err)
	}

	if err := session.WindowChange(100, 100); err != nil {
		t.Fatalf("window-change failed: %s", err)
	}

	err = session.Shell()
	if err != nil {
		t.Fatalf("session failed: %s", err)
	}

	stdin.Write([]byte("stty size && exit\n"))

	var buf bytes.Buffer
	if _, err := io.Copy(&buf, stdout); err != nil {
		t.Fatalf("reading failed: %s", err)
	}

	if sttyOutput := buf.String(); !strings.Contains(sttyOutput, "100 100") {
		t.Fatalf("terminal WindowChange failure: expected \"100 100\" stty output, got %s", sttyOutput)
	}
}

func TestCiphers(t *testing.T) {
	var config ssh.Config
	config.SetDefaults()
	cipherOrder := config.Ciphers
	// These ciphers will not be tested when commented out in cipher.go it will
	// fallback to the next available as per line 292.
	cipherOrder = append(cipherOrder, "aes128-cbc", "3des-cbc")

	for _, ciph := range cipherOrder {
		server := newServer(t)
		defer server.Shutdown()
		conf := clientConfig()
		conf.Ciphers = []string{ciph}
		// Don't fail if sshd doesn't have the cipher.
		conf.Ciphers = append(conf.Ciphers, cipherOrder...)
		conn, err := server.TryDial(conf)
		if err == nil {
			conn.Close()
		} else {
			t.Fatalf("failed for cipher %q", ciph)
		}
	}
}

func TestMACs(t *testing.T) {
	var config ssh.Config
	config.SetDefaults()
	macOrder := config.MACs

	for _, mac := range macOrder {
		server := newServer(t)
		defer server.Shutdown()
		conf := clientConfig()
		conf.MACs = []string{mac}
		// Don't fail if sshd doesn't have the MAC.
		conf.MACs = append(conf.MACs, macOrder...)
		if conn, err := server.TryDial(conf); err == nil {
			conn.Close()
		} else {
			t.Fatalf("failed for MAC %q", mac)
		}
	}
}

func TestKeyExchanges(t *testing.T) {
	var config ssh.Config
	config.SetDefaults()
	kexOrder := config.KeyExchanges
	for _, kex := range kexOrder {
		server := newServer(t)
		defer server.Shutdown()
		conf := clientConfig()
		// Don't fail if sshd doesn't have the kex.
		conf.KeyExchanges = append([]string{kex}, kexOrder...)
		conn, err := server.TryDial(conf)
		if err == nil {
			conn.Close()
		} else {
			t.Errorf("failed for kex %q", kex)
		}
	}
}

func TestClientAuthAlgorithms(t *testing.T) {
	for _, key := range []string{
		"rsa",
		"dsa",
		"ecdsa",
		"ed25519",
	} {
		server := newServer(t)
		conf := clientConfig()
		conf.SetDefaults()
		conf.Auth = []ssh.AuthMethod{
			ssh.PublicKeys(testSigners[key]),
		}

		conn, err := server.TryDial(conf)
		if err == nil {
			conn.Close()
		} else {
			t.Errorf("failed for key %q", key)
		}

		server.Shutdown()
	}
}

{'repo_name': 'tjfoc/hyperledger-fabric-gm', 'stars': '134', 'repo_language': 'Go', 'file_name': 'Makefile', 'mime_type': 'text/x-makefile', 'hash': 1566585130853476648, 'source_dataset': 'data'}


# Azure AD B2C: Force password after 90 days

This solution demonstrates how to force user to reset password after 90 day or so. The solution is based on an extension attribute that stores the last time user sets the password and a comparison to the current date and time, minus specified number of days. Read here how to [configure extension attributes](https://docs.microsoft.com/en-us/azure/active-directory-b2c/active-directory-b2c-create-custom-attributes-profile-edit-custom). When a user sign-up or resets the password, the policy sets the extension attributes to the current datetime. On sign-in the policy checks whether both the extension attribute is not null and whether the current date time, minus 90 day is greater than last time user sets the password or not. If greater, it means that at least 90 days passed from the time user reset the password.

## Adding this functionality to your policy
To merge the policy with yours, you need:
1.	Add the claims in the extension policy

1.	Add the claims transformations in the extension policy

1. In the **ComparePasswordResetOnWithCurrentDateTime** claims transformation, change the value of the **timeSpanInSeconds** input parameter to the number of days in seconds you want the users to reset their password. For testing only the value is set to 80 seconds. Note: the value must be negative (starts with minus)

1. In the **AAD-UserReadUsingObjectId** technical profile, add the output claim and output claims transformation.  This technical profile reads the extension_passwordResetOn attribute from the user account, checks if the claim is null and compares the value of the extension_passwordResetOn claim with current datetime. The result of this technical profile is the **skipPasswordReset** output claim (return in the last output claims transformation) that indicates whether password reset is required or not (based on date comparison and if extension_passwordResetOn is null)

1. In **AAD-UserWriteUsingLogonEmail** and **AAD-UserWritePasswordUsingObjectId** add the input claims transformation and perssis claims. These technical profiles, set the current datetime to the extension_passwordResetOn claim and persists the data do the user account.

1.	Add the extra orchestration before the last orchestration step. This orchestration step asks the user to reset the password, saves the new password, and also sets the extension_passwordResetOn claim to current date and time. The orchestration setup will NOT run for social account and if the skipPasswordReset claim is true.

## Tests
You should run at least following acceptance tests:
- **New account** doesn't need to reset the password (skipPasswordReset: true)
- **Existing account before 90 days** doesn't need to reset the password (skipPasswordReset: true)
- **Existing account after 90 days** need to reset the password (skipPasswordReset: false)
- **Account that extension_passwordResetOn never set before**, should reset the password (skipPasswordReset: false) = pass

## Community Help and Support
Use [Stack Overflow](https://stackoverflow.com/questions/tagged/azure-ad-b2c) to get support from the community. Ask your questions on Stack Overflow first and browse existing issues to see if someone has asked your question before. Make sure that your questions or comments are tagged with [azure-ad-b2c].
If you find a bug in the sample, please raise the issue on [GitHub Issues](https://github.com/azure-ad-b2c/samples/issues).
To provide product feedback, visit the Azure Active Directory B2C [Feedback page](https://feedback.azure.com/forums/169401-azure-active-directory?category_id=160596).

> Note:  This sample policy is based on [SocialAndLocalAccounts starter pack](https://github.com/Azure-Samples/active-directory-b2c-custom-policy-starterpack/tree/master/SocialAndLocalAccounts). All changes are marked with **Demo:** comment inside the policy XML files. Make the necessary changes in the **Demo action required** sections.

{'repo_name': 'azure-ad-b2c/samples', 'stars': '154', 'repo_language': 'HTML', 'file_name': 'VSWorkspaceState.json', 'mime_type': 'text/plain', 'hash': 5107508388245350244, 'source_dataset': 'data'}


/*************************************************************************/
/*  dictionary.h                                                         */
/*************************************************************************/
/*                       This file is part of:                           */
/*                           GODOT ENGINE                                */
/*                      https://godotengine.org                          */
/*************************************************************************/
/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur.                 */
/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md).   */
/*                                                                       */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the       */
/* "Software"), to deal in the Software without restriction, including   */
/* without limitation the rights to use, copy, modify, merge, publish,   */
/* distribute, sublicense, and/or sell copies of the Software, and to    */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions:                                             */
/*                                                                       */
/* The above copyright notice and this permission notice shall be        */
/* included in all copies or substantial portions of the Software.       */
/*                                                                       */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,       */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF    */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY  */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,  */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE     */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                */
/*************************************************************************/

#ifndef GODOT_DICTIONARY_H
#define GODOT_DICTIONARY_H

#ifdef __cplusplus
extern "C" {
#endif

#include <stdint.h>

#define GODOT_DICTIONARY_SIZE sizeof(void *)

#ifndef GODOT_CORE_API_GODOT_DICTIONARY_TYPE_DEFINED
#define GODOT_CORE_API_GODOT_DICTIONARY_TYPE_DEFINED
typedef struct {
	uint8_t _dont_touch_that[GODOT_DICTIONARY_SIZE];
} godot_dictionary;
#endif

// reduce extern "C" nesting for VS2013
#ifdef __cplusplus
}
#endif

#include <gdnative/array.h>
#include <gdnative/gdnative.h>
#include <gdnative/variant.h>

#ifdef __cplusplus
extern "C" {
#endif

void GDAPI godot_dictionary_new(godot_dictionary *r_dest);
void GDAPI godot_dictionary_new_copy(godot_dictionary *r_dest, const godot_dictionary *p_src);
void GDAPI godot_dictionary_destroy(godot_dictionary *p_self);

godot_dictionary GDAPI godot_dictionary_duplicate(const godot_dictionary *p_self, const godot_bool p_deep);

godot_int GDAPI godot_dictionary_size(const godot_dictionary *p_self);

godot_bool GDAPI godot_dictionary_empty(const godot_dictionary *p_self);

void GDAPI godot_dictionary_clear(godot_dictionary *p_self);

godot_bool GDAPI godot_dictionary_has(const godot_dictionary *p_self, const godot_variant *p_key);

godot_bool GDAPI godot_dictionary_has_all(const godot_dictionary *p_self, const godot_array *p_keys);

void GDAPI godot_dictionary_erase(godot_dictionary *p_self, const godot_variant *p_key);

godot_int GDAPI godot_dictionary_hash(const godot_dictionary *p_self);

godot_array GDAPI godot_dictionary_keys(const godot_dictionary *p_self);

godot_array GDAPI godot_dictionary_values(const godot_dictionary *p_self);

godot_variant GDAPI godot_dictionary_get(const godot_dictionary *p_self, const godot_variant *p_key);
void GDAPI godot_dictionary_set(godot_dictionary *p_self, const godot_variant *p_key, const godot_variant *p_value);

godot_variant GDAPI *godot_dictionary_operator_index(godot_dictionary *p_self, const godot_variant *p_key);

const godot_variant GDAPI *godot_dictionary_operator_index_const(const godot_dictionary *p_self, const godot_variant *p_key);

godot_variant GDAPI *godot_dictionary_next(const godot_dictionary *p_self, const godot_variant *p_key);

godot_bool GDAPI godot_dictionary_operator_equal(const godot_dictionary *p_self, const godot_dictionary *p_b);

godot_string GDAPI godot_dictionary_to_json(const godot_dictionary *p_self);

// GDNative core 1.1

godot_bool GDAPI godot_dictionary_erase_with_return(godot_dictionary *p_self, const godot_variant *p_key);

godot_variant GDAPI godot_dictionary_get_with_default(const godot_dictionary *p_self, const godot_variant *p_key, const godot_variant *p_default);

#ifdef __cplusplus
}
#endif

#endif // GODOT_DICTIONARY_H

{'repo_name': 'godotengine/godot', 'stars': '31917', 'repo_language': 'C++', 'file_name': 'Skeleton3D.xml', 'mime_type': 'text/xml', 'hash': -1978262028310209179, 'source_dataset': 'data'}


//
//  MMPinView.m
//  MMPopupView
//
//  Created by Ralph Li on 9/6/15.
//  Copyright © 2015 LJC. All rights reserved.
//

#import "MMPinView.h"
#import "MMPopupItem.h"
#import "MMPopupCategory.h"
#import "MMPopupDefine.h"
#import "MMPopupWindow.h"
#import <Masonry/Masonry.h>

@interface MMPinView()

@property (nonatomic, strong) UIView      *backView;

@property (nonatomic, strong) UILabel     *lblStatus;
@property (nonatomic, strong) UILabel     *lblPhone;

@property (nonatomic, strong) UIView      *numberView;
@property (nonatomic, strong) NSArray     *numberArray;

@property (nonatomic, strong) UIButton    *btnCountDown;

@property (nonatomic, strong) UITextField *tfPin;

@property (nonatomic, strong) UIButton    *btnClose;

@property (nonatomic, assign) BOOL        pinLocked;
@property (nonatomic, strong) NSString    *pinLockValue;

@property (nonatomic, strong) NSDate      *dateCountdown;
@property (nonatomic, assign) NSUInteger  nCountdown;

@end

@implementation MMPinView

- (instancetype)init
{
    self = [super init];

    if ( self )
    {
        self.type = MMPopupTypeCustom;

        [self mas_makeConstraints:^(MASConstraintMaker *make) {
            make.size.mas_equalTo(CGSizeMake(240, 200));
        }];

        self.withKeyboard = YES;

        self.backView = [UIView new];
        [self addSubview:self.backView];
        [self.backView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(self);
        }];
        self.backView.layer.cornerRadius = 5.0f;
        self.backView.clipsToBounds = YES;
        self.backView.backgroundColor = [UIColor whiteColor];

        self.btnClose = [UIButton mm_buttonWithTarget:self action:@selector(actionClose)];
        [self.backView addSubview:self.btnClose];
        [self.btnClose mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.right.equalTo(self.backView).insets(UIEdgeInsetsMake(0, 0, 0, 5));
            make.size.mas_equalTo(CGSizeMake(40, 40));
        }];
        [self.btnClose setTitle:@"Close" forState:UIControlStateNormal];
        [self.btnClose setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        self.btnClose.titleLabel.font = [UIFont systemFontOfSize:14];

        self.lblStatus = [UILabel new];
        [self.backView addSubview:self.lblStatus];
        [self.lblStatus mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.top.right.equalTo(self.backView).insets(UIEdgeInsetsMake(0, 19, 0, 19));
            make.height.equalTo(@50);
        }];
        self.lblStatus.textColor = MMHexColor(0x333333FF);
        self.lblStatus.font = [UIFont boldSystemFontOfSize:17];
        self.lblStatus.text = @"You Pin Code";
        self.lblStatus.textAlignment = NSTextAlignmentCenter;

        UIView *split = [UIView new];
        [self.backView addSubview:split];
        [split mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.equalTo(self.backView);
            make.bottom.equalTo(self.lblStatus.mas_bottom);
            make.height.mas_equalTo(MM_SPLIT_WIDTH);
        }];

        self.lblPhone = [UILabel new];
        [self.backView addSubview:self.lblPhone];
        [self.lblPhone mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.equalTo(self.backView).insets(UIEdgeInsetsMake(0, 19, 0, 19));
            make.top.equalTo(self.lblStatus.mas_bottom).offset(10);
        }];
        self.lblPhone.numberOfLines = 0;
        self.lblPhone.textAlignment = NSTextAlignmentCenter;
        self.lblPhone.font = [UIFont systemFontOfSize:14];
        self.lblPhone.textColor = MMHexColor(0x999999FF);
        [self.lblPhone setContentCompressionResistancePriority:UILayoutPriorityFittingSizeLevel forAxis:UILayoutConstraintAxisVertical];
        [self.lblPhone setContentHuggingPriority:UILayoutPriorityRequired forAxis:UILayoutConstraintAxisVertical];
        self.lblPhone.text = @"The Code was sent to\n186 8877 8877";

        self.btnCountDown = [UIButton mm_buttonWithTarget:self action:@selector(actionResend)];
        [self.backView addSubview:self.btnCountDown];
        [self.btnCountDown mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.equalTo(self.backView).insets(UIEdgeInsetsMake(0, 19, 0, 19));
            make.bottom.equalTo(self.backView.mas_bottom).offset(-20);
        }];
        self.btnCountDown.titleLabel.textAlignment = NSTextAlignmentCenter;
        self.btnCountDown.titleLabel.font = [UIFont systemFontOfSize:12];
        [self.btnCountDown setTitleColor:MMHexColor(0x999999FF) forState:UIControlStateDisabled];
        [self.btnCountDown setTitleColor:MMHexColor(0xE76153FF) forState:UIControlStateNormal];
        [self.btnCountDown setContentCompressionResistancePriority:UILayoutPriorityFittingSizeLevel forAxis:UILayoutConstraintAxisVertical];
        [self.btnCountDown setContentHuggingPriority:UILayoutPriorityRequired forAxis:UILayoutConstraintAxisVertical];

        self.numberView = [UIView new];
        [self.backView addSubview:self.numberView];
        [self.numberView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.lessThanOrEqualTo(self.lblPhone.mas_bottom);
            make.bottom.greaterThanOrEqualTo(self.btnCountDown.mas_top);
            make.centerX.equalTo(self.backView);
            make.width.equalTo(@150);
        }];
        [self.numberView setContentHuggingPriority:UILayoutPriorityFittingSizeLevel forAxis:UILayoutConstraintAxisVertical];
        [self.numberView setContentCompressionResistancePriority:UILayoutPriorityRequired forAxis:UILayoutConstraintAxisVertical];

        self.numberArray = @[[UILabel new],[UILabel new],[UILabel new],[UILabel new]];

        for ( UILabel *label in self.numberArray )
        {
            [self.numberView addSubview:label];

            [label mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.bottom.equalTo(self.numberView);
                make.width.equalTo(@30);
            }];

            label.font = [UIFont boldSystemFontOfSize:40];
            label.textColor = MMHexColor(0xE76153FF);
            label.text = @"_";
        }
        [self.numberView mm_distributeSpacingHorizontallyWith:self.numberArray];

        self.tfPin = [UITextField new];
        [self addSubview:self.tfPin];
        self.tfPin.keyboardType = UIKeyboardTypeNumberPad;
        [self sendSubviewToBack:self.tfPin];

        [self startCountDown];
    }

    return self;
}

- (void)startCountDown
{
//    [self stopCountDown];
//
//    self.nCountdown = 30;
//
//    self.btnCountDown.enabled = NO;
//
//    [self checkCountDown];
}

- (void)stopCountDown
{
//    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(checkCountDown) object:nil];
}

- (void)checkCountDown
{
    if ( self.nCountdown == 0 )
    {
        self.btnCountDown.enabled = YES;
        [self.btnCountDown setTitle:@"Resent" forState:UIControlStateNormal];
    }
    else
    {
        NSString *text = [NSString stringWithFormat:@"Receive in %@ secs", [@(self.nCountdown) stringValue]];

        [self.btnCountDown setTitle:text forState:UIControlStateDisabled];

        --self.nCountdown;

        [self performSelector:@selector(checkCountDown) withObject:nil afterDelay:1 inModes:@[NSRunLoopCommonModes]];
    }
}

- (void)actionClose
{
    [self hide];
}

- (void)actionResend
{
    [self startCountDown];
}

- (void)showKeyboard
{
    [self.tfPin becomeFirstResponder];
}

- (void)hideKeyboard
{
    [self.tfPin resignFirstResponder];
}

@end

{'repo_name': 'adad184/MMPopupView', 'stars': '2080', 'repo_language': 'Objective-C', 'file_name': 'contents.xcworkspacedata', 'mime_type': 'text/xml', 'hash': 5545075235557474154, 'source_dataset': 'data'}


<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Pdf
 * @subpackage FileParser
 * @copyright  Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id$
 */

/** @see Zend_Pdf_FileParser_Image */
//require_once 'Zend/Pdf/FileParser/Image.php';

/**
 * Abstract base class for Image file parsers.
 *
 * @package    Zend_Pdf
 * @subpackage FileParser
 * @copyright  Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Pdf_FileParser_Image_Png extends Zend_Pdf_FileParser_Image
{
     protected $_isPNG;
     protected $_width;
     protected $_height;
     protected $_bits;
     protected $_color;
     protected $_compression;
     protected $_preFilter;
     protected $_interlacing;

     protected $_imageData;
     protected $_paletteData;
     protected $_transparencyData;

  /**** Public Interface ****/

     public function getWidth() {
          if(!$this->_isParsed) {
               $this->parse();
          }
          return $this->_width;
     }

     public function getHeight() {
          if(!$this->_isParsed) {
               $this->parse();
          }
          return $this->_width;
     }

     public function getBitDepth() {
          if(!$this->_isParsed) {
               $this->parse();
          }
          return $this->_bits;
     }

     public function getColorSpace() {
          if(!$this->_isParsed) {
               $this->parse();
          }
          return $this->_color;
     }

     public function getCompressionStrategy() {
          if(!$this->_isParsed) {
               $this->parse();
          }
          return $this->_compression;
     }

     public function getPaethFilter() {
          if(!$this->_isParsed) {
               $this->parse();
          }
          return $this->_preFilter;
     }

     public function getInterlacingMode() {
          if(!$this->_isParsed) {
               $this->parse();
          }
          return $this->_interlacing;
     }

     public function getRawImageData() {
          if(!$this->_isParsed) {
               $this->parse();
          }
          return $this->_imageData;
     }

     public function getRawPaletteData() {
          if(!$this->_isParsed) {
               $this->parse();
          }
          return $this->_paletteData;
     }

     public function getRawTransparencyData() {
          if(!$this->_isParsed) {
               $this->parse();
          }
          return $this->_transparencyData;
     }

  /* Semi-Concrete Class Implementation */

    /**
     * Verifies that the image file is in the expected format.
     *
     * @throws Zend_Pdf_Exception
     */
    public function screen()
    {
         if ($this->_isScreened) {
             return;
         }
         return $this->_checkSignature();
    }

    /**
     * Reads and parses the image data from the file on disk.
     *
     * @throws Zend_Pdf_Exception
     */
    public function parse()
    {
        if ($this->_isParsed) {
            return;
        }

        /* Screen the font file first, if it hasn't been done yet.
        */
        $this->screen();

        $this->_parseIHDRChunk();
        $this->_parseChunks();
    }

    protected function _parseSignature() {
         $this->moveToOffset(1); //Skip the first byte (%)
         if('PNG' != $this->readBytes(3)) {
               $this->_isPNG = false;
         } else {
               $this->_isPNG = true;
         }
    }

    protected function _checkSignature() {
         if(!isset($this->_isPNG)) {
              $this->_parseSignature();
         }
         return $this->_isPNG;
    }

    protected function _parseChunks() {
         $this->moveToOffset(33); //Variable chunks start at the end of IHDR

         //Start processing chunks. If there are no more bytes to read parsing is complete.
         $size = $this->getSize();
         while($size - $this->getOffset() >= 8) {
              $chunkLength = $this->readUInt(4);
              if($chunkLength < 0 || ($chunkLength + $this->getOffset() + 4) > $size) {
                   //require_once 'Zend/Pdf/Exception.php';
                   throw new Zend_Pdf_Exception("PNG Corrupt: Invalid Chunk Size In File.");
              }

              $chunkType = $this->readBytes(4);
              $offset = $this->getOffset();

              //If we know how to process the chunk, do it here, else ignore the chunk and move on to the next
              switch($chunkType) {
                   case 'IDAT': // This chunk may appear more than once. It contains the actual image data.
                       $this->_parseIDATChunk($offset, $chunkLength);
                       break;

                   case 'PLTE': // This chunk contains the image palette.
                       $this->_parsePLTEChunk($offset, $chunkLength);
                       break;

                   case 'tRNS': // This chunk contains non-alpha channel transparency data
                       $this->_parseTRNSChunk($offset, $chunkLength);
                       break;

                   case 'IEND':
                       break 2; //End the loop too

                   //@TODO Implement the rest of the PNG chunks. (There are many not implemented here)
              }
              if($offset + $chunkLength + 4 < $size) {
                  $this->moveToOffset($offset + $chunkLength + 4); //Skip past the data finalizer. (Don't rely on the parse to leave the offsets correct)
              }
         }
         if(empty($this->_imageData)) {
              //require_once 'Zend/Pdf/Exception.php';
              throw new Zend_Pdf_Exception ( "This PNG is corrupt. All png must contain IDAT chunks." );
         }
    }

    protected function _parseIHDRChunk() {
         $this->moveToOffset(12); //IHDR must always start at offset 12 and run for 17 bytes
         if(!$this->readBytes(4) == 'IHDR') {
              //require_once 'Zend/Pdf/Exception.php';
              throw new Zend_Pdf_Exception( "This PNG is corrupt. The first chunk in a PNG file must be IHDR." );
         }
         $this->_width = $this->readUInt(4);
         $this->_height = $this->readUInt(4);
         $this->_bits = $this->readInt(1);
         $this->_color = $this->readInt(1);
         $this->_compression = $this->readInt(1);
         $this->_preFilter = $this->readInt(1);
         $this->_interlacing = $this->readInt(1);
         if($this->_interlacing != Zend_Pdf_Image::PNG_INTERLACING_DISABLED) {
              //require_once 'Zend/Pdf/Exception.php';
              throw new Zend_Pdf_Exception( "Only non-interlaced images are currently supported." );
         }
    }

    protected function _parseIDATChunk($chunkOffset, $chunkLength) {
         $this->moveToOffset($chunkOffset);
         if(!isset($this->_imageData)) {
              $this->_imageData = $this->readBytes($chunkLength);
         } else {
              $this->_imageData .= $this->readBytes($chunkLength);
         }
    }

    protected function _parsePLTEChunk($chunkOffset, $chunkLength) {
         $this->moveToOffset($chunkOffset);
         $this->_paletteData = $this->readBytes($chunkLength);
    }

    protected function _parseTRNSChunk($chunkOffset, $chunkLength) {
         $this->moveToOffset($chunkOffset);

         //Processing of tRNS data varies dependending on the color depth

         switch($this->_color) {
             case Zend_Pdf_Image::PNG_CHANNEL_GRAY:
                  $baseColor = $this->readInt(1);
                  $this->_transparencyData = array($baseColor, $baseColor);
                  break;

             case Zend_Pdf_Image::PNG_CHANNEL_RGB:

                  //@TODO Fix this hack.
                  //This parser cheats and only uses the lsb's (and only works with < 16 bit depth images)

                  /*
                       From the standard:

                       For color type 2 (truecolor), the tRNS chunk contains a single RGB color value, stored in the format:

                       Red:   2 bytes, range 0 .. (2^bitdepth)-1
                       Green: 2 bytes, range 0 .. (2^bitdepth)-1
                       Blue:  2 bytes, range 0 .. (2^bitdepth)-1

                       (If the image bit depth is less than 16, the least significant bits are used and the others are 0.)
                       Pixels of the specified color value are to be treated as transparent (equivalent to alpha value 0);
                       all other pixels are to be treated as fully opaque (alpha value 2bitdepth-1).

                  */

                  $red = $this->readInt(1);
                  $this->skipBytes(1);
                  $green = $this->readInt(1);
                  $this->skipBytes(1);
                  $blue = $this->readInt(1);

                  $this->_transparencyData = array($red, $red, $green, $green, $blue, $blue);

                  break;

             case Zend_Pdf_Image::PNG_CHANNEL_INDEXED:

                  //@TODO Fix this hack.
                  //This parser cheats too. It only masks the first color in the palette.

                  /*
                       From the standard:

                       For color type 3 (indexed color), the tRNS chunk contains a series of one-byte alpha values, corresponding to entries in the PLTE chunk:

                          Alpha for palette index 0:  1 byte
                          Alpha for palette index 1:  1 byte
                          ...etc...

                       Each entry indicates that pixels of the corresponding palette index must be treated as having the specified alpha value.
                       Alpha values have the same interpretation as in an 8-bit full alpha channel: 0 is fully transparent, 255 is fully opaque,
                       regardless of image bit depth. The tRNS chunk must not contain more alpha values than there are palette entries,
                       but tRNS can contain fewer values than there are palette entries. In this case, the alpha value for all remaining palette
                       entries is assumed to be 255. In the common case in which only palette index 0 need be made transparent, only a one-byte
                       tRNS chunk is needed.

                  */

                  $tmpData = $this->readBytes($chunkLength);
                  if(($trnsIdx = strpos($tmpData, "\0")) !== false) {
                       $this->_transparencyData = array($trnsIdx, $trnsIdx);
                  }

                  break;

             case Zend_Pdf_Image::PNG_CHANNEL_GRAY_ALPHA:
                  //Fall through to the next case
             case Zend_Pdf_Image::PNG_CHANNEL_RGB_ALPHA:
                  //require_once 'Zend/Pdf/Exception.php';
                  throw new Zend_Pdf_Exception( "tRNS chunk illegal for Alpha Channel Images" );
                  break;
         }
    }
}

{'repo_name': 'wecenter/wecenter', 'stars': '901', 'repo_language': 'PHP', 'file_name': 'aws_offical_external.php', 'mime_type': 'text/x-php', 'hash': -2472035983388363047, 'source_dataset': 'data'}


const fs = require('fs').promises;

fs.readFile('./readme.txt')
  .then((data) => {
    console.log(data);
    console.log(data.toString());
  })
  .catch((err) => {
    console.error(err);
  });

{'repo_name': 'ZeroCho/nodejs-book', 'stars': '269', 'repo_language': 'JavaScript', 'file_name': 'layout.html', 'mime_type': 'text/html', 'hash': 2656098258814150649, 'source_dataset': 'data'}


#pragma once

#include <cstddef>

template<typename T, size_t Size>
class RingBuffer {
public:
    inline size_t size() const { return Size; }

    inline bool empty() const { return _read == _write; }

    inline bool full() const { return writable() == 0; }

    inline size_t entries() const { return (_write - _read) % Size; }

    inline size_t writable() const {
        return (_read - _write - 1) % Size;
    }

    inline size_t readable() const {
        return (_write - _read) % Size;
    }

    inline void write(T value) {
        size_t write = _write;
        _buffer[write] = value;
        _write = (write + 1) % Size;
    }

    inline void write(const T *data, size_t length) {
        while (length--) {
            write(*data++);
        }
    }

    inline T read() {
        size_t read = _read;
        T value = _buffer[read];
        _read = (read + 1) % Size;
        return value;
    }

    inline void read(T *data, size_t length) {
        while (length--) {
            read(*data++);
        }
    }

private:
    T _buffer[Size];
    volatile size_t _read = 0;
    volatile size_t _write = 0;
};

{'repo_name': 'westlicht/performer', 'stars': '106', 'repo_language': 'C', 'file_name': 'FindSDL2_image.cmake', 'mime_type': 'text/plain', 'hash': -8125389746921420121, 'source_dataset': 'data'}


module Eye::Cli::Commands

private

  def client
    @client ||= Eye::Client.new(Eye::Local.socket_path)
  end

  def _cmd(cmd, *args)
    client.execute(command: cmd, args: args)
  rescue Errno::ECONNREFUSED, Errno::ENOENT
    :not_started
  end

  def cmd(cmd, *args)
    res = _cmd(cmd, *args)

    if res == :not_started
      error! "socket(#{Eye::Local.socket_path}) not found, did you run `eye load`?"
    elsif res == :timeouted
      error! 'eye timed out without responding...'
    end

    res
  end

  def say_load_result(res = {}, opts = {})
    error!(res) unless res.is_a?(Hash)
    say_filename = (res.size > 1)
    error = false
    res.each do |filename, res2|
      say "#{filename}: ", nil, true if say_filename
      show_load_message(res2, opts)
      error = true if res2[:error]
    end

    exit(1) if error
  end

  def show_load_message(res, opts = {})
    if res[:error]
      say res[:message], :red
      res[:backtrace].to_a.each { |line| say line, :red }
    else
      unless res[:empty]
        say(opts[:syntax] ? 'Config ok!' : 'Config loaded!', :green)
      end

      if opts[:print_config]
        require 'pp'
        PP.pp res[:config], STDOUT, 150
      end
    end
  end

  def send_command(command, *args)
    res = cmd(command, *args)
    if res == :unknown_command
      error! "unknown command :#{command}"
    elsif res == :corrupted_data
      error! 'something crazy wrong, check eye logs!'
    elsif res.is_a?(Hash)
      if res[:error]
        error! "Error: #{res[:error]}"
      elsif res = res[:result]
        if res == []
          error! "command :#{command}, objects not found!"
        else
          say "command :#{command} sent to [#{res * ', '}]"
        end
      end
    else
      error! "unknown result #{res.inspect}"
    end
  end

end

{'repo_name': 'kostya/eye', 'stars': '1160', 'repo_language': 'Ruby', 'file_name': 'status.rb', 'mime_type': 'text/x-ruby', 'hash': -688243033448021627, 'source_dataset': 'data'}


fileFormatVersion: 2
guid: b804088948820194cbda76af39c08174
timeCreated: 1529972058
licenseType: Free
DefaultImporter:
  userData:
  assetBundleName:
  assetBundleVariant:

{'repo_name': 'EsotericSoftware/spine-runtimes', 'stars': '2640', 'repo_language': 'JavaScript', 'file_name': 'AssemblyInfo.cs', 'mime_type': 'text/plain', 'hash': -7233544834340956709, 'source_dataset': 'data'}


# Protocol Buffers for Go with Gadgets

[![Build Status](https://travis-ci.org/gogo/protobuf.svg?branch=master)](https://travis-ci.org/gogo/protobuf)
[![GoDoc](https://godoc.org/github.com/gogo/protobuf?status.svg)](http://godoc.org/github.com/gogo/protobuf)

gogoprotobuf is a fork of golang/protobuf with extra code generation features.

This code generation is used to achieve:

  - fast marshalling and unmarshalling
  - more canonical Go structures
  - goprotobuf compatibility
  - less typing by optionally generating extra helper code
  - peace of mind by optionally generating test and benchmark code
  - other serialization formats

Keeping track of how up to date gogoprotobuf is relative to golang/protobuf is done in this
issue

## Release v1.3.0

The project has updated to release v1.3.0. Check out the release notes here.

With this new release comes a new internal library version. This means any newly generated *pb.go files generated with the v1.3.0 library will not be compatible with the old library version (v1.2.1). However, current *pb.go files (generated with v1.2.1) should still work with the new library.

Please make sure you manage your dependencies correctly when upgrading your project. If you are still using v1.2.1 and you update your dependencies, one of which could include a new *pb.go (generated with v1.3.0), you could get a compile time error.

Our upstream repo, golang/protobuf, also had to go through this process in order to update their library version.
Here is a link explaining hermetic builds.

## Users

These projects use gogoprotobuf:

  - etcd - blog - sample proto file
  - spacemonkey - blog
  - badoo - sample proto file
  - mesos-go - sample proto file
  - heka - the switch from golang/protobuf to gogo/protobuf when it was still on code.google.com
  - cockroachdb - sample proto file
  - go-ipfs - sample proto file
  - rkive-go - sample proto file
  - dropbox
  - srclib - sample proto file
  - adyoulike
  - cloudfoundry - sample proto file
  - kubernetes - go2idl built on top of gogoprotobuf
  - dgraph - release notes - benchmarks
  - centrifugo - release notes - blog
  - docker swarmkit - sample proto file
  - nats.io - go-nats-streaming
  - tidb - Communication between tidb and tikv
  - protoactor-go - vanity command that also generates actors from service definitions
  - containerd - vanity command with custom field names that conforms to the golang convention.
  - nakama
  - proteus
  - carbonzipper stack
  - sendgrid
  - zero-os/0-stor
  - go-spacemesh
  - cortex - sample proto file
  - Apache SkyWalking APM - Istio telemetry receiver based on Mixer bypass protocol
  - Hyperledger Burrow - a permissioned DLT framework
  - IOV Weave - a blockchain framework - sample proto files

Please let us know if you are using gogoprotobuf by posting on our GoogleGroup.

### Mentioned

  - Cloudflare - go serialization talk - Albert Strasheim
  - GopherCon 2014 Writing High Performance Databases in Go by Ben Johnson
  - alecthomas' go serialization benchmarks
  - Go faster with gogoproto - Agniva De Sarker
  - Evolution of protobuf (Gource Visualization) - Landon Wilkins
  - Creating GopherJS Apps with gRPC-Web - Johan Brandhorst
  - So you want to use GoGo Protobuf - Johan Brandhorst
  - Advanced gRPC Error Usage - Johan Brandhorst
  - gRPC Golang Course on Udemy - Stephane Maarek

## Getting Started

There are several ways to use gogoprotobuf, but for all you need to install go and protoc.
After that you can choose:

  - Speed
  - More Speed and more generated code
  - Most Speed and most customization

### Installation

To install it, you must first have Go (at least version 1.6.3 or 1.9 if you are using gRPC) installed (see [http://golang.org/doc/install](http://golang.org/doc/install)).
Latest patch versions of 1.10 and 1.11 are continuously tested.

Next, install the standard protocol buffer implementation from [https://github.com/google/protobuf](https://github.com/google/protobuf).
Most versions from 2.3.1 should not give any problems, but 2.6.1, 3.0.2 and 3.6.1 are continuously tested.

### Speed

Install the protoc-gen-gofast binary

    go get github.com/gogo/protobuf/protoc-gen-gofast

Use it to generate faster marshaling and unmarshaling go code for your protocol buffers.

    protoc --gofast_out=. myproto.proto

This does not allow you to use any of the other gogoprotobuf [extensions](https://github.com/gogo/protobuf/blob/master/extensions.md).

### More Speed and more generated code

Fields without pointers cause less time in the garbage collector.
More code generation results in more convenient methods.

Other binaries are also included:

    protoc-gen-gogofast (same as gofast, but imports gogoprotobuf)
    protoc-gen-gogofaster (same as gogofast, without XXX_unrecognized, less pointer fields)
    protoc-gen-gogoslick (same as gogofaster, but with generated string, gostring and equal methods)

Installing any of these binaries is easy.  Simply run:

    go get github.com/gogo/protobuf/proto
    go get github.com/gogo/protobuf/{binary}
    go get github.com/gogo/protobuf/gogoproto

These binaries allow you to use gogoprotobuf [extensions](https://github.com/gogo/protobuf/blob/master/extensions.md). You can also use your own binary.

To generate the code, you also need to set the include path properly.

    protoc -I=. -I=$GOPATH/src -I=$GOPATH/src/github.com/gogo/protobuf/protobuf --{binary}_out=. myproto.proto

To use proto files from "google/protobuf" you need to add additional args to protoc.

    protoc -I=. -I=$GOPATH/src -I=$GOPATH/src/github.com/gogo/protobuf/protobuf --{binary}_out=\
    Mgoogle/protobuf/any.proto=github.com/gogo/protobuf/types,\
    Mgoogle/protobuf/duration.proto=github.com/gogo/protobuf/types,\
    Mgoogle/protobuf/struct.proto=github.com/gogo/protobuf/types,\
    Mgoogle/protobuf/timestamp.proto=github.com/gogo/protobuf/types,\
    Mgoogle/protobuf/wrappers.proto=github.com/gogo/protobuf/types:. \
    myproto.proto

Note that in the protoc command, {binary} does not contain the initial prefix of "protoc-gen".

### Most Speed and most customization

Customizing the fields of the messages to be the fields that you actually want to use removes the need to copy between the structs you use and structs you use to serialize.
gogoprotobuf also offers more serialization formats and generation of tests and even more methods.

Please visit the [extensions](https://github.com/gogo/protobuf/blob/master/extensions.md) page for more documentation.

Install protoc-gen-gogo:

    go get github.com/gogo/protobuf/proto
    go get github.com/gogo/protobuf/jsonpb
    go get github.com/gogo/protobuf/protoc-gen-gogo
    go get github.com/gogo/protobuf/gogoproto

## GRPC

It works the same as golang/protobuf, simply specify the plugin.
Here is an example using gofast:

    protoc --gofast_out=plugins=grpc:. my.proto

See [https://github.com/gogo/grpc-example](https://github.com/gogo/grpc-example) for an example of using gRPC with gogoprotobuf and the wider grpc-ecosystem.

## License
This software is licensed under the 3-Clause BSD License
("BSD License 2.0", "Revised BSD License", "New BSD License", or "Modified BSD License").

{'repo_name': 'docker/cli', 'stars': '2265', 'repo_language': 'Go', 'file_name': 'docker_windows.go', 'mime_type': 'text/plain', 'hash': -3441137602413724568, 'source_dataset': 'data'}