text:
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using Microsoft.DotNet.Cli;
using Microsoft.DotNet.Cli.Compiler.Common;
using Microsoft.DotNet.Cli.Utils;
using Microsoft.DotNet.ProjectModel;
using Microsoft.DotNet.ProjectModel.Compilation;
using Microsoft.Extensions.DependencyModel;
using NuGet.Frameworks;
using Microsoft.DotNet.ProjectModel.Graph;

namespace Microsoft.DotNet.Tools.Compiler
{
    public class ManagedCompiler : Compiler
    {
        private readonly IScriptRunner _scriptRunner;
        private readonly ICommandFactory _commandFactory;

        public ManagedCompiler(IScriptRunner scriptRunner, ICommandFactory commandFactory)
        {
            _scriptRunner = scriptRunner;
            _commandFactory = commandFactory;
        }

        public override bool Compile(ProjectContext context, BuildCommandApp args)
        {
            // Set up Output Paths
            var outputPaths = context.GetOutputPaths(args.ConfigValue, args.BuildBasePathValue);
            var outputPath = outputPaths.CompilationOutputPath;
            var intermediateOutputPath = outputPaths.IntermediateOutputDirectoryPath;

            Directory.CreateDirectory(outputPath);
            Directory.CreateDirectory(intermediateOutputPath);

            // Create the library exporter
            var exporter = context.CreateExporter(args.ConfigValue, args.BuildBasePathValue);

            // Gather exports for the project
            var dependencies = exporter.GetDependencies().ToList();

            Reporter.Output.WriteLine($"Compiling {context.RootProject.Identity.Name.Yellow()} for {context.TargetFramework.DotNetFrameworkName.Yellow()}");
            var sw = Stopwatch.StartNew();

            var diagnostics = new List<DiagnosticMessage>();
            var missingFrameworkDiagnostics = new List<DiagnosticMessage>();

            // Collect dependency diagnostics
            foreach (var diag in context.LibraryManager.GetAllDiagnostics())
            {
                if (diag.ErrorCode == ErrorCodes.DOTNET1011 ||
                    diag.ErrorCode == ErrorCodes.DOTNET1012)
                {
                    missingFrameworkDiagnostics.Add(diag);
                }

                diagnostics.Add(diag);
            }

            if(diagnostics.Any(d => d.Severity == DiagnosticMessageSeverity.Error))
            {
                // We got an unresolved dependency or missing framework. Don't continue the compilation.
                PrintSummary(diagnostics, sw);
                return false;
            }

            // Get compilation options
            var outputName = outputPaths.CompilationFiles.Assembly;

            // Assemble args
            var compilerArgs = new List<string>()
            {
                $"--temp-output:{intermediateOutputPath}",
                $"--out:{outputName}"
            };

            var compilationOptions = context.ResolveCompilationOptions(args.ConfigValue);

            // Set default platform if it isn't already set and we're on desktop
            if (compilationOptions.EmitEntryPoint == true && string.IsNullOrEmpty(compilationOptions.Platform) && context.TargetFramework.IsDesktop())
            {
                // See https://github.com/dotnet/cli/issues/2428 for more details.
                compilationOptions.Platform = RuntimeInformation.ProcessArchitecture == Architecture.X64 ?
                    "x64" : "anycpu32bitpreferred";
            }

            var languageId = CompilerUtil.ResolveLanguageId(context);

            var references = new List<string>();

            // Add compilation options to the args
            compilerArgs.AddRange(compilationOptions.SerializeToArgs());

            // Add metadata options
            compilerArgs.AddRange(AssemblyInfoOptions.SerializeToArgs(AssemblyInfoOptions.CreateForProject(context)));

            foreach (var dependency in dependencies)
            {
                references.AddRange(dependency.CompilationAssemblies.Select(r => r.ResolvedPath));

                compilerArgs.AddRange(dependency.SourceReferences.Select(s => s.GetTransformedFile(intermediateOutputPath)));

                foreach (var resourceFile in dependency.EmbeddedResources)
                {
                    var transformedResource = resourceFile.GetTransformedFile(intermediateOutputPath);
                    var resourceName = ResourceManifestName.CreateManifestName(
                        Path.GetFileName(resourceFile.ResolvedPath), compilationOptions.OutputName);
                    compilerArgs.Add($"--resource:\"{transformedResource}\",{resourceName}");
                }

                // Add analyzer references
                compilerArgs.AddRange(dependency.AnalyzerReferences
                    .Where(a => a.AnalyzerLanguage == languageId)
                    .Select(a => $"--analyzer:{a.AssemblyPath}"));
            }

            compilerArgs.AddRange(references.Select(r => $"--reference:{r}"));

            if (compilationOptions.PreserveCompilationContext == true)
            {
                var allExports = exporter.GetAllExports().ToList();
                var exportsLookup = allExports.ToDictionary(e => e.Library.Identity.Name);
                var buildExclusionList = context.GetTypeBuildExclusionList(exportsLookup);
                var filteredExports = allExports
                    .Where(e => e.Library.Identity.Type.Equals(LibraryType.ReferenceAssembly) ||
                        !buildExclusionList.Contains(e.Library.Identity.Name));

                var dependencyContext = new DependencyContextBuilder().Build(compilationOptions,
                    filteredExports,
                    filteredExports,
                    false, // For now, just assume non-portable mode in the legacy deps file (this is going away soon anyway)
                    context.TargetFramework,
                    context.RuntimeIdentifier ?? string.Empty);

                var writer = new DependencyContextWriter();
                var depsJsonFile = Path.Combine(intermediateOutputPath, compilationOptions.OutputName + "dotnet-compile.deps.json");
                using (var fileStream = File.Create(depsJsonFile))
                {
                    writer.Write(dependencyContext, fileStream);
                }

                compilerArgs.Add($"--resource:\"{depsJsonFile}\",{compilationOptions.OutputName}.deps.json");
            }

            if (!AddNonCultureResources(context.ProjectFile, compilerArgs, intermediateOutputPath, compilationOptions))
            {
                return false;
            }
            // Add project source files
            var sourceFiles = CompilerUtil.GetCompilationSources(context, compilationOptions);
            compilerArgs.AddRange(sourceFiles);

            var compilerName = compilationOptions.CompilerName;

            // Write RSP file
            var rsp = Path.Combine(intermediateOutputPath, $"dotnet-compile.rsp");
            File.WriteAllLines(rsp, compilerArgs);

            // Run pre-compile event
            var contextVariables = new Dictionary<string, string>()
            {
                { "compile:TargetFramework", context.TargetFramework.GetShortFolderName() },
                { "compile:FullTargetFramework", context.TargetFramework.DotNetFrameworkName },
                { "compile:Configuration", args.ConfigValue },
                { "compile:OutputFile", outputName },
                { "compile:OutputDir", outputPath.TrimEnd('\\', '/') },
                { "compile:ResponseFile", rsp }
            };

            if (context.ProjectFile.HasRuntimeOutput(args.ConfigValue))
            {
                var runtimeContext = args.Workspace.GetRuntimeContext(context, args.GetRuntimes());
                var runtimeOutputPath = runtimeContext.GetOutputPaths(args.ConfigValue, args.BuildBasePathValue, args.OutputValue);

                contextVariables.Add(
                    "compile:RuntimeOutputDir",
                    runtimeOutputPath.RuntimeOutputPath.TrimEnd('\\', '/'));

                contextVariables.Add(
                    "compile:RuntimeIdentifier",
                    runtimeContext.RuntimeIdentifier);
            }

            _scriptRunner.RunScripts(context, ScriptNames.PreCompile, contextVariables);

            // Cache the reporters before invoking the command in case it is a built-in command, which replaces
            // the static Reporter instances.
            Reporter errorReporter = Reporter.Error;
            Reporter outputReporter = Reporter.Output;

            CommandResult result = _commandFactory.Create($"compile-{compilerName}", new[] { $"@{rsp}" })
                .WorkingDirectory(context.ProjectDirectory)
                .OnErrorLine(line => HandleCompilerOutputLine(line, context, diagnostics, errorReporter))
                .OnOutputLine(line => HandleCompilerOutputLine(line, context, diagnostics, outputReporter))
                .Execute();

            // Run post-compile event
            contextVariables["compile:CompilerExitCode"] = result.ExitCode.ToString();
            _scriptRunner.RunScripts(context, ScriptNames.PostCompile, contextVariables);

            var success = result.ExitCode == 0;

            if (!success)
            {
                Reporter.Error.WriteLine($"{result.StartInfo.FileName} {result.StartInfo.Arguments} returned Exit Code {result.ExitCode}");
            }

            if (success)
            {
                success &= GenerateCultureResourceAssemblies(context.ProjectFile, dependencies, outputPath, compilationOptions);
            }

            return PrintSummary(diagnostics, sw, success);
        }

        private static void HandleCompilerOutputLine(string line, ProjectContext context, List<DiagnosticMessage> diagnostics, Reporter reporter)
        {
            var diagnostic = ParseDiagnostic(context.ProjectDirectory, line);
            if (diagnostic != null)
            {
                diagnostics.Add(diagnostic);
            }
            else
            {
                reporter.WriteLine(line);
            }
        }
    }
}


text:
import csv
import datetime

import requests

r = requests.get('http://metrics.unguku.com/metrics/stats.timers.nori.metrickeep.metrics.post.median')
metrics = r.json()

data = []
timestamps = range(metrics['start'], metrics['stop']+1, metrics['step'])
for ts, value in zip(timestamps, metrics['values']):
    clock_time = datetime.datetime.fromtimestamp(ts)
    human_time = clock_time.strftime("%H:%M:%S")
    data.append({'Time': human_time, 'Value': value})

with open('metrics.csv','wb') as f:
    writer = csv.DictWriter(f, fieldnames=['Time', 'Value'])
    writer.writeheader()
    writer.writerows(data)

redpajama_set_name: RedPajamaGithub


text:
import { round } from 'app/shared/util/utils';

export class TutorIssue {
    constructor(
        public tutorId: number,
        public tutorName: string,
        public numberOfTutorItems: number,
        public averageTutorValue: number,
        public allowedRange: Range,
        public translationKey: string,
    ) {}
}

/**
 * Represents the inclusive range with a lower and upper bound
 */
export class Range {
    constructor(public lowerBound: number, public upperBound: number) {}
}

/**
 * `TutorValueChecker` is an abstract class that wraps the verification logic whether or not the tutor value surpasses the allowed range.
 */
abstract class TutorValueChecker {
    constructor(public numberOfTutorItems: number, public averageTutorValue: number, public averageCourseValue: number, public tutorName: string, public tutorId: number) {
        this.averageTutorValue = round(this.averageTutorValue, 1);
    }

    /**
     * Checks if the tutor value is within an allowed range.
     */
    get isPerformanceIssue(): boolean {
        // If there are no 'items', then do not perform the check
        if (this.numberOfTutorItems === 0) {
            return false;
        }

        const isWithinBounds = this.allowedRange.lowerBound <= this.averageTutorValue && this.averageTutorValue <= this.allowedRange.upperBound;
        return !isWithinBounds;
    }

    /**
     * What is the allowed threshold for the tutor value.
     * By default it's average course value -/+ 20%
     */
    get allowedRange(): Range {
        const twentyPercent = this.averageCourseValue / 5;
        return new Range(round(this.averageCourseValue - twentyPercent, 1), round(this.averageCourseValue + twentyPercent, 1));
    }

    /**
     * The key to use in case of the translation.
     */
    abstract get translationKey(): string;

    /**
     * Creates tutor issue object out of the validation information.
     */
    toIssue(): TutorIssue {
        return new TutorIssue(this.tutorId, this.tutorName, this.numberOfTutorItems, this.averageTutorValue, this.allowedRange, this.translationKey);
    }
}

/**
 * `TutorValueChecker` for rating.
 */
export class TutorIssueRatingChecker extends TutorValueChecker {
    // Tutor average rating should be greater or equal to 3. Maximum rating is 5.
    static readonly MIN_RATING = 3;
    static readonly MAX_RATING = 5;

    get allowedRange(): Range {
        return new Range(TutorIssueRatingChecker.MIN_RATING, TutorIssueRatingChecker.MAX_RATING);
    }

    get translationKey(): string {
        return 'artemisApp.assessmentDashboard.tutorPerformanceIssues.ratings';
    }
}

/**
 * `TutorValueChecker` for score.
 */
export class TutorIssueScoreChecker extends TutorValueChecker {
    get translationKey(): string {
        return 'artemisApp.assessmentDashboard.tutorPerformanceIssues.score';
    }
}

/**
 * `TutorValueChecker` for complaints.
 */
export class TutorIssueComplaintsChecker extends TutorValueChecker {
    get allowedRange(): Range {
        // Tutor complaint ratio should be less than average course complaint ratio + 20%
        const twentyPercent = this.averageCourseValue / 5;
        return new Range(0, round(this.averageCourseValue + twentyPercent, 1));
    }

    get translationKey(): string {
        return 'artemisApp.assessmentDashboard.tutorPerformanceIssues.complaints';
    }
}


text:
using Chess.Framework;
using System;

namespace Chess.Representation
{
    /// <summary>
    /// A move decribes two points in the game world.
    /// </summary>
    public struct Move : IEquatable<Move>
    {
        /// <summary>
        /// Gets the coordinates of the origin point of this move.
        /// </summary>
        public Vector2 From { get { return _from; } }

        /// <summary>
        /// Gets the coordinates of the end point of this move.
        /// </summary>
        public Vector2 To { get { return _to; } }

        /// <summary>
        ///
        /// </summary>
        /// <param name="from"></param>
        /// <param name="to"></param>
        public Move(Vector2 from, Vector2 to)
        {
            _from = from;
            _to = to;
        }

        /// <summary>
        /// Compares this move to a second move.
        /// </summary>
        /// <param name="other">The second move.</param>
        /// <returns>True if both vectors are equal, false otherwise.</returns>
        public bool Equals(Move other)
        {
            return From.Equals(other.From) && To.Equals(other.To);
        }

        /// <summary>
        /// The coordinates of the end point of this move.
        /// </summary>
        private Vector2 _from;

        /// <summary>
        /// The coordinates of the end point of this move.
        /// </summary>
        private Vector2 _to;
    }
}


text:
"""Initial_schema

Revision ID: 722b06c8ce2e
Revises:
Create Date: 2017-04-18 00:01:34.407801

"""
from alembic import op
import sqlalchemy as sa

# revision identifiers, used by Alembic.
revision = '722b06c8ce2e'
down_revision = None
branch_labels = None
depends_on = None

def upgrade():

    op.create_table('users',
        sa.Column('id', sa.Integer(), nullable=False),
        sa.Column('login', sa.String(length=255), nullable=False),
        sa.Column('first_name', sa.String(length=255), nullable=False),
        sa.Column('family_name', sa.String(length=255), nullable=False),
        sa.Column('email', sa.String(length=255), nullable=False),
        sa.Column('pwd_hash', sa.String(length=255), nullable=False),
        sa.Column('is_admin', sa.Boolean(), nullable=False),
        sa.Column('is_active', sa.Boolean(), nullable=False),
        sa.Column('created_at', sa.DateTime(), nullable=True),
        sa.Column('updated_at', sa.DateTime(), nullable=True),
        sa.Column('deactivated_at', sa.DateTime(), nullable=True),
        sa.Column('reactivated_at', sa.DateTime(), nullable=True),
        sa.Column('first_login_at', sa.DateTime(), nullable=True),
        sa.Column('last_login_at', sa.DateTime(), nullable=True),
        sa.PrimaryKeyConstraint('id')
    )

    op.execute("""
        insert into users (id, login, email, first_name, family_name, pwd_hash, is_admin, is_active,created_at,updated_at,first_login_at,last_login_at)
        values(169, 'login169', 'user169@a.net', 'Adam','Anderson','pwd169', False, True ,'2017-02-24 10:01:05.88313','2017-02-26 10:01:01.88313','2017-02-24 10:01:05.88313','2017-02-27 10:01:05.88313');

        insert into users (id, login, email, first_name, family_name, pwd_hash, is_admin, is_active, created_at,updated_at,first_login_at,last_login_at)
        values(221, 'login221', 'user221@a.net', 'John','Smith','pwd221', True, True,'2016-02-24 10:01:05.88313','2016-02-26 10:01:01.88313','2016-02-24 10:01:05.88313','2016-02-27 10:01:05.88313');

    """)

def downgrade():
    pass


text:
package com.google.common.css.compiler.ast;

import com.google.common.collect.ImmutableList;
import com.google.common.css.SourceCode;

import java.util.List;

/**
 * A wrapper around the JavaCC generated GSS parser.
 *
 */
public class GssParser {

  private final List<SourceCode> sources;

  public GssParser(List<SourceCode> sources) {
    this.sources = sources;
  }

  public GssParser(SourceCode source) {
    this(ImmutableList.of(source));
  }

  public CssTree parse() throws GssParserException {
    SourceCode globalSourceCode = new SourceCode("global", null);
    CssBlockNode globalBlock =
        new CssBlockNode(false /* isEnclosedWithBraces */);
    CssTree tree = new CssTree(globalSourceCode, new CssRootNode(globalBlock));
    for (SourceCode source : sources) {
      new GssParserCC(globalBlock, source).parse();
    }
    return tree;
  }
}


text:
class UIBackShader : public UIBackground {
public:

    UIBackShader();
    UIBackShader(string _name);
    virtual ~UIBackShader(){};

    virtual bool load(string _name);
    virtual string  getClassName();

    virtual void draw();

protected:
    virtual void setupUI();
    virtual void guiEvent(ofxUIEventArgs &e);

	virtual void update(ofEventArgs & args);
    virtual void windowResized(ofResizeEventArgs & args);

    void    checkShaderFile();
    bool    reloadShader(string _fragPath);
    void    extractUniforms(string _shaderCode);
    void    addUniform(UniformType _type, string _name);

    std::time_t getLastModified( ofFile& _file );
    int     lastTimeCheckMillis;
    int     millisBetweenFileCheck;

    //  Mesh
    //
    ofMesh  mesh;
    bool    bMeshReady;

    //  FragShader
    //
    ofFile      fragFile;
    string      fragFilename;
    std::time_t fragChangedTimes;

    string      fragmentShader;

    ofShader    shader;

    vector<Uniform*>    uniforms;
    bool                bOpen;
};


text:
@interface XMLReader : NSObject<NSXMLParserDelegate>

@property (nonatomic, retain) NSMutableArray *dictionaryStack;
@property (nonatomic, retain) NSMutableString *textInProgress;

@end

@implementation XMLReader

+ (NSDictionary *)dictionaryForXMLData:(NSData *)data {
    XMLReader *reader = [[XMLReader alloc] init];
    NSDictionary *rootDictionary = [reader objectWithData:data];
    return rootDictionary;
}

- (NSDictionary *)objectWithData:(NSData *)data {
    _dictionaryStack = [[NSMutableArray alloc] init];
    _textInProgress = [[NSMutableString alloc] init];
    [_dictionaryStack addObject:[NSMutableDictionary dictionary]];
    NSXMLParser *parser = [[NSXMLParser alloc] initWithData:data];
    parser.delegate = self;
    BOOL success = [parser parse];
    return (success) ? _dictionaryStack[0] : nil;
}

- (void)parser:(NSXMLParser *)parser
didStartElement:(NSString *)elementName
  namespaceURI:(NSString *)namespaceURI
 qualifiedName:(NSString *)qName
    attributes:(NSDictionary *)attributeDict {
    NSMutableDictionary *parentDict = [_dictionaryStack lastObject];
    NSMutableDictionary *childDict = [NSMutableDictionary dictionary];
    [childDict addEntriesFromDictionary:attributeDict];
    id existingValue = parentDict[elementName];
    if (existingValue) {
        NSMutableArray *array = nil;
        if ([existingValue isKindOfClass:[NSMutableArray class]]) {
            array = (NSMutableArray *)existingValue;
        } else {
            array = [NSMutableArray array];
            [array addObject:existingValue];
            parentDict[elementName] = array;
        }
        [array addObject:childDict];
    } else {
        parentDict[elementName] = childDict;
    }
    [_dictionaryStack addObject:childDict];
}

- (void)parser:(NSXMLParser *)parser
 didEndElement:(NSString *)elementName
  namespaceURI:(NSString *)namespaceURI
 qualifiedName:(NSString *)qName {
    NSMutableDictionary *dictInProgress = [_dictionaryStack lastObject];
    if ([_textInProgress length] > 0) {
        [dictInProgress setObject:_textInProgress forKey:@"text"];
        _textInProgress = [[NSMutableString alloc] init];
    }
    [_dictionaryStack removeLastObject];
}

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
    NSString *trimmed = [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    if (trimmed.length > 0) {
        [_textInProgress appendString:string];
    }
}

- (void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError {
    // do nothing
}

@end

@implementation NSDictionary (Helpers)

+ (NSDictionary *)dictionaryFromXML:(NSData *)xml {
    return [XMLReader dictionaryForXMLData:xml];
}

- (NSString *)asQuery {
    NSMutableArray *pairs = [NSMutableArray array];
    for (NSString *key in self) {
        NSString *sanitizedKey = [key URLEncode];
        id value = self[key];
        NSString *string = [[NSString stringWithFormat:@"%@", value] URLEncode];
        [pairs addObject:[NSString stringWithFormat:@"%@=%@", sanitizedKey, string]];
    }
    return [pairs componentsJoinedByString:@"&"];
}

- (BOOL)matches:(NSDictionary *)pattern error:(NSError *__autoreleasing *)error {
    return [self compare:self to:pattern error:error];
}

- (BOOL)compare:(id)source to:(id)pattern error:(NSError *__autoreleasing *)error {
    BOOL result = YES;
    if (([source isKindOfClass:[NSDictionary class]]) && ([pattern isKindOfClass:[NSDictionary class]])) {
        // inception, we have to go deeper >_<
        NSArray *keys = [pattern allKeys];
        for (NSInteger i = 0; (i < keys.count) && (result); i++) {
            id key = keys[i];
            id sourceValue = [source objectForKey:key];
            if (sourceValue) {
                id patternValue = [pattern objectForKey:key];
                result = [self compare:sourceValue to:patternValue error:error];
            } else {
                result = NO;
            }
        }
    } else if (([source isKindOfClass:[NSArray class]]) && ([pattern isKindOfClass:[NSArray class]])) {
        // match array elements
        if ([source count] == [pattern count]) {
            for (NSInteger i = 0; (i < [source count]) && ((! error) || (! *error)); i++) {
                result = [self compare:source[i] to:pattern[i] error:error];
            }
        } else {
            result = NO;
        }
    } else if (([source isKindOfClass:[NSNumber class]]) && ([pattern isKindOfClass:[NSArray class]])) {
        // texas range(r)
        NSArray *array = (NSArray *)pattern;
        if (array.count == 2) {
            BOOL leftConcrete = (array[0] != [NSNull null]);
            BOOL rightConcrete = (array[1] != [NSNull null]);
            if ((leftConcrete) && (! [array[0] isKindOfClass:[NSNumber class]])) {
                if (error) {
                    *error = [AIQError errorWithCode:AIQErrorInvalidArgument message:[NSString stringWithFormat:@"Invalid range: %@", [array JSONString]]];
                }
                result = NO;
            } else if ((rightConcrete) && (! [array[1] isKindOfClass:[NSNumber class]])) {
                if (error) {
                    *error = [AIQError errorWithCode:AIQErrorInvalidArgument message:[NSString stringWithFormat:@"Invalid range: %@", [array JSONString]]];
                }
                result = NO;
            } else {
                if (leftConcrete) {
                    NSComparisonResult comparisonResult = [(NSNumber *)source compare:(NSNumber *)array[0]];
                    result = (comparisonResult == NSOrderedSame) || (comparisonResult == NSOrderedDescending);
                }
                if ((result) && (rightConcrete)) {
                    NSComparisonResult comparisonResult = [(NSNumber *)source compare:(NSNumber *)array[1]];
                    result = (comparisonResult == NSOrderedSame) || (comparisonResult == NSOrderedAscending);
                }
            }

        } else {
            if (error) {
                *error = [AIQError errorWithCode:AIQErrorInvalidArgument message:[NSString stringWithFormat:@"Invalid range: %@", [array JSONString]]];
            }
            result = NO;
        }
    } else if (([source isKindOfClass:[NSNumber class]]) && ([pattern isKindOfClass:[NSNumber class]])) {
        // two numbers, ohai floating points!
        result = [(NSNumber *)source isEqualToNumber:(NSNumber *)pattern];
    } else {
        // two objects reduced to strings
        regex_t regex;
        int errcode = regcomp(&regex, [[pattern description] cStringUsingEncoding:NSUTF8StringEncoding], REG_EXTENDED);
        if (errcode) {
            // invalid regular expression
            if (error) {
                *error = [AIQError errorWithCode:AIQErrorInvalidArgument message:[self stringFromRegexError:errcode forRegex:regex]];
            }
            result = NO;
        } else {
            errcode = regexec(&regex, [[source description] cStringUsingEncoding:NSUTF8StringEncoding], 0, NULL, 0);
            if (errcode) {
                result = NO;
                // invalid regular expression
                if (errcode != REG_NOMATCH) {
                    if (error) {
                        *error = [AIQError errorWithCode:AIQErrorInvalidArgument message:[self stringFromRegexError:errcode forRegex:regex]];
                    }
                }
            }
        }
        regfree(&regex);
    }
    return result;
}

- (NSString *)stringFromRegexError:(int)error forRegex:(regex_t)regex {
    char *errbuf;
    size_t errbuf_size;
    errbuf_size = regerror(error, &regex, NULL, 0);
    if (! (errbuf = (char *)malloc(errbuf_size))) {
        perror("malloc error!");
        exit(255);
    };
    regerror(error, &regex, errbuf, errbuf_size);
    NSString *result = @(errbuf);
    free(errbuf);
    return result;
}

@end


text:
' Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

Imports System.Composition
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.CodeFixes
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax

Namespace Microsoft.ApiDesignGuidelines.Analyzers
    ''' <summary>
    ''' CA1028: Enum Storage should be Int32
    ''' </summary>
    <ExportCodeFixProvider(LanguageNames.VisualBasic), [Shared]>
    Public NotInheritable Class BasicEnumStorageShouldBeInt32Fixer
        Inherits EnumStorageShouldBeInt32Fixer

        Protected Overrides Function GetTargetNode(node As SyntaxNode) As SyntaxNode
            Dim enumDecl = DirectCast(node, EnumBlockSyntax).EnumStatement
            Dim asClause = DirectCast(enumDecl.UnderlyingType, SimpleAsClauseSyntax)
            Return asClause
        End Function
    End Class
End Namespace


text:
require 'spec_helper'

describe BambooService, :use_clean_rails_memory_store_caching do
  include ReactiveCachingHelpers

  let(:bamboo_url) { 'http://gitlab.com/bamboo' }

  subject(:service) do
    described_class.create(
      project: create(:project),
      properties: {
        bamboo_url: bamboo_url,
        username: 'mic',
        password: 'password',
        build_key: 'foo'
      }
    )
  end

  describe 'Associations' do
    it { is_expected.to belong_to :project }
    it { is_expected.to have_one :service_hook }
  end

  describe 'Validations' do
    context 'when service is active' do
      before do
        subject.active = true
      end

      it { is_expected.to validate_presence_of(:build_key) }
      it { is_expected.to validate_presence_of(:bamboo_url) }
      it_behaves_like 'issue tracker service URL attribute', :bamboo_url

      describe '#username' do
        it 'does not validate the presence of username if password is nil' do
          subject.password = nil

          expect(subject).not_to validate_presence_of(:username)
        end

        it 'validates the presence of username if password is present' do
          subject.password = 'secret'

          expect(subject).to validate_presence_of(:username)
        end
      end

      describe '#password' do
        it 'does not validate the presence of password if username is nil' do
          subject.username = nil

          expect(subject).not_to validate_presence_of(:password)
        end

        it 'validates the presence of password if username is present' do
          subject.username = 'john'

          expect(subject).to validate_presence_of(:password)
        end
      end
    end

    context 'when service is inactive' do
      before do
        subject.active = false
      end

      it { is_expected.not_to validate_presence_of(:build_key) }
      it { is_expected.not_to validate_presence_of(:bamboo_url) }
      it { is_expected.not_to validate_presence_of(:username) }
      it { is_expected.not_to validate_presence_of(:password) }
    end
  end

  describe 'Callbacks' do
    describe 'before_update :reset_password' do
      context 'when a password was previously set' do
        it 'resets password if url changed' do
          bamboo_service = service

          bamboo_service.bamboo_url = 'http://gitlab1.com'
          bamboo_service.save

          expect(bamboo_service.password).to be_nil
        end

        it 'does not reset password if username changed' do
          bamboo_service = service

          bamboo_service.username = 'some_name'
          bamboo_service.save

          expect(bamboo_service.password).to eq('password')
        end

        it "does not reset password if new url is set together with password, even if it's the same password" do
          bamboo_service = service

          bamboo_service.bamboo_url = 'http://gitlab_edited.com'
          bamboo_service.password = 'password'
          bamboo_service.save

          expect(bamboo_service.password).to eq('password')
          expect(bamboo_service.bamboo_url).to eq('http://gitlab_edited.com')
        end
      end

      it 'saves password if new url is set together with password when no password was previously set' do
        bamboo_service = service
        bamboo_service.password = nil

        bamboo_service.bamboo_url = 'http://gitlab_edited.com'
        bamboo_service.password = 'password'
        bamboo_service.save

        expect(bamboo_service.password).to eq('password')
        expect(bamboo_service.bamboo_url).to eq('http://gitlab_edited.com')
      end
    end
  end

  describe '#execute' do
    it 'runs update and build action' do
      stub_update_and_build_request

      subject.execute(Gitlab::DataBuilder::Push::SAMPLE_DATA)
    end
  end

  describe '#build_page' do
    it 'returns the contents of the reactive cache' do
      stub_reactive_cache(service, { build_page: 'foo' }, 'sha', 'ref')

      expect(service.build_page('sha', 'ref')).to eq('foo')
    end
  end

  describe '#commit_status' do
    it 'returns the contents of the reactive cache' do
      stub_reactive_cache(service, { commit_status: 'foo' }, 'sha', 'ref')

      expect(service.commit_status('sha', 'ref')).to eq('foo')
    end
  end

  describe '#calculate_reactive_cache' do
    context '#build_page' do
      subject { service.calculate_reactive_cache('123', 'unused')[:build_page] }

      it 'returns a specific URL when status is 500' do
        stub_request(status: 500)

        is_expected.to eq('http://gitlab.com/bamboo/browse/foo')
      end

      it 'returns a specific URL when response has no results' do
        stub_request(body: bamboo_response(size: 0))

        is_expected.to eq('http://gitlab.com/bamboo/browse/foo')
      end

      it 'returns a build URL when bamboo_url has no trailing slash' do
        stub_request(body: bamboo_response)

        is_expected.to eq('http://gitlab.com/bamboo/browse/42')
      end

      context 'bamboo_url has trailing slash' do
        let(:bamboo_url) { 'http://gitlab.com/bamboo/' }

        it 'returns a build URL' do
          stub_request(body: bamboo_response)

          is_expected.to eq('http://gitlab.com/bamboo/browse/42')
        end
      end
    end

    context '#commit_status' do
      subject { service.calculate_reactive_cache('123', 'unused')[:commit_status] }

      it 'sets commit status to :error when status is 500' do
        stub_request(status: 500)

        is_expected.to eq(:error)
      end

      it 'sets commit status to "pending" when status is 404' do
        stub_request(status: 404)

        is_expected.to eq('pending')
      end

      it 'sets commit status to "pending" when response has no results' do
        stub_request(body: %q({"results":{"results":{"size":"0"}}}))

        is_expected.to eq('pending')
      end

      it 'sets commit status to "success" when build state contains Success' do
        stub_request(body: bamboo_response(build_state: 'YAY Success!'))

        is_expected.to eq('success')
      end

      it 'sets commit status to "failed" when build state contains Failed' do
        stub_request(body: bamboo_response(build_state: 'NO Failed!'))

        is_expected.to eq('failed')
      end

      it 'sets commit status to "pending" when build state contains Pending' do
        stub_request(body: bamboo_response(build_state: 'NO Pending!'))

        is_expected.to eq('pending')
      end

      it 'sets commit status to :error when build state is unknown' do
        stub_request(body: bamboo_response(build_state: 'FOO BAR!'))

        is_expected.to eq(:error)
      end
    end
  end

  def stub_update_and_build_request(status: 200, body: nil)
    bamboo_full_url = 'http://gitlab.com/bamboo/updateAndBuild.action?buildKey=foo&os_authType=basic'

    stub_bamboo_request(bamboo_full_url, status, body)
  end

  def stub_request(status: 200, body: nil)
    bamboo_full_url = 'http://gitlab.com/bamboo/rest/api/latest/result/byChangeset/123?os_authType=basic'

    stub_bamboo_request(bamboo_full_url, status, body)
  end

  def stub_bamboo_request(url, status, body)
    WebMock.stub_request(:get, url).to_return(
      status: status,
      headers: { 'Content-Type' => 'application/json' },
      body: body
    ).with(basic_auth: %w(mic password))
  end

  def bamboo_response(result_key: 42, build_state: 'success', size: 1)
    %Q({"results":{"results":{"size":"#{size}","result":{"buildState":"#{build_state}","planResultKey":{"key":"#{result_key}"}}}}})
  end
end


text:
package checkpoint

import (
	"fmt"
	"text/tabwriter"

	"golang.org/x/net/context"

	"github.com/docker/docker/cli"
	"github.com/docker/docker/cli/command"
	"github.com/spf13/cobra"
)

func newListCommand(dockerCli *command.DockerCli) *cobra.Command {
	return &cobra.Command{
		Use:     "ls CONTAINER",
		Aliases: []string{"list"},
		Short:   "List checkpoints for a container",
		Args:    cli.ExactArgs(1),
		RunE: func(cmd *cobra.Command, args []string) error {
			return runList(dockerCli, args[0])
		},
	}
}

func runList(dockerCli *command.DockerCli, container string) error {
	client := dockerCli.Client()

	checkpoints, err := client.CheckpointList(context.Background(), container)
	if err != nil {
		return err
	}

	w := tabwriter.NewWriter(dockerCli.Out(), 20, 1, 3, ' ', 0)
	fmt.Fprintf(w, "CHECKPOINT NAME")
	fmt.Fprintf(w, "\n")

	for _, checkpoint := range checkpoints {
		fmt.Fprintf(w, "%s\t", checkpoint.Name)
		fmt.Fprint(w, "\n")
	}

	w.Flush()
	return nil
}


text:
package com.ait.toolkit.sencha.touch.client.core;

import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.GWT.UncaughtExceptionHandler;
import com.google.gwt.core.client.JavaScriptObject;

public abstract class InitHandler {

    final JavaScriptObject jsoPeer = createPeer(this);

    private static native JavaScriptObject createPeer(InitHandler listener) /*-{
		return function() {
			listener.@com.ait.toolkit.sencha.touch.client.core.InitHandler::onInit()();
		};
    }-*/;

    protected abstract void onInit();

    // Called from JSNI
    private final void fireOnEvent() {
        UncaughtExceptionHandler handler = GWT.getUncaughtExceptionHandler();
        if (handler != null) {
            fireOnEventAndCatch(handler);
        } else {
            onInit();
        }
    }

    private void fireOnEventAndCatch(UncaughtExceptionHandler handler) {
        try {
            onInit();
        } catch (Throwable e) {
            handler.onUncaughtException(e);
        }
    }

    public JavaScriptObject getJsoPeer() {
        return jsoPeer;
    }

}


text:
namespace zz {
namespace arm {

void CodeGen::LiteralLdrBranch(uint32_t address) {
  TurboAssembler *turbo_assembler_ = reinterpret_cast<TurboAssembler *>(this->assembler_);
#define _ turbo_assembler_->
  _ ldr(pc, MemOperand(pc, -4));
  turbo_assembler_->GetCodeBuffer()->Emit32((addr_t)address);
}

} // namespace arm
} // namespace zz

#endif


text:
// Copyright 2017, Dell EMC, Inc.
/* jshint node:true */

'use strict';

describe(require('path').basename(__filename), function () {
    var base = require('./base-tasks-spec');

    base.before(function (context) {
        context.taskdefinition = helper.require('/lib/task-data/tasks/dell-wsman-update-firmware.js');
    });

    describe('task-data', function () {
        base.examples();
    });

});


text:
<?xml version="1.0" encoding="UTF-8"?><module codename="org.netbeans.modules.xml.catalog/2">
    <module_version install_time="1416338990279" last="true" origin="installer" specification_version="1.37.1.4">
        <file crc="4257896318" name="config/Modules/org-netbeans-modules-xml-catalog.xml"/>
        <file crc="173574465" name="modules/locale/org-netbeans-modules-xml-catalog_ja.jar"/>
        <file crc="327306633" name="modules/locale/org-netbeans-modules-xml-catalog_pt_BR.jar"/>
        <file crc="2046767181" name="modules/locale/org-netbeans-modules-xml-catalog_ru.jar"/>
        <file crc="3045275165" name="modules/locale/org-netbeans-modules-xml-catalog_zh_CN.jar"/>
        <file crc="2234528957" name="modules/org-netbeans-modules-xml-catalog.jar"/>
    </module_version>
</module>


text:
@implementation NSDate (Legendary)

- (instancetype)initWithYear:(NSInteger)year month:(NSInteger)month day:(NSInteger)day{

    self  = [self init];
    if (self){
        NSCalendar *calendar = [NSCalendar currentCalendar];
        NSDateComponents *components = [[NSDateComponents alloc] init];
        components.year = year;
        components.month = month;
        components.day = day;
        components.timeZone = [NSTimeZone timeZoneWithName:@"America/New_York"];
        self = [calendar dateFromComponents:components];
    }

    return self;
}

@end


text:
oTest.fnStart( "fnCreatedCell tests" );

$(document).ready( function () {
	var tmp = 0;
	var complete = false;

	$('#example').dataTable( {
		"bServerSide": true,
		"sAjaxSource": "../../../examples/server_side/scripts/server_processing.php",
		"aoColumnDefs": [ {
			fnCreatedCell: function () {
				tmp++;
			},
			"aTargets": ["_all"]
		} ]
	} );

	oTest.fnWaitTest(
		"Cell created is called once for each cell on init",
		null,
		function () { return tmp===50; }
	);

	oTest.fnWaitTest(
		"Created is called back on other draws",
		function () { $('#example th:eq(1)').click(); },
		function () { return tmp===100; }
	);

	oTest.fnWaitTest(
		"Four arguments for the function",
		function () {
			oSession.fnRestore();
			tmp = true;
			complete = false;

			$('#example').dataTable( {
				"bServerSide": true,
				"sAjaxSource": "../../../examples/server_side/scripts/server_processing.php",
				"aoColumnDefs": [ {
					fnCreatedRow: function () {
						if ( arguments.length !== 4 ) {
							tmp = false;
						}
					},
					"aTargets": ["_all"]
				} ],
				fnInitComplete: function () {
					complete = true;
				}
			} );
		},
		function () { return (tmp && complete); }
	);

	oTest.fnWaitTest(
		"First argument is a TD element",
		function () {
			oSession.fnRestore();
			tmp = true;
			complete = false;

			$('#example').dataTable( {
				"bServerSide": true,
				"sAjaxSource": "../../../examples/server_side/scripts/server_processing.php",
				"aoColumnDefs": [ {
					fnCreatedRow: function () {
						if ( arguments[0].nodeName !== "TD" ) {
							tmp = false;
						}
					},
					"aTargets": ["_all"]
				} ],
				fnInitComplete: function () {
					complete = true;
				}
			} );
		},
		function () { return (tmp && complete); }
	);

	oTest.fnWaitTest(
		"Second argument is the HTML value",
		function () {
			oSession.fnRestore();
			tmp = true;
			complete = false;

			$('#example').dataTable( {
				"bServerSide": true,
				"sAjaxSource": "../../../examples/server_side/scripts/server_processing.php",
				"aoColumnDefs": [ {
					fnCreatedRow: function () {
						if ( arguments[1] != $('td').html() ) {
							tmp = false;
						}
					},
					"aTargets": ["_all"]
				} ],
				fnInitComplete: function () {
					complete = true;
				}
			} );
		},
		function () { return (tmp && complete); }
	);

	oTest.fnWaitTest(
		"Third argument is the data array",
		function () {
			oSession.fnRestore();
			tmp = true;
			complete = false;

			$('#example').dataTable( {
				"bServerSide": true,
				"sAjaxSource": "../../../examples/server_side/scripts/server_processing.php",
				"aoColumnDefs": [ {
					fnCreatedRow: function () {
						if ( arguments[2].length !== 5 ) {
							tmp = false;
						}
					},
					"aTargets": ["_all"]
				} ],
				fnInitComplete: function () {
					complete = true;
				}
			} );
		},
		function () { return (tmp && complete); }
	);

	oTest.fnWaitTest(
		"Fourth argument is the data source for the row",
		function () {
			oSession.fnRestore();
			tmp = true;
			complete = false;

			$('#example').dataTable( {
				"bServerSide": true,
				"sAjaxSource": "../../../examples/server_side/scripts/server_processing.php",
				"aoColumnDefs": [ {
					fnCreatedRow: function () {
						if ( arguments[2] !== this.fnSettings().aoData[ arguments[2] ]._aData ) {
							tmp = false;
						}
					},
					"aTargets": ["_all"]
				} ],
				fnInitComplete: function () {
					complete = true;
				}
			} );
		},
		function () { return (tmp && complete); }
	);

	oTest.fnWaitTest(
		"Fifth argument is the the col index",
		function () {
			oSession.fnRestore();
			tmp = true;
			complete = false;

			$('#example').dataTable( {
				"bServerSide": true,
				"sAjaxSource": "../../../examples/server_side/scripts/server_processing.php",
				"aoColumnDefs": [ {
					fnCreatedRow: function () {
						if ( arguments[1] != $('td:eq('+arguments[4]+')', arguments[0].parentNode).html() ) {
							tmp = false;
						}
					},
					"aTargets": ["_all"]
				} ],
				fnInitComplete: function () {
					complete = true;
				}
			} );
		},
		function () { return (tmp && complete); }
	);

	oTest.fnComplete();
} );


text:
<?php declare(strict_types=1);

namespace NettePalette\Latte;

use Latte\CompileException;
use Latte\Compiler;
use Latte\MacroNode;
use Latte\Macros\MacroSet;
use Latte\PhpWriter;
use Nette\Utils\Validators;

/**
 * LatteMacroSet
 * @package NettePalette\Latte
 * @url https://usefulangle.com/post/114/webp-image-in-html-with-fallback
 */
final class LatteMacroSet extends MacroSet
{
    /** @var bool je aktuálně vykreslován tag picture přes makro? */
    private $isInPicture = false;

    /** @var string|null PHP kód pro načtení zdrojového obrázku pro picture set. */
    private $pictureSrcPhpCode = null;

    /** @var int<1, 100>|null přetížení výchozí kvality WebP obrázků. */
    private $macroWebPQuality = null;

    /**
     * Provede instalaci palette maker do Latte compileru.
     * @param Compiler $compiler
     * @return void
     */
    public static function install(Compiler $compiler): void
    {
        $me = new LatteMacroSet($compiler);

        // Přidání makra pro vygenerování picture setu s WebP verzí obrázku.
        $me->addMacro('webp', [$me, 'macroWebpOpen'], [$me, 'macroWebpClose']);

        // Přidání makra pro definici zdrojového obrázku picture setu (tento obrázek se používá jako fallback pro staré prohlížeče).
        $me->addMacro('picture-src', null, null, [$me, 'macroPictureSrc']);

        // Přidání makra pro vygenerování src odkazu pro obrázek přes n:palette-src.
        $me->addMacro('palette-src', null, null, [$me, 'macroPaletteSrc']);
    }

    /**
     * Provedení akcí při začátku vykreslování picture setu.
     * @param MacroNode $node
     * @param PhpWriter $writer
     * @return string
     * @throws CompileException
     */
    public function macroWebpOpen(MacroNode $node, PhpWriter $writer): string
    {
        $this->isInPicture = true;
        $this->pictureSrcPhpCode = null;
        $this->macroWebPQuality = null;

        // Makro n:webp je možné používat pouze na html tagu picture.
        if (!$node->htmlNode || strtolower($node->htmlNode->name) !== 'picture')
        {
            throw new CompileException('Macro n:webp is allowed only on html tag <picture> in ' . $node->getNotation());
        }

        // Načteme a zvalidujeme vlastní definici kvality WebP obrázků v makru.
        $quality = $node->tokenizer->fetchWord();

        if ($quality !== null)
        {
            $intQuality = (int) $quality;

            if ($intQuality <= 0 || $intQuality > 100 || !Validators::isNumericInt($quality))
            {
                throw new CompileException('Quality of must be int<1, 100>|null in ' . $node->getNotation());
            }

            $this->macroWebPQuality = $intQuality;
        }

        return '';
    }

    /**
     * Provedení akcí při dokončení vykreslování picture setu.
     * @param MacroNode $node
     * @param PhpWriter $writer
     * @return string
     * @throws CompileException
     */
    public function macroWebpClose(MacroNode $node, PhpWriter $writer): string
    {
        $this->isInPicture = false;

        if (!$this->pictureSrcPhpCode)
        {
            throw new CompileException('Missing picture-src inside macro webp in ' . $node->getNotation());
        }

        // Vygenerování source setů přes palette.
        // (kód v picture tagu je nutné striktně seřadit!)
        $node->innerContent =
            // Sestavení instance zdrojového obrázku.
            $this->pictureSrcPhpCode .
            // Vygenerované srcsety
            $writer->write(
                '<?php echo NettePalette\Latte\LatteHelpers::generatePictureSrcSetHtml(%var, $this->global->palette, $__paletteSourcePicture); ?>',
                $this->macroWebPQuality
            ) .
            // Fallback tag img a případný existující obsah tagu <picture>
            $node->innerContent .
            // Promazání dočasných proměnných.
            $writer->write('<?php unset($__paletteSourcePicture); ?>');

        return '';
    }

    /**
     * Definice zdrojového obrázku pro picture set, tento obrázek se použije jako fallback.
     * @param MacroNode $node
     * @param PhpWriter $writer
     * @return string
     * @throws CompileException
     */
    public function macroPictureSrc(MacroNode $node, PhpWriter $writer): string
    {
        // Makro `picture-src` je možné používat pouze uvnitř makra `webp`.
        if (!$this->isInPicture)
        {
            throw new CompileException('Macro picture-src is only available inside macro webp in ' . $node->getNotation());
        }

        // Je možné definovat pouze jeden zdrojový obrázek pro picture set.
        if ($this->pictureSrcPhpCode !== null)
        {
            throw new CompileException('Multiple picture-src in webp macro is forbidden in ' . $node->getNotation());
        }

        // Makro n:picture-src je možné používat pouze na html tagu img.
        if (!$node->htmlNode || strtolower($node->htmlNode->name) !== 'img')
        {
            throw new CompileException('Macro n:picture-src is allowed only on html tag <img> in ' . $node->getNotation());
        }

        // Vygenerujeme PHP kód pro načtení zdrojového obrázku setu přes Palette.
        $this->pictureSrcPhpCode = $writer->write(
            '<?php $__paletteSourcePicture=$this->global->palette->getSourcePicture(true, %var, %node.args); ?>',
            $this->macroWebPQuality
        );

        // Vygenerujeme PHP/HTML kód img tagu s fallbackem picture setu.
        return
            ' ?> src="<?php ' .
            $writer->write('echo NettePalette\Latte\LatteHelpers::generateImgUrl($this->global->palette, $__paletteSourcePicture); ') .
            '?>"<?php ';
    }

    /**
     * Definice zdrojového obrázku img tagu přes makro n:palette.
     * @param MacroNode $node
     * @param PhpWriter $writer
     * @return string
     * @throws CompileException
     */
    public function macroPaletteSrc(MacroNode $node, PhpWriter $writer): string
    {
        $htmlNodeName = $node->htmlNode ? strtolower($node->htmlNode->name) : null;

        // Makro n:palette-src je možné používat pouze na html tagu img | source.
        if (!in_array($htmlNodeName, ['img', 'source'], true))
        {
            throw new CompileException('Macro n:picture-src is allowed only on html tag <img> or <source> in ' . $node->getNotation());
        }

        // Vygenerujeme název html atributu s cestou k obrázku.
        $htmlSrcAttribute = $htmlNodeName === 'source' ? 'srcset' : 'src';

        return
            ' ?> ' . $htmlSrcAttribute . '="<?php ' .
            $writer->write('echo $this->global->palette->getSourcePicture(false, null, %node.args)->getPictureUrl(); ') .
            '?>"<?php ';
    }
}


text:
require 'rubygems'
require 'rspec'
require 'maestro_plugin/logging_stdout'

$LOAD_PATH.unshift(File.dirname(__FILE__) + '/../src') unless $LOAD_PATH.include?(File.dirname(__FILE__) + '/../src')

require 'git_worker'

RSpec.configure do |config|
  config.mock_with :mocha
end


text:
package com.amazonaws.services.elasticloadbalancing.model.transform;

import javax.annotation.Generated;

import com.amazonaws.SdkClientException;
import com.amazonaws.Request;
import com.amazonaws.DefaultRequest;
import com.amazonaws.http.HttpMethodName;
import com.amazonaws.services.elasticloadbalancing.model.*;
import com.amazonaws.transform.Marshaller;
import com.amazonaws.util.StringUtils;

/**
 * CreateLBCookieStickinessPolicyRequest Marshaller
 */

@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class CreateLBCookieStickinessPolicyRequestMarshaller implements
        Marshaller<Request<CreateLBCookieStickinessPolicyRequest>, CreateLBCookieStickinessPolicyRequest> {

    public Request<CreateLBCookieStickinessPolicyRequest> marshall(CreateLBCookieStickinessPolicyRequest createLBCookieStickinessPolicyRequest) {

        if (createLBCookieStickinessPolicyRequest == null) {
            throw new SdkClientException("Invalid argument passed to marshall(...)");
        }

        Request<CreateLBCookieStickinessPolicyRequest> request = new DefaultRequest<CreateLBCookieStickinessPolicyRequest>(
                createLBCookieStickinessPolicyRequest, "AmazonElasticLoadBalancing");
        request.addParameter("Action", "CreateLBCookieStickinessPolicy");
        request.addParameter("Version", "2012-06-01");
        request.setHttpMethod(HttpMethodName.POST);

        if (createLBCookieStickinessPolicyRequest.getLoadBalancerName() != null) {
            request.addParameter("LoadBalancerName", StringUtils.fromString(createLBCookieStickinessPolicyRequest.getLoadBalancerName()));
        }

        if (createLBCookieStickinessPolicyRequest.getPolicyName() != null) {
            request.addParameter("PolicyName", StringUtils.fromString(createLBCookieStickinessPolicyRequest.getPolicyName()));
        }

        if (createLBCookieStickinessPolicyRequest.getCookieExpirationPeriod() != null) {
            request.addParameter("CookieExpirationPeriod", StringUtils.fromLong(createLBCookieStickinessPolicyRequest.getCookieExpirationPeriod()));
        }

        return request;
    }

}


text:
$('#form_presupuestos').validate({
    errorElement: 'span', //default input error message container
    errorClass: 'help-inline', // default input error message class
    focusInvalid: false, // do not focus the last invalid input
    ignore: "",
    rules: {
        presupuesto_id: {
            required: true
        },
        unidad_id: {
            required: true
        },
        status_id: {
            required: true
        },
        descripcion: {
            required: true
        },
        cantidad: {
            number: true,
            required: true
        },
        rendimiento: {
            number: true,
            required: true
        }
    },

    invalidHandler: function (event, validator) { //display error alert on form submit
        $('.alert-success').hide();
        $('.alert-error').show();
        //App.scrollTo(error1, -200);
    },

    submitHandler: function (form) {
        //$('.alert-success').show();
        $('.alert-error').hide();
        form.submit();
    },

    highlight: function (element) { // hightlight error inputs
        $(element).closest('.help-inline').removeClass('ok'); // display OK icon
        $(element).closest('.control-group').removeClass('success').addClass('error'); // set error class to the control group
    },

    unhighlight: function (element) { // revert the change dony by hightlight
        $(element).closest('.control-group').removeClass('error'); // set error class to the control group
    },

    success: function (label) {
        label.addClass('valid').addClass('help-inline ok') // mark the current input as valid and display OK icon
        .closest('.control-group').removeClass('error').addClass('success'); // set success class to the control group
    }
});


text:
/*
 * USER: mslm
 * DATE: 3/15/17
 */

package com.gedder.gedderalarm.controller;

import android.content.Context;
import android.database.Cursor;
import android.support.v4.widget.CursorAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.ToggleButton;

import com.gedder.gedderalarm.R;
import com.gedder.gedderalarm.db.AlarmClockDBSchema.AlarmClockTable;

import java.util.Locale;

/**
 *
Provides a custom ArrayAdapter for the AlarmClock class.

 *
 *
Can be used, for example, to populate ListViews with alarm clocks.

 */

public class AlarmClocksCursorAdapter extends CursorAdapter {
    private static final String TAG = AlarmClocksCursorAdapter.class.getSimpleName();

    public AlarmClocksCursorAdapter(Context context, Cursor cursor) {
        super(context, cursor, 0);
    }

    @Override
    public View newView(final Context context, final Cursor cursor, ViewGroup parent) {
        return LayoutInflater.from(context).inflate(R.layout.item_alarm_clock, parent, false);
    }

    @Override
    public void bindView(View view, Context context, Cursor cursor) {
        // Set the UUID of the alarm as a tag to this view.
        view.setTag(cursor.getString(cursor.getColumnIndexOrThrow(
                AlarmClockTable.Columns.UUID)));

        // Get data needed for this view.
        int hour         = cursor.getInt(cursor.getColumnIndexOrThrow(
                AlarmClockTable.Columns.ALARM_HOUR));
        int minute       = cursor.getInt(cursor.getColumnIndexOrThrow(
                AlarmClockTable.Columns.ALARM_MINUTE));
        boolean alarmOn  = cursor.getInt(cursor.getColumnIndexOrThrow(
                AlarmClockTable.Columns.ALARM_SET)) > 0;
        boolean gedderOn = cursor.getInt(cursor.getColumnIndexOrThrow(
                AlarmClockTable.Columns.GEDDER_SET)) > 0;

        // Format our display.
        String period = hour >= 12? "PM":"AM";
        hour          = hour > 12? (hour % 12) : (hour == 0? 12 : hour);
        String time   = String.format(Locale.getDefault(), "%d:%02d %s", hour, minute, period);

        // Populate our views with that formatted data.
        ((TextView) view.findViewById(R.id.itemAlarmClock_WakeupTime)).setText(time);

        if (alarmOn) {
            ((ToggleButton) view.findViewById(R.id.itemAlarmClock_alarmClockToggleBtn))
                    .setChecked(true);
        } else {
            ((ToggleButton) view.findViewById(R.id.itemAlarmClock_alarmClockToggleBtn))
                    .setChecked(false);
        }

        if (gedderOn) {
            ((ToggleButton) view.findViewById(R.id.itemAlarmClock_GedderAlarmToggleBtn))
                    .setChecked(true);
        } else {
            ((ToggleButton) view.findViewById(R.id.itemAlarmClock_GedderAlarmToggleBtn))
                    .setChecked(false);
        }
    }
}


text:
package org.intellij.plugins.relaxNG.model.resolve;

import com.intellij.ide.highlighter.XmlFileType;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiManager;
import com.intellij.psi.impl.include.FileIncludeManager;
import com.intellij.psi.search.PsiElementProcessor;
import com.intellij.psi.xml.XmlFile;
import com.intellij.util.NullableFunction;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.xml.DomManager;
import org.intellij.plugins.relaxNG.compact.RncFileType;
import org.intellij.plugins.relaxNG.xml.dom.RngGrammar;
import org.jetbrains.annotations.NotNull;

/*
* Created by IntelliJ IDEA.
* User: sweinreuter
* Date: 09.06.2010
*/
public class RelaxIncludeIndex {
  public static boolean processForwardDependencies(XmlFile file, final PsiElementProcessor<XmlFile> processor) {
    final Project project = file.getProject();
    final VirtualFile[] files = FileIncludeManager.getManager(project).getIncludedFiles(file.getVirtualFile(), true);

    return processRelatedFiles(file, files, processor);
  }

  public static boolean processBackwardDependencies(@NotNull XmlFile file, PsiElementProcessor<XmlFile> processor) {
    return processBackwardDependencies((PsiFile)file, processor);
  }

  private static boolean processBackwardDependencies(@NotNull PsiFile file, PsiElementProcessor<XmlFile> processor) {
    final Project project = file.getProject();
    final VirtualFile[] files = FileIncludeManager.getManager(project).getIncludingFiles(file.getVirtualFile(), true);

    return processRelatedFiles(file, files, processor);
  }

  private static boolean processRelatedFiles(PsiFile file, VirtualFile[] files, PsiElementProcessor<XmlFile> processor) {
    Project project = file.getProject();
    final PsiManager psiManager = PsiManager.getInstance(project);
    final PsiFile[] psiFiles = ContainerUtil.map2Array(files, PsiFile.class, new NullableFunction<VirtualFile, PsiFile>() {
      public PsiFile fun(VirtualFile file) {
        return psiManager.findFile(file);
      }
    });

    for (final PsiFile psiFile : psiFiles) {
      final FileType type = file.getFileType();
      if (type == XmlFileType.INSTANCE && isRngFile(psiFile)) {
        if (!processor.execute((XmlFile)psiFile)) {
          return false;
        }
      } else if (type == RncFileType.getInstance()) {
        if (!processor.execute((XmlFile)psiFile)) {
          return false;
        }
      }
    }
    return true;
  }

  static boolean isRngFile(PsiFile psiFile) {
    try {
      return DomManager.getDomManager(psiFile.getProject()).getFileElement((XmlFile)psiFile, RngGrammar.class) != null;
    } catch (ClassCastException e) {
      return false; // fileType == XML && !instanceof XmlFile
    }
  }
}


text:
package com.jetbrains.python.psi.impl;

import com.intellij.lang.ASTNode;
import com.intellij.psi.PsiElement;
import com.intellij.psi.tree.TokenSet;
import com.intellij.psi.util.PsiTreeUtil;
import com.jetbrains.python.PyElementTypes;
import com.jetbrains.python.psi.*;
import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;

/**
 * @author yole
 */
public class PyWithStatementImpl extends PyElementImpl implements PyWithStatement {
  private static final TokenSet WITH_ITEM = TokenSet.create(PyElementTypes.WITH_ITEM);

  public PyWithStatementImpl(ASTNode astNode) {
    super(astNode);
  }

  protected void acceptPyVisitor(final PyElementVisitor pyVisitor) {
    pyVisitor.visitPyWithStatement(this);
  }

  @NotNull
  public Iterable<PyElement> iterateNames() {
    PyWithItem[] items = PsiTreeUtil.getChildrenOfType(this, PyWithItem.class);
    List<PyElement> result = new ArrayList<PyElement>();
    if (items != null) {
      for (PyWithItem item : items) {
        PyExpression targetExpression = item.getTarget();
        result.addAll(PyUtil.flattenedParensAndTuples(targetExpression));
      }
    }
    return result;
  }

  public PsiElement getElementNamed(final String the_name) {
    PyElement named_elt = IterHelper.findName(iterateNames(), the_name);
    return named_elt;
  }

  public boolean mustResolveOutside() {
    return false;
  }

  public PyWithItem[] getWithItems() {
    return childrenToPsi(WITH_ITEM, PyWithItem.EMPTY_ARRAY);
  }

  @Override
  @NotNull
  public PyStatementList getStatementList() {
    final PyStatementList statementList = childToPsi(PyElementTypes.STATEMENT_LIST);
    assert statementList != null : "Statement list missing for with statement " + getText();
    return statementList;
  }
}


text:
package org.apache.johnzon.jsonschema.spi.builtin;

import java.util.Optional;
import java.util.function.Function;
import java.util.stream.Stream;

import javax.json.JsonNumber;
import javax.json.JsonValue;

import org.apache.johnzon.jsonschema.ValidationResult;
import org.apache.johnzon.jsonschema.spi.ValidationContext;
import org.apache.johnzon.jsonschema.spi.ValidationExtension;

public class MinimumValidation implements ValidationExtension {
    @Override
    public Optional<Function<JsonValue, Stream<ValidationResult.ValidationError>>> create(final ValidationContext model) {
        if (model.getSchema().getString("type", "object").equals("number")) {
            return Optional.ofNullable(model.getSchema().get("minimum"))
                    .filter(v -> v.getValueType() == JsonValue.ValueType.NUMBER)
                    .map(m -> new Impl(model.toPointer(), model.getValueProvider(), JsonNumber.class.cast(m).doubleValue()));
        }
        return Optional.empty();
    }

    private static class Impl extends BaseNumberValidation {
        private Impl(final String pointer, final Function<JsonValue, JsonValue> valueProvider, final double bound) {
            super(pointer, valueProvider, bound);
        }

        @Override
        protected boolean isValid(final double val) {
            return val >= this.bound;
        }

        @Override
        protected Stream<ValidationResult.ValidationError> toError(final double val) {
            return Stream.of(new ValidationResult.ValidationError(pointer, val + " is less than " + this.bound));
        }

        @Override
        public String toString() {
            return "Minimum{" +
                    "factor=" + bound +
                    ", pointer='" + pointer + '\'' +
                    '}';
        }
    }
}


text:
package org.assertj.core.error;

/**
 * Creates an error message indicating that an assertion that verifies that an object has same class as another instance failed.
 *
 * @author Nicolas François
 */
public class ShouldNotHaveSameClass extends BasicErrorMessageFactory {

  /**
   * Creates a new </code>{@link ShouldNotHaveSameClass}</code>.
   * @param actual the actual value in the failed assertion.
   * @param other the type {@code actual} is expected to be.
   * @return the created {@code ErrorMessageFactory}.
   */
  public static ErrorMessageFactory shouldNotHaveSameClass(Object actual, Object other) {
    return new ShouldNotHaveSameClass(actual, other);
  }

  private ShouldNotHaveSameClass(Object actual, Object other) {
    super("%nExpecting:%n <%s>%nnot to have not the same class as:%n <%s> (%s)", actual, other, actual.getClass());
  }
}


text:
Territories

<map center="{{mapCenter}}" zoom="11" mayTypeId="ROADMAP" ng-model="customers">

      <marker ng-repeat="collectionSite in collectionSites" icon="img/collection.png"
       	position="{{collectionSite.coords}}"
       	title="Collection Site: {{collectionSite.name}}, {{collectionSite.address}} "/>

      <shape name="polygon"  stroke-color="#FF0000"
       stroke-opacity="0.8"
       stroke-weight="2"
       fill-color="{{territory.color}}"
       label ="goo"
       fill-opacity="0.12" ng-repeat="territory in territories" paths="{{territory.coords}}"/>

      <marker ng-repeat="territory in territories" icon="img/number_{{territory.name}}.png"
       	position="{{territory.marker}}" ng-show="territory.marker"
       	title="{{territory._id}}"/>

  </map>

<button ng-click="logout()">Log Out</button>


text:
import { Component, Input, AfterViewInit, ViewChild, ComponentFactoryResolver } from '@angular/core';

import { ReplaySubject } from 'rxjs/ReplaySubject';

import { View } from './view';
import { ViewActionRegistry } from './view-action-registry.service';
import { ViewActionComponent } from './view-action.component';
import { ViewActionHostDirective } from './view-action-host.directive';
import { ViewActionItem } from './view-action-item';

@Component({
  selector: 'zp-view-action-container',
  template: `
    <ng-template zpViewActionHost></ng-template>
  `
})
export class ViewActionContainerComponent implements AfterViewInit {
  @Input() context: ReplaySubject<any>;
  @Input() view: View;
  @ViewChild(ViewActionHostDirective) zpViewActionHost: ViewActionHostDirective;

  private actions: ViewActionItem[];

  constructor(private resolver: ComponentFactoryResolver, private registry: ViewActionRegistry) { }

  ngAfterViewInit() {
    console.log('ViewActionContainerComponent::ngAfterInitView', this.context, this.view);
    this.actions = this.registry.getActionsByView(this.view);
    const container = this.zpViewActionHost.viewContainerRef;
    container.clear();
    this.actions.forEach((action) => {
      const factory = this.resolver.resolveComponentFactory(action.component);
      const ref = container.createComponent(factory);
      const component = <ViewActionComponent>ref.instance;
      // Inject initial parameters
      component.parameters = action.parameters;
      // Inject view context
      component.context = this.context;
      // Notify context injected
      component.onContextInjected(this.context);
    });
  }

}


text:
 .. Licensed to the Apache Software Foundation (ASF) under one
    or more contributor license agreements.  See the NOTICE file
    distributed with this work for additional information
    regarding copyright ownership.  The ASF licenses this file
    to you under the Apache License, Version 2.0 (the
    "License"); you may not use this file except in compliance
    with the License.  You may obtain a copy of the License at

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

 .. Unless required by applicable law or agreed to in writing,
    software distributed under the License is distributed on an
    "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
    KIND, either express or implied.  See the License for the
    specific language governing permissions and limitations
    under the License.

Production Guide
================

The following are things to consider when using this Helm chart in a production environment.

Database
--------

You will want to use an external database instead of the one deployed with the chart by default.
Both **PostgreSQL** and **MySQL** are supported. Supported versions can be
found on the :doc:`Set up a Database Backend <apache-airflow:howto/set-up-database>` page.

.. code-block:: yaml

  # Don't deploy postgres
  postgresql:
    enabled: false

  # Use an external database
  data:
    metadataConnection:
      user: ...
      pass: ...
      protocol: postgresql  # or 'mysql'
      host: ...
      port: ...
      db: ...

.. _production-guide:pgbouncer:

PgBouncer
---------

If you are using PostgreSQL as your database, you will likely want to enable `PgBouncer <https://www.pgbouncer.org/>`_ as well.
Airflow can open a lot of database connections due to its distributed nature and using a connection pooler can significantly
reduce the number of open connections on the database.

.. code-block:: yaml

  pgbouncer:
    enabled: true

Depending on the size of you Airflow instance, you may want to adjust the following as well (defaults are shown):

.. code-block:: yaml

  pgbouncer:
    # The maximum number of connections to PgBouncer
    maxClientConn: 100
    # The maximum number of server connections to the metadata database from PgBouncer
    metadataPoolSize: 10
    # The maximum number of server connections to the result backend database from PgBouncer
    resultBackendPoolSize: 5

Webserver Secret Key
--------------------

You should set a static webserver secret key when deploying with this chart as it will help ensure
your Airflow components only restart when necessary.

.. warning::
  You should use a different secret key for every instance you run, as this key is used to sign
  session cookies and perform other security related functions!

First, generate a strong secret key:

.. code-block:: bash

    python3 -c 'import secrets; print(secrets.token_hex(16))'

Now add the secret to your values file:

.. code-block:: yaml

    webserverSecretKey: <secret_key>

Alternatively, create a kubernetes Secret and use ``webserverSecretKeySecretName``:

.. code-block:: yaml

    webserverSecretKeySecretName: my-webserver-secret
    # where the random key is under `webserver-secret-key` in the k8s Secret

Example to create a kubernetes Secret from ``kubectl``:

.. code-block:: bash

    kubectl create secret generic my-webserver-secret --from-literal="webserver-secret-key=$(python3 -c 'import secrets; print(secrets.token_hex(16))')"

Extending and customizing Airflow Image
---------------------------------------

The Apache Airflow community, releases Docker Images which are ``reference images`` for Apache Airflow.
However, Airflow has more than 60 community managed providers (installable via extras) and some of the
default extras/providers installed are not used by everyone, sometimes others extras/providers
are needed, sometimes (very often actually) you need to add your own custom dependencies,
packages or even custom providers, or add custom tools and binaries that are needed in
your deployment.

In Kubernetes and Docker terms this means that you need another image with your specific requirements.
This is why you should learn how to build your own ``Docker`` (or more properly ``Container``) image.

Typical scenarios where you would like to use your custom image:

* Adding ``apt`` packages
* Adding ``PyPI`` packages
* Adding binary resources necessary for your deployment
* Adding custom tools needed in your deployment

See `Building the image <https://airflow.apache.org/docs/docker-stack/build.html>`_ for more
details on how you can extend and customize the Airflow image.

Managing DAG Files
------------------

See :doc:`manage-dags-files`.

.. _production-guide:knownhosts:

knownHosts
^^^^^^^^^^

If you are using ``dags.gitSync.sshKeySecret``, you should also set ``dags.gitSync.knownHosts``. Here we will show the process
for GitHub, but the same can be done for any provider:

Grab GitHub's public key:

.. code-block:: bash

    ssh-keyscan -t rsa github.com > github_public_key

Next, print the fingerprint for the public key:

.. code-block:: bash

    ssh-keygen -lf github_public_key

Compare that output with `GitHub's SSH key fingerprints <https://docs.github.com/en/github/authenticating-to-github/githubs-ssh-key-fingerprints>`_.

They match, right? Good. Now, add the public key to your values. It'll look something like this:

.. code-block:: yaml

    dags:
      gitSync:
        knownHosts: |
          github.com ssh-rsa AAAA...FAaQ==

Accessing the Airflow UI
------------------------

How you access the Airflow UI will depend on your environment, however the chart does support various options:

Ingress
^^^^^^^

You can create and configure ``Ingress`` objects. See the :ref:`Ingress chart parameters <parameters:ingress>`.
For more information on ``Ingress``, see the
`Kubernetes Ingress documentation <https://kubernetes.io/docs/concepts/services-networking/ingress/>`_.

LoadBalancer Service
^^^^^^^^^^^^^^^^^^^^

You can change the Service type for the webserver to be ``LoadBalancer``, and set any necessary annotations:

.. code-block:: yaml

  webserver:
    service: LoadBalancer
    annotations: {}

For more information on ``LoadBalancer`` Services, see the `Kubernetes LoadBalancer Service Documentation
<https://kubernetes.io/docs/concepts/services-networking/service/#loadbalancer>`_.

Logging
-------

Depending on your choice of executor, task logs may not work out of the box. All logging choices can be found
at :doc:`manage-logs`.

Metrics
-------

The chart can support sending metrics to an existing StatsD instance or provide a Prometheus endpoint.

Prometheus
^^^^^^^^^^

The metrics endpoint is available at ``svc/{{ .Release.Name }}-statsd:9102/metrics``.

External StatsD
^^^^^^^^^^^^^^^

To use an external StatsD instance:

.. code-block:: yaml

  statsd:
    enabled: false
  config:
    metrics:  # or 'scheduler' for Airflow 1
      statsd_on: true
      statsd_host: ...
      statsd_port: ...

Celery Backend
--------------

If you are using ``CeleryExecutor`` or ``CeleryKubernetesExecutor``, you can bring your own Celery backend.

By default, the chart will deploy Redis. However, you can use any supported Celery backend instead:

.. code-block:: yaml

  redis:
    enabled: false
  data:
    brokerUrl: redis://redis-user:password@redis-host:6379/0

For more information about setting up a Celery broker, refer to the
exhaustive `Celery documentation on the topic <http://docs.celeryproject.org/en/latest/getting-started/>`_.

Security Context Constraints
-----------------------------

A ``Security Context Constraint`` (SCC) is a OpenShift construct that works as a RBAC rule however it targets Pods instead of users.
When defining a SCC, one can control actions and resources a POD can perform or access during startup and runtime.

The SCCs are split into different levels or categories with the ``restricted`` SCC being the default one assigned to Pods.
When deploying Airflow to OpenShift, one can leverage the SCCs and allow the Pods to start containers utilizing the ``anyuid`` SCC.

In order to enable the usage of SCCs, one must set the parameter :ref:`rbac.createSCCRoleBinding <parameters:Kubernetes>` to ``true`` as shown below:

.. code-block:: yaml

  rbac:
    create: true
    createSCCRoleBinding: true

In this chart, SCCs are bound to the Pods via RoleBindings meaning that the option ``rbac.create`` must also be set to ``true`` in order to fully enable the SCC usage.

For more information about SCCs and what can be achieved with this construct, please refer to `Managing security context constraints <https://docs.openshift.com/container-platform/latest/authentication/managing-security-context-constraints.html#scc-prioritization_configuring-internal-oauth/>`_.


text:
#include "paragraph/scheduling/instruction_fsm.h"

#include <algorithm>
#include <string>
#include <vector>

#include "absl/strings/str_cat.h"
#include "paragraph/scheduling/graph_scheduler.h"
#include "paragraph/shim/macros.h"

namespace paragraph {

std::string InstructionFsm::InstructionStateToString(
    InstructionFsm::State state) {
  switch (state) {
#define CASE_STATE_STRING(enum_name, state_name)     \
    case InstructionFsm::State::enum_name:           \
    return state_name;
    INSTRUCTION_STATE_LIST(CASE_STATE_STRING)
#undef CASE_STATE_STRING
  default:
    return "UNKNOWN";
  }
}

shim::StatusOr<InstructionFsm::State> InstructionFsm::StringToInstructionState(
    const std::string& state_name) {
  static auto* state_map = new absl::flat_hash_map<
      std::string, InstructionFsm::State>({
#define STRING_TO_STATE_ENTRY(enum_name, state_name) \
  {state_name, InstructionFsm::State::enum_name},
      INSTRUCTION_STATE_LIST(STRING_TO_STATE_ENTRY)
#undef STRING_TO_STATE_ENTRY
  });
  auto it = state_map->find(state_name);
  if (it == state_map->end()) {
    return absl::InvalidArgumentError(
        "Unknown instruction FSM state " + state_name +
        " in StringToInstructionState conversion.");
  }
  return it->second;
}

InstructionFsm::InstructionFsm(GraphScheduler* scheduler,
                               Instruction* instruction)
    : instruction_(instruction),
      scheduler_(scheduler),
      time_ready_(0.0),
      time_started_(0.0),
      time_finished_(0.0),
      clock_time_(0.0),
      wall_time_(0.0) {}

bool InstructionFsm::IsUnblockedByOperands() const {
  bool unblocked = true;
  for (auto& operand : instruction_->Operands()) {
    unblocked &= scheduler_->GetFsm(operand).IsFinished();
  }
  return unblocked;
}

bool InstructionFsm::IsBlocked() const {
  return state_ == State::kBlocked;
}

void InstructionFsm::SetBlocked() { state_ = State::kBlocked; }

bool InstructionFsm::IsReady() const { return state_ == State::kReady; }

void InstructionFsm::SetReady() { state_ = State::kReady; }

bool InstructionFsm::IsScheduled() const {
  return state_ == State::kScheduled;
}

void InstructionFsm::SetScheduled() { state_ = State::kScheduled; }

bool InstructionFsm::IsExecuting() const {
  return state_ == State::kExecuting;
}

void InstructionFsm::SetExecuting() { state_ = State::kExecuting; }

bool InstructionFsm::IsFinished() const {
  return state_ == State::kFinished;
}

void InstructionFsm::SetFinished() { state_ = State::kFinished; }

double InstructionFsm::GetTimeReady() const {
  return time_ready_;
}

void InstructionFsm::SetTimeReady(double current_time) {
  time_ready_ = current_time;
}

double InstructionFsm::GetTimeStarted() const {
  return time_started_;
}

void InstructionFsm::SetTimeStarted(double current_time) {
  time_started_ = current_time;
}

double InstructionFsm::GetTimeFinished() const {
  return time_finished_;
}

void InstructionFsm::SetTimeFinished(double current_time) {
  time_finished_ = current_time;
}

double InstructionFsm::GetClockTime() const {
  return clock_time_;
}

void InstructionFsm::SetClockTime(double current_time) {
  clock_time_ = current_time;
}

double InstructionFsm::GetWallTime() const {
  return wall_time_;
}

void InstructionFsm::SetWallTime(double current_time) {
  wall_time_ = current_time;
}

void InstructionFsm::Reset() {
  SetTimeReady(0.0);
  SetTimeStarted(0.0);
  SetTimeFinished(0.0);
  SetClockTime(0.0);
  SetWallTime(0.0);
  if (instruction_->Operands().empty()) {
    state_ = State::kReady;
  } else {
    state_ = State::kBlocked;
  }
  for (auto& subroutine : instruction_->InnerSubroutines()) {
    scheduler_->GetFsm(subroutine.get()).Reset();
  }
}

const Instruction* InstructionFsm::GetInstruction() const {
  return instruction_;
}

absl::Status InstructionFsm::PrepareToSchedule() {
  // If instruction has inner subroutines, we don't schedule it directly,
  // instead we schedule inner subroutines and its instructions
  if (!instruction_->InnerSubroutines().empty()) {
    // If we see instruction with its subroutines for the first time, set ready
    // time immediately
    bool seen = false;
    for (auto& subroutine : instruction_->InnerSubroutines()) {
      if (subroutine->GetExecutionCount() !=
          scheduler_->GetFsm(subroutine.get()).GetExecutionCount()) {
        seen = true;
      }
    }
    if (!seen & !IsScheduled()) {
      SetTimeReady(scheduler_->GetCurrentTime());
    }
    SetScheduled();
    ASSIGN_OR_RETURN(Subroutine* subroutine, PickSubroutine());
    // Check if subroutine is not finished yet
    if (scheduler_->GetFsm(subroutine).GetExecutionCount() > 0 &&
        !scheduler_->GetFsm(subroutine).IsFinished()) {
      RETURN_IF_ERROR(scheduler_->GetFsm(subroutine).PrepareToSchedule());
    } else {
      // If we picked this subroutine, and it is finished, it means that
      // all subroutines are finished and parent instruction can be
      // marked finished
      scheduler_->InstructionFinished(instruction_,
                                      scheduler_->GetCurrentTime());
      return absl::OkStatus();
    }
  } else {
    // If we see Null opcode, which is ParaGraph internal opcode, we do not
    // schedule it through scheduler and just instantly execute it
    if (instruction_->GetOpcode() == Opcode::kNull) {
      SetTimeReady(scheduler_->GetCurrentTime());
      scheduler_->InstructionStarted(instruction_,
                                      scheduler_->GetCurrentTime());
      scheduler_->InstructionFinished(instruction_,
                                      scheduler_->GetCurrentTime());
    } else {
      SetReady();
      SetTimeReady(scheduler_->GetCurrentTime());
      scheduler_->EnqueueToScheduler(instruction_);
    }
  }
  return absl::OkStatus();
}

shim::StatusOr<Subroutine*> InstructionFsm::PickSubroutine() {
  Subroutine* picked_subroutine;
  if (instruction_->GetOpcode() == Opcode::kConditional) {
    RETURN_IF_FALSE(instruction_->InnerSubroutines().size() >= 2,
                    absl::InternalError) << "Conditional instruction " <<
        instruction_->GetName() << " should have at least 2 subroutines.";

    // Setup the weights for distribution
    std::vector<float> weights;
    for (auto& subroutine : instruction_->InnerSubroutines()) {
      weights.push_back(subroutine->GetExecutionProbability());
    }
    // Create the distribution with the weights above
    std::discrete_distribution<uint64_t> dist(weights.begin(), weights.end());
    picked_subroutine = instruction_->InnerSubroutines().at(
        dist(scheduler_->prng_)).get();
  } else if (instruction_->GetOpcode() == Opcode::kWhile) {
    RETURN_IF_FALSE(instruction_->InnerSubroutines().size() == 2,
                    absl::InternalError) << "While instruction " <<
        instruction_->GetName() << " should have exactly 2 subroutines.";
    // Reset state if iteration of loop cycle is finished, next available
    auto body_subroutine = instruction_->InnerSubroutines().at(0).get();
    auto condition_subroutine = instruction_->InnerSubroutines().at(1).get();
    if (scheduler_->GetFsm(body_subroutine).IsFinished() &&
        scheduler_->GetFsm(condition_subroutine).IsFinished() &&
        scheduler_->GetFsm(condition_subroutine).GetExecutionCount() > 0) {
      // If while wasn't executed yet, meaning its a first iteration, flag it
      // and  set the start time as the start time of the earliest instruction
      // in the loop.
      bool first_encounter = GetClockTime() == 0;
      double start_time = scheduler_->GetCurrentTime();
      // Increment while execution time every iteration
      for (auto& subroutine : instruction_->InnerSubroutines()) {
        for (auto& nested_instr : subroutine->Instructions()) {
          start_time = std::min(
              start_time,
              scheduler_->GetFsm(nested_instr.get()).GetTimeStarted());
          SetClockTime(GetClockTime() +
              scheduler_->GetFsm(nested_instr.get()).GetClockTime());
        }
      }
      if (first_encounter) {
        SetTimeStarted(start_time);
      }
      scheduler_->GetFsm(body_subroutine).Reset(false);
      scheduler_->GetFsm(condition_subroutine).Reset(false);
    } else if (scheduler_->GetFsm(body_subroutine).IsFinished() &&
        scheduler_->GetFsm(condition_subroutine).IsFinished() &&
        scheduler_->GetFsm(condition_subroutine).GetExecutionCount() == 0) {
      SetWallTime(scheduler_->GetCurrentTime() - GetTimeStarted());
    }
    if (!scheduler_->GetFsm(body_subroutine).IsFinished()) {
      picked_subroutine = body_subroutine;
    } else {
      picked_subroutine = condition_subroutine;
    }
  } else if (instruction_->GetOpcode() == Opcode::kCall) {
    for (auto& subroutine : instruction_->InnerSubroutines()) {
      picked_subroutine = subroutine.get();
      if (!scheduler_->GetFsm(picked_subroutine).IsFinished() &&
          scheduler_->GetFsm(picked_subroutine).GetExecutionCount() > 0) {
        break;
      }
    }
  } else {
    // Only kConditional, kWhile, and kCall should have more than one subroutine
    RETURN_IF_FALSE(instruction_->InnerSubroutines().size() <= 1,
                    absl::InternalError) << "Instruction " <<
        instruction_->GetName() <<
        " should have not more than 1 subroutine.";
    picked_subroutine = instruction_->InnerSubroutines().at(0).get();
  }
  return picked_subroutine;
}

}  // namespace paragraph


text:
-- MySQL dump 10.13  Distrib 5.7.12, for Win64 (x86_64)
--
-- Host: localhost    Database: test
-- ------------------------------------------------------
-- Server version	5.5.5-10.1.16-MariaDB

/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;

--
-- Table structure for table `articles`
--

DROP TABLE IF EXISTS `articles`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `articles` (
  `ID` int(11) NOT NULL,
  `TAG` int(11) NOT NULL,
  `TEXT` mediumtext NOT NULL,
  `IMAGE` text,
  PRIMARY KEY (`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Dumping data for table `articles`
--

LOCK TABLES `articles` WRITE;
/*!40000 ALTER TABLE `articles` DISABLE KEYS */;
INSERT INTO `articles` VALUES (1,1,'Today is a nice day. This is the very first day of the Summer Vocation! I can feel the wind, the sun and everything good in this world. Today I am going to the beach to enjoy the sunshine, the sea and the beautiful girls!','database/summer.jpg'),(2,2,'CodeIgniter is a very useful framework. It is very friendly for the former user of java like me and provides many features which are easy to use',NULL),(3,2,'Any software application requires some effort to learn. The workers have done their best to minimize the learning curve while making the process as enjoyable as possible. I am really thankful of them.','database/coding.jpg'),(4,3,'Today I have tried to make a delicious Chinese traditional meal. It is really tasty. I invited some of my friends to have this dish with me. They all praised about this dish and some of my friends even asked me to teach them! I love this dish.','database/meat.jpg');
/*!40000 ALTER TABLE `articles` ENABLE KEYS */;
UNLOCK TABLES;
/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;

/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;

-- Dump completed on 2016-12-24 13:55:44


text:
namespace Google.Cloud.VMMigration.V1.Snippets
{
    // [START vmmigration_v1_generated_VmMigration_ListMigratingVms_sync_flattened]
    using Google.Api.Gax;
    using Google.Cloud.VMMigration.V1;
    using System;

    public sealed partial class GeneratedVmMigrationClientSnippets
    {
        /// <summary>Snippet for ListMigratingVms</summary>
        /// <remarks>
        /// This snippet has been automatically generated and should be regarded as a code template only.
        /// It will require modifications to work:
        /// - It may require correct/in-range values for request initialization.
        /// - It may require specifying regional endpoints when creating the service client as shown in
        ///   https://cloud.google.com/dotnet/docs/reference/help/client-configuration#endpoint.
        /// </remarks>
        public void ListMigratingVms()
        {
            // Create client
            VmMigrationClient vmMigrationClient = VmMigrationClient.Create();
            // Initialize request argument(s)
            string parent = "projects/[PROJECT]/locations/[LOCATION]/sources/[SOURCE]";
            // Make the request
            PagedEnumerable<ListMigratingVmsResponse, MigratingVm> response = vmMigrationClient.ListMigratingVms(parent);

            // Iterate over all response items, lazily performing RPCs as required
            foreach (MigratingVm item in response)
            {
                // Do something with each item
                Console.WriteLine(item);
            }

            // Or iterate over pages (of server-defined size), performing one RPC per page
            foreach (ListMigratingVmsResponse page in response.AsRawResponses())
            {
                // Do something with each page of items
                Console.WriteLine("A page of results:");
                foreach (MigratingVm item in page)
                {
                    // Do something with each item
                    Console.WriteLine(item);
                }
            }

            // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
            int pageSize = 10;
            Page<MigratingVm> singlePage = response.ReadPage(pageSize);
            // Do something with the page of items
            Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
            foreach (MigratingVm item in singlePage)
            {
                // Do something with each item
                Console.WriteLine(item);
            }
            // Store the pageToken, for when the next page is required.
            string nextPageToken = singlePage.NextPageToken;
        }
    }
    // [END vmmigration_v1_generated_VmMigration_ListMigratingVms_sync_flattened]
}


text:
layout: page
title: Chambers Llc. Dinner
date: 2016-05-24
author: Nicholas Sutton
tags: weekly links, java
status: published
summary: Nam dapibus iaculis leo vitae tristique. Phasellus.
banner: images/banner/leisure-01.jpg
booking:
  startDate: 01/11/2019
  endDate: 01/12/2019
  ctyhocn: AUSRKHX
  groupCode: CLD
published: true
---
Nam pretium nunc facilisis, ultricies augue nec, iaculis magna. Mauris porta risus diam, in bibendum lacus mattis quis. Morbi vel eros ut ante scelerisque malesuada fringilla nec ipsum. Maecenas bibendum, elit id tincidunt auctor, leo lorem viverra nunc, eu auctor quam odio at justo. Proin rhoncus tellus vel lectus varius ornare. Duis non leo posuere, convallis orci et, semper erat. Aliquam varius, sapien vitae laoreet interdum, nunc ex dictum purus, vitae fermentum velit felis eget diam. Fusce sed odio risus.

* Proin accumsan diam placerat diam tempor, a bibendum nisi rutrum
* Curabitur sit amet eros aliquam dolor congue lacinia
* In mollis dui in eros condimentum sollicitudin a nec urna
* Duis porttitor nisi in sapien scelerisque consequat.

Phasellus ac dictum velit. Sed bibendum orci sit amet nisi euismod sodales. Duis quis lorem pretium, fringilla turpis eget, ornare ante. Vestibulum pharetra est justo. Praesent fringilla metus nulla, a tempus sem pretium sit amet. Pellentesque non sagittis risus. Sed sapien leo, consectetur nec laoreet et, faucibus vitae turpis. Sed fringilla felis eros, a gravida libero convallis a. Aenean laoreet sodales nisi, eu mattis lorem hendrerit nec. Mauris ut lorem eu turpis vulputate dapibus vel vulputate justo. Ut eget nisi risus. Nulla ullamcorper, elit ac elementum lobortis, mi nulla iaculis sapien, nec imperdiet purus velit eget elit. Vivamus pharetra ornare ipsum in commodo. Suspendisse porttitor dapibus lectus, sit amet aliquam odio vehicula non. Nunc lorem nibh, varius in erat sit amet, bibendum tempus justo. Phasellus faucibus nunc posuere hendrerit dictum.


text:
.class final Landroid/app/RemoteInput$1;
.super Ljava/lang/Object;
.source "RemoteInput.java"

# interfaces
.implements Landroid/os/Parcelable$Creator;

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Landroid/app/RemoteInput;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x8
    name = null
.end annotation

.annotation system Ldalvik/annotation/Signature;
    value = {
        "Ljava/lang/Object;",
        "Landroid/os/Parcelable$Creator",
        "<",
        "Landroid/app/RemoteInput;",
        ">;"
    }
.end annotation

# direct methods
.method constructor <init>()V
    .locals 0

    .prologue
    .line 300
    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    return-void
.end method

# virtual methods
.method public createFromParcel(Landroid/os/Parcel;)Landroid/app/RemoteInput;
    .locals 2
    .param p1, "in"    # Landroid/os/Parcel;

    .prologue
    .line 303
    new-instance v0, Landroid/app/RemoteInput;

    const/4 v1, 0x0

    invoke-direct {v0, p1, v1}, Landroid/app/RemoteInput;-><init>(Landroid/os/Parcel;Landroid/app/RemoteInput$1;)V

    return-object v0
.end method

.method public bridge synthetic createFromParcel(Landroid/os/Parcel;)Ljava/lang/Object;
    .locals 1

    .prologue
    .line 300
    invoke-virtual {p0, p1}, Landroid/app/RemoteInput$1;->createFromParcel(Landroid/os/Parcel;)Landroid/app/RemoteInput;

    move-result-object v0

    return-object v0
.end method

.method public newArray(I)[Landroid/app/RemoteInput;
    .locals 1
    .param p1, "size"    # I

    .prologue
    .line 308
    new-array v0, p1, [Landroid/app/RemoteInput;

    return-object v0
.end method

.method public bridge synthetic newArray(I)[Ljava/lang/Object;
    .locals 1

    .prologue
    .line 300
    invoke-virtual {p0, p1}, Landroid/app/RemoteInput$1;->newArray(I)[Landroid/app/RemoteInput;

    move-result-object v0

    return-object v0
.end method


text:
FROM gcr.io/oss-fuzz-base/base-builder
RUN apt-get update && apt-get install -y make autoconf automake libtool cmake
RUN git clone --depth 1 https://github.com/libgit2/libgit2 libgit2
WORKDIR libgit2

COPY build.sh $SRC/