text:
<?php
namespace Platformsh\Cli\Command\Environment;

use Platformsh\Cli\Command\PlatformCommand;
use Platformsh\Cli\Helper\GitHelper;
use Platformsh\Cli\Helper\ShellHelper;
use Platformsh\Cli\Local\LocalBuild;
use Platformsh\Cli\Local\LocalProject;
use Platformsh\Cli\Util\ActivityUtil;
use Platformsh\Client\Model\Environment;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;

class EnvironmentBranchCommand extends PlatformCommand
{

    protected function configure()
    {
        $this
          ->setName('environment:branch')
          ->setAliases(array('branch'))
          ->setDescription('Branch an environment')
          ->addArgument(
            'name',
            InputArgument::OPTIONAL,
            'The name of the new environment. For example: "Sprint 2"'
          )
          ->addArgument('parent', InputArgument::OPTIONAL, 'The parent of the new environment')
          ->addOption(
            'force',
            null,
            InputOption::VALUE_NONE,
            "Create the new environment even if the branch cannot be checked out locally"
          )
          ->addOption(
            'no-wait',
            null,
            InputOption::VALUE_NONE,
            'Do not wait for the Platform.sh branch to be created'
          )
          ->addOption(
            'build',
            null,
            InputOption::VALUE_NONE,
            "Build the new environment locally"
          );
        $this->addProjectOption()
             ->addEnvironmentOption();
        $this->addExample('Create a new branch "sprint-2", based on "develop"', 'sprint-2 develop');
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $this->envArgName = 'parent';
        $this->validateInput($input, true);
        $selectedProject = $this->getSelectedProject();

        $branchName = $input->getArgument('name');
        if (empty($branchName)) {
            if ($input->isInteractive()) {
                // List environments.
                return $this->runOtherCommand(
                  'environments',
                  array('--project' => $selectedProject->id)
                );
            }
            $this->stdErr->writeln("<error>You must specify the name of the new branch.</error>");

            return 1;
        }

        $machineName = Environment::sanitizeId($branchName);
        $environmentId = $this->getSelectedEnvironment()['id'];

        if ($machineName == $environmentId) {
            $this->stdErr->writeln("<comment>Already on $machineName</comment>");

            return 1;
        }

        if ($environment = $this->getEnvironment($machineName, $selectedProject)) {
            $checkout = $this->getHelper('question')
                             ->confirm(
                               "The environment <comment>$machineName</comment> already exists. Check out?",
                               $input,
                               $this->stdErr
                             );
            if ($checkout) {
                return $this->runOtherCommand(
                  'environment:checkout',
                  array('id' => $environment->id)
                );
            }

            return 1;
        }

        if (!$this->getSelectedEnvironment()
                  ->operationAvailable('branch')
        ) {
            $this->stdErr->writeln(
              "Operation not available: The environment <error>$environmentId</error> can't be branched."
            );

            return 1;
        }

        $force = $input->getOption('force');

        $projectRoot = $this->getProjectRoot();
        if (!$projectRoot && $force) {
            $this->stdErr->writeln(
              "<comment>This command was run from outside your local project root, the new Platform.sh branch cannot be checked out in your local Git repository."
              . " Make sure to run 'platform checkout' or 'git checkout' in your repository directory to switch to the branch you are expecting.</comment>"
            );
            $local_error = true;
        } elseif (!$projectRoot) {
            $this->stdErr->writeln("<error>You must run this command inside the project root, or specify --force.</error>");

            return 1;
        }

        $selectedEnvironment = $this->getSelectedEnvironment();

        $this->stdErr->writeln(
          "Creating a new environment <info>$branchName</info>, branched from <info>{$selectedEnvironment['title']}</info>"
        );

        $activity = $selectedEnvironment->branch($branchName, $machineName);

        // Clear the environments cache, as branching has started.
        $this->clearEnvironmentsCache($selectedProject);

        if ($projectRoot) {
            $gitHelper = new GitHelper(new ShellHelper($this->stdErr));
            $gitHelper->setDefaultRepositoryDir($projectRoot . '/' . LocalProject::REPOSITORY_DIR);

            // If the Git branch already exists locally, just check it out.
            $existsLocally = $gitHelper->branchExists($machineName);
            if ($existsLocally) {
                $this->stdErr->writeln("Checking out <info>$machineName</info> locally");
                if (!$gitHelper->checkOut($machineName)) {
                    $this->stdErr->writeln('<error>Failed to check out branch locally: ' . $machineName . '</error>');
                    $local_error = true;
                    if (!$force) {
                        return 1;
                    }
                }
            } else {
                // Create a new branch, using the current or specified environment as the parent if it exists locally.
                $parent = $this->getSelectedEnvironment()['id'];
                if (!$gitHelper->branchExists($parent)) {
                    $parent = null;
                }
                $this->stdErr->writeln("Creating local branch <info>$machineName</info>");
                if (!$gitHelper->checkOutNew($machineName, $parent)) {
                    $this->stdErr->writeln('<error>Failed to create branch locally: ' . $machineName . '</error>');
                    $local_error = true;
                    if (!$force) {
                        return 1;
                    }
                }
            }
        }

        $remoteSuccess = true;
        if (!$input->getOption('no-wait')) {
            $remoteSuccess = ActivityUtil::waitAndLog(
              $activity,
              $this->stdErr,
              "The environment <info>$branchName</info> has been branched.",
              '<error>Branching failed</error>'
            );

            // Clear the environments cache again.
            $this->clearEnvironmentsCache($selectedProject);
        }

        $build = $input->getOption('build');
        if (empty($local_error) && $build && $projectRoot) {
            // Build the new branch.
            try {
                $buildSettings = array(
                  'environmentId' => $machineName,
                  'verbosity' => $output->getVerbosity(),
                );
                $builder = new LocalBuild($buildSettings, $output);
                $builder->buildProject($projectRoot);
            } catch (\Exception $e) {
                $this->stdErr->writeln("<comment>The new branch could not be built: \n" . $e->getMessage() . "</comment>");

                return 1;
            }
        }

        $this->clearEnvironmentsCache();

        return $remoteSuccess ? 0 : 1;
    }
}


text:
package colsetup

import (
	"encoding/json"
	"html/template"
	"log"
	"net/http"

	"github.com/icza/repmastered/parser"
	"github.com/icza/repmastered/settings"
	"github.com/icza/repmastered/ui/pages/repfolders/rfparams"
	"github.com/icza/repmastered/ui/uireg"
)

const (
	// paramEditedColsetup is the name of the edited colsetup param
	paramEditedColsetup = "editedColsetup"

	// paramRestoreDefault is the param name to signal restoring default colsetup
	paramRestoreDefault = "restoreDefault"

	// paramSave is the param name to signal save
	paramSave = "save"
)

func init() {
	page := &uireg.Page{
		Name:  uireg.PgColSetup,
		Title: "Column Setup",
		Class: "i-fEditColumn",
		Logic: colSetupLogic,
	}
	uireg.RegisterPage(page)
}

// colSetupLogic contains logic for the Column Setup page.
func colSetupLogic(ctx *uireg.PgCtx) {
	name := ctx.R.FormValue(rfparams.RepFolder)
	if name == "" {
		ctx.ErrorMsg = "Missing Replay Folder name parameter! Go back to the " +
			ctx.GetPage(uireg.PgRepFolders).Link + " page."
		return
	}

	rf := settings.RepFolderByName(name)
	if rf == nil {
		ctx.ErrorMsg = `Invalid Replay Folder name: <span class="code">` + template.HTML(name) +
			"</span>! Go back to the " + ctx.GetPage(uireg.PgRepFolders).Link + " page."
		return
	}

	parsr := parser.Get(rf.ParserName)

	// check if only table is needed and parse edited colsetup:
	var colsetup []string
	tableOnly := false
	editedColsetup := ctx.R.FormValue(paramEditedColsetup)
	if editedColsetup != "" {
		if err := json.Unmarshal([]byte(editedColsetup), &colsetup); err != nil {
			log.Printf("Invalid colsetup (%s): %v", editedColsetup, err)
			http.Error(ctx.W, "Invalid colsetup!", http.StatusBadRequest)
			return
		}
	}
	if ctx.R.FormValue(paramRestoreDefault) != "" {
		colsetup = parsr.ColSetupSetting().Default
	}
	if colsetup != nil {
		tableOnly = true
	} else {
		colsetup = parsr.ColSetupSetting().Get()
		ctx.ParentLinks = []template.HTML{
			ctx.GetPage(uireg.PgRepFolders).BareLink,
			ctx.GetPage(uireg.PgRepBrowser).LinkWithQuery(ctx.R.URL.RawQuery),
		}
	}

	cols := parsr.Meta().ColsByNames(colsetup)
	// cols is optionally filtered as it only contains valid, supported columns. Use that:
	colsetup = make([]string, len(cols))
	for i, col := range cols {
		colsetup[i] = col.Name
	}

	if ctx.R.FormValue(paramSave) != "" {
		// Check authorization (guests cannot edit)!
		if !ctx.Admin {
			http.Error(ctx.W, "Not authorized (guest users cannot edit)!", http.StatusForbidden)
			return
		}
		// Perform saving:
		switch {
		case len(colsetup) == 0:
			ctx.ErrorMsg = "You must select at least 1 column!"
		default:
			ctx.InfoMsg = "Column setup saved successfully!"
			parsr.ColSetupSetting().Set(colsetup)
		}
	}

	// All column names, starting with elements of colsetup:
	colNames := make([]string, len(colsetup), len(parsr.Meta().SupportedCols))
	copy(colNames, colsetup)

	for _, c := range parsr.Meta().SupportedCols {
		found := false
		for _, name := range colsetup {
			if name == c.Name {
				found = true
				break
			}
		}
		if !found {
			cols = append(cols, c)
			colNames = append(colNames, c.Name)
		}
	}

	ctx.Data = map[string]interface{}{
		"TableOnly":           tableOnly,
		"ParamEditedColsetup": paramEditedColsetup,
		"ParamRestoreDefault": paramRestoreDefault,
		"ParamSave":           paramSave,
		"Parser":              parsr,
		"RepFolder":           rf,
		"ColNames":            colNames,
		"Cols":                cols,
		"NumSelected":         len(colsetup),
	}
}

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
R-Index
</TITLE>

<META NAME="date" CONTENT="2011-01-03">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../stylesheet.css" TITLE="Style">

      Overview
      Package
      Class
      Use
      Tree
      Deprecated
    Index
      Help

 PREV LETTER
 NEXT LETTER

  FRAMES
 NO FRAMES

  All Classes

A B C D E F G I M O P R S T U V

R

RadialDistanceOrder - Class in toxi.sim.dla
This comparator sorts segments based on their mid-point's distance to a given
 origin point.
RadialDistanceOrder() -
Constructor for class toxi.sim.dla.RadialDistanceOrder

RadialDistanceOrder(Vec3D, boolean) -
Constructor for class toxi.sim.dla.RadialDistanceOrder

randomize() -
Method in interface toxi.sim.automata.CARule

randomize() -
Method in class toxi.sim.automata.CARule2D

randomize() -
Method in class toxi.sim.automata.CAWolfram1D

removeListener(DLAEventListener) -
Method in class toxi.sim.dla.DLA

reorientate() -
Method in class toxi.sim.dla.DLAParticle

reset() -
Method in class toxi.sim.automata.CAMatrix

Clears the matrix and resets the generation counter.

reset() -
Method in class toxi.sim.dla.DLA

reset() -
Method in class toxi.sim.dla.DLAGuideLines

reset() -
Method in class toxi.sim.fluids.FluidSolver

Reset the datastructures.

reset() -
Method in class toxi.sim.grayscott.GrayScott

Resets the simulation matrix to an initial, clean state.

      Overview
      Package
      Class
      Use
      Tree
      Deprecated
    Index
      Help

 PREV LETTER
 NEXT LETTER

  FRAMES
 NO FRAMES

  All Classes

A B C D E F G I M O P R S T U V


text:
// Copyright Project Harbor Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/*
  [
    {
        "project_id": 1,
        "owner_id": 1,
        "name": "library",
        "creation_time": "2017-02-10T07:57:56Z",
        "creation_time_str": "",
        "deleted": 0,
        "owner_name": "",
        "public": 1,
        "togglable": true,
        "update_time": "2017-02-10T07:57:56Z",
        "current_user_role_id": 1,
        "repo_count": 0
    }
  ]
*/
export class Project {
    project_id: number;
    owner_id: number;
    name: string;
    creation_time: Date;
    creation_time_str: string;
    deleted: number;
    owner_name: string;
    togglable: boolean;
    update_time: Date;
    current_user_role_id: number;
    repo_count: number;
    chart_count: number;
    has_project_admin_role: boolean;
    is_member: boolean;
    role_name: string;
    metadata: {
      public: string | boolean;
      enable_content_trust: string | boolean;
      prevent_vul: string | boolean;
      severity: string;
      auto_scan: string | boolean;
    };
    constructor () {
      this.metadata = <any>{};
      this.metadata.public = false;
    }
}


text:
CoreParse
=========

CoreParse is a parsing library for Mac OS X and iOS.  It supports a wide range of grammars thanks to its shift/reduce parsing schemes.  Currently CoreParse supports SLR, LR(1) and LALR(1) parsers.

For full documentation see http://beelsebob.github.com/CoreParse.

Why Should You use CoreParse
----------------------------

You may wonder why and/or when you should use CoreParse.  There are already a number of parsers available in the wild, why should you use this one?

* Compared to ParseKit:
  * CoreParse supports more languages (LR(1) languages cover all LL(1) languages and more).  In practice, LALR(1) grammars cover most useful languages.
  * CoreParse produces faster parsers.
  * CoreParse parsers and tokenisers can be archived using NSKeyedArchivers to save regenerating them each time your application runs.
  * CoreParse's parsing algorithm is not recursive, meaning it could theoretically deal with much larger hierarchies of language structure without blowing the stack.
* Compared to lex/yacc or flex/bison:
  * While I have no explicitly benchmarked, I would expect parsers produced by lex/yacc or flex/bison to be faster than CoreParse ones.
  * CoreParse does not _require_ you to compile your parser before you start (though it is recommended).
  * CoreParse provides allows you to specify grammars right in your Objective-C source, rather than needing another language, which intermixes C/Obj-C.
  * CoreParse does not use global state, multiple parser instances can be run in parallel (or the same parser instance can parse multiple token streams in parallel).

Where is CoreParse Already Used?
--------------------------------

CoreParse is already used in a major way in at least two projects:

* Francis Chong uses it in his [CSS selector convertor](https://github.com/siuying/CSSSelectorConverter) to parse CSS3
* Matt Mower uses it in his [statec](https://github.com/mmower/statec) project to parse his state machine specifications.
* I use it in [OpenStreetPad](https://github.com/beelsebob/OpenStreetPad/) to parse MapCSS.

If you know of any other places it's been used, please feel free to get in touch.

Parsing Guide
=============

CoreParse is a powerful framework for tokenising and parsing.  This document explains how to create a tokeniser and parser from scratch, and how to use those parsers to create your model data structures for you.  We will follow the same example throughout this document.  This will deal with parsing a simple numerical expression and computing the result.

gavineadie has implemented this entire example, to see full working source see https://github.com/beelsebob/ParseTest/.

Tokenisation
------------

CoreParse's tokenisation class is CPTokeniser.  To specify how tokens are constructed you must add *token recognisers* in order of precidence to the tokeniser.

Our example language will involve several symbols, numbers, whitespace, and comments.  We add these to the tokeniser:

```objective-c
CPTokeniser *tokeniser = [[[CPTokeniser alloc] init] autorelease];
[tokeniser addTokenRecogniser:[CPNumberRecogniser numberRecogniser]];
[tokeniser addTokenRecogniser:[CPWhiteSpaceRecogniser whiteSpaceRecogniser]];
[tokeniser addTokenRecogniser:[CPQuotedRecogniser quotedRecogniserWithStartQuote:@"/*" endQuote:@"*/" name:@"Comment"]];
[tokeniser addTokenRecogniser:[CPKeywordRecogniser recogniserForKeyword:@"+"]];
[tokeniser addTokenRecogniser:[CPKeywordRecogniser recogniserForKeyword:@"-"]];
[tokeniser addTokenRecogniser:[CPKeywordRecogniser recogniserForKeyword:@"*"]];
[tokeniser addTokenRecogniser:[CPKeywordRecogniser recogniserForKeyword:@"/"]];
[tokeniser addTokenRecogniser:[CPKeywordRecogniser recogniserForKeyword:@"("]];
[tokeniser addTokenRecogniser:[CPKeywordRecogniser recogniserForKeyword:@")"]];
```

Note that the comment tokeniser is added before the keyword recogniser for the divide symbol.  This gives it higher precidence, and means that the first slash of a comment will not be recognised as a division.

Next, we add ourself as a delegate to the tokeniser.  We implement the tokeniser delegate methods in such a way that whitespace tokens and comments, although consumed, will not appear in the tokeniser's output:

```objective-c
- (BOOL)tokeniser:(CPTokeniser *)tokeniser shouldConsumeToken:(CPToken *)token
{
    return YES;
}

- (void)tokeniser:(CPTokeniser *)tokeniser requestsToken:(CPToken *)token pushedOntoStream:(CPTokenStream *)stream
{
    if (![token isWhiteSpaceToken] && ![[token name] isEqualToString:@"Comment"])
    {
        [stream pushToken:token];
    }
}
```

We can now invoke our tokeniser.

```objective-c
CPTokenStream *tokenStream = [tokeniser tokenise:@"5 + (2.0 / 5.0 + 9) * 8"];
```

Parsing
-------

We construct parsers by specifying their grammar.  We can construct a grammar simply using a simple BNF like language.  Note the syntax tag@<NonTerminal> can be read simply as <NonTerminal>, the tag can be used later to quickly extract values from the parsed result:

```objective-c
NSString *expressionGrammar =
    @"Expression ::= term@<Term>   | expr@<Expression> op@<AddOp> term@<Term>;"
    @"Term       ::= fact@<Factor> | fact@<Factor>     op@<MulOp> term@<Term>;"
    @"Factor     ::= num@'Number' | '(' expr@<Expression> ')';"
    @"AddOp      ::= '+' | '-';"
    @"MulOp      ::= '*' | '/';";
NSError *err;
CPGrammar *grammar = [CPGrammar grammarWithStart:@"Expression" backusNaurForm:expressionGrammar error:&err];
if (nil == grammar)
{
    NSLog(@"Error creating grammar:");
    NSLog(@"%@", err);
}
else
{
    CPParser *parser = [CPLALR1Parser parserWithGrammar:grammar];
    [parser setDelegate:self];
    ...
}
```

When a rule is matched by the parser, the `initWithSyntaxTree:` method will be called on a new instance of the apropriate class.  If no such class exists the parser delegate's `parser:didProduceSyntaxTree:` method is called.  To deal with this cleanly, we implement 3 classes: Expression; Term; and Factor.  AddOp and MulOp non-terminals are dealt with by the parser delegate.  Here we see the initWithSyntaxTree: method for the Expression class, these methods are similar for Term and Factor:

```objective-c
- (id)initWithSyntaxTree:(CPSyntaxTree *)syntaxTree
{
    self = [self init];

    if (nil != self)
    {
        Term       *t = [syntaxTree valueForTag:@"term"];
        Expression *e = [syntaxTree valueForTag:@"expr"];

        if (nil == e)
        {
            [self setValue:[t value]];
        }
        else if ([[syntaxTree valueForTag:@"op"] isEqualToString:@"+"])
        {
            [self setValue:[e value] + [t value]];
        }
        else
        {
            [self setValue:[e value] - [t value]];
        }
    }

    return self;
}
```

We must also implement the delegate's method for dealing with AddOps and MulOps:

```objective-c
- (id)parser:(CPParser *)parser didProduceSyntaxTree:(CPSyntaxTree *)syntaxTree
{
    return [(CPKeywordToken *)[syntaxTree childAtIndex:0] keyword];
}
```

We can now parse the token stream we produced earlier:

```objective-c
NSLog(@"%f", [(Expression *)[parser parse:tokenStream] value]);
```

Which outputs:

    80.2

Best Practices
--------------

CoreParse offers three types of parser - SLR, LR(1) and LALR(1):
* SLR parsers cover the smallest set of languages, and are faster to generate than LALR(1) parsers.
* LR(1) parsers consume a lot of RAM, and are slow, but cover the largest set of languages.
* LALR(1) parsers are as fast as SLR parsers to run, but slower to generate, they cover almost as many languages as LR(1) parsers.

It is recommended that you start with an SLR parser (unless you know better), and when a parser cannot be generated for your grammar, move onto an LALR(1) parser.  LR(1) parsers are not really recommended at all, though may be useful in extreme circumstances.

It is recommended that if you have a significant grammar that requires an LALR(1) parser, you should use NSKeyedArchiving to archive the parser to a file.  You should then read this file, and unarchive it when your application runs to save generating the parser every time it runs, as parser generation can take some time.


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.

using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Structure;
using Microsoft.CodeAnalysis.Structure;
using Roslyn.Test.Utilities;
using Xunit;

namespace Microsoft.CodeAnalysis.CSharp.Structure.Outlining
{
    public class NamespaceDeclarationStructureTests : AbstractCSharpSyntaxNodeStructureTests<NamespaceDeclarationSyntax>
    {
        internal override AbstractSyntaxStructureProvider CreateProvider() => new NamespaceDeclarationStructureProvider();

        [Fact, Trait(Traits.Feature, Traits.Features.Outlining)]
        public async Task TestNamespace()
        {
            const string code = @"
class C
{
    {|hint:$$namespace N{|textspan:
    {
    }|}|}
}";

            await VerifyBlockSpansAsync(code,
                Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: false));
        }

        [Fact, Trait(Traits.Feature, Traits.Features.Outlining)]
        public async Task TestNamespaceWithLeadingComments()
        {
            const string code = @"
class C
{
    {|span1:// Goo
    // Bar|}
    {|hint2:$$namespace N{|textspan2:
    {
    }|}|}
}";

            await VerifyBlockSpansAsync(code,
                Region("span1", "// Goo ...", autoCollapse: true),
                Region("textspan2", "hint2", CSharpStructureHelpers.Ellipsis, autoCollapse: false));
        }

        [Fact, Trait(Traits.Feature, Traits.Features.Outlining)]
        public async Task TestNamespaceWithNestedUsings()
        {
            const string code = @"
class C
{
    {|hint1:$$namespace N{|textspan1:
    {
        {|hint2:using {|textspan2:System;
        using System.Linq;|}|}
    }|}|}
}";

            await VerifyBlockSpansAsync(code,
                Region("textspan1", "hint1", CSharpStructureHelpers.Ellipsis, autoCollapse: false),
                Region("textspan2", "hint2", CSharpStructureHelpers.Ellipsis, autoCollapse: true));
        }

        [Fact, Trait(Traits.Feature, Traits.Features.Outlining)]
        public async Task TestNamespaceWithNestedUsingsWithLeadingComments()
        {
            const string code = @"
class C
{
    {|hint1:$$namespace N{|textspan1:
    {
        {|span2:// Goo
        // Bar|}
        {|hint3:using {|textspan3:System;
        using System.Linq;|}|}
    }|}|}
}";

            await VerifyBlockSpansAsync(code,
                Region("textspan1", "hint1", CSharpStructureHelpers.Ellipsis, autoCollapse: false),
                Region("span2", "// Goo ...", autoCollapse: true),
                Region("textspan3", "hint3", CSharpStructureHelpers.Ellipsis, autoCollapse: true));
        }

        [Fact, Trait(Traits.Feature, Traits.Features.Outlining)]
        public async Task TestNamespaceWithNestedComments()
        {
            const string code = @"
class C
{
    {|hint1:$$namespace N{|textspan1:
    {
        {|span2:// Goo
        // Bar|}
    }|}|}
}";

            await VerifyBlockSpansAsync(code,
                Region("textspan1", "hint1", CSharpStructureHelpers.Ellipsis, autoCollapse: false),
                Region("span2", "// Goo ...", autoCollapse: true));
        }
    }
}


text:
package com.dianping.cat.report.page.app.display;

import java.util.LinkedHashMap;
import java.util.Map;

public class DisplayCommand {

	private int m_id;

	private String m_name;

	private long m_count;

	private double m_sum;

	private double m_avg;

	private long m_errors;

	private double m_successRatio;

	private long m_requestSum;

	private double m_requestAvg;

	private long m_responseSum;

	private double m_responseAvg;

	private long m_transactionCount;

	private double m_transactionAvg;

	private double m_countComparison;

	private double m_avgComparison;

	private String m_domain;

	private String m_bu;

	private String m_department;

	private String m_title;

	private Map<String, DisplayCode> m_codes = new LinkedHashMap<String, DisplayCode>();

	public DisplayCommand(int id) {
		m_id = id;
	}

	public DisplayCommand addCode(DisplayCode code) {
		m_codes.put(code.getId(), code);
		return this;
	}

	public DisplayCode findCode(String id) {
		return m_codes.get(id);
	}

	public DisplayCode findOrCreateCode(String id) {
		DisplayCode code = m_codes.get(id);

		if (code == null) {
			synchronized (m_codes) {
				code = m_codes.get(id);

				if (code == null) {
					code = new DisplayCode(id);
					m_codes.put(id, code);
				}
			}
		}

		return code;
	}

	public double getAvg() {
		return m_avg;
	}

	public double getAvgComparison() {
		return m_avgComparison;
	}

	public String getBu() {
		return m_bu;
	}

	public Map<String, DisplayCode> getCodes() {
		return m_codes;
	}

	public long getCount() {
		return m_count;
	}

	public double getCountComparison() {
		return m_countComparison;
	}

	public String getDepartment() {
		return m_department;
	}

	public String getDomain() {
		return m_domain;
	}

	public long getErrors() {
		return m_errors;
	}

	public int getId() {
		return m_id;
	}

	public String getName() {
		return m_name;
	}

	public double getRequestAvg() {
		return m_requestAvg;
	}

	public long getRequestSum() {
		return m_requestSum;
	}

	public double getResponseAvg() {
		return m_responseAvg;
	}

	public long getResponseSum() {
		return m_responseSum;
	}

	public double getSuccessRatio() {
		return m_successRatio;
	}

	public double getSum() {
		return m_sum;
	}

	public String getTitle() {
		return m_title;
	}

	public double getTransactionAvg() {
		return m_transactionAvg;
	}

	public long getTransactionCount() {
		return m_transactionCount;
	}

	public DisplayCommand incCount() {
		m_count++;
		return this;
	}

	public DisplayCommand incCount(long count) {
		m_count += count;
		return this;
	}

	public DisplayCommand incErrors() {
		m_errors++;
		return this;
	}

	public DisplayCommand incErrors(long errors) {
		m_errors += errors;
		return this;
	}

	public DisplayCommand incRequestSum() {
		m_requestSum++;
		return this;
	}

	public DisplayCommand incRequestSum(long requestSum) {
		m_requestSum += requestSum;
		return this;
	}

	public DisplayCommand incResponseSum() {
		m_responseSum++;
		return this;
	}

	public DisplayCommand incResponseSum(long responseSum) {
		m_responseSum += responseSum;
		return this;
	}

	public DisplayCommand incSum() {
		m_sum++;
		return this;
	}

	public DisplayCommand incSum(double sum) {
		m_sum += sum;
		return this;
	}

	public void setAvg(double avg) {
		m_avg = avg;
	}

	public void setAvgComparison(double avgComparison) {
		m_avgComparison = avgComparison;
	}

	public void setBu(String bu) {
		m_bu = bu;
	}

	public void setCodes(Map<String, DisplayCode> codes) {
		m_codes = codes;
	}

	public void setCount(long count) {
		m_count = count;
	}

	public void setCountComparison(double countComparison) {
		m_countComparison = countComparison;
	}

	public void setDepartment(String department) {
		m_department = department;
	}

	public void setDomain(String domain) {
		m_domain = domain;
	}

	public void setErrors(long errors) {
		m_errors = errors;
	}

	public void setId(int id) {
		m_id = id;
	}

	public void setName(String name) {
		m_name = name;
	}

	public void setRequestAvg(double requestAvg) {
		m_requestAvg = requestAvg;
	}

	public void setRequestSum(long requestSum) {
		m_requestSum = requestSum;
	}

	public void setResponseAvg(double responseAvg) {
		m_responseAvg = responseAvg;
	}

	public void setResponseSum(long responseSum) {
		m_responseSum = responseSum;
	}

	public void setSuccessRatio(double successRatio) {
		m_successRatio = successRatio;
	}

	public void setSum(double sum) {
		m_sum = sum;
	}

	public void setTitle(String title) {
		m_title = title;
	}

	public void setTransactionAvg(double transactionAvg) {
		m_transactionAvg = transactionAvg;
	}

	public void setTransactionCount(long transactionCount) {
		m_transactionCount = transactionCount;
	}

}


text:
INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django.contrib.admin',
    'django.contrib.admindocs',

    'model_utils',
    'django_h5bp',
#apps
    'chat_parser',

#deploy

)


text:
/*
 * @author max
 */
package com.intellij.psi.stubs;

import com.intellij.psi.PsiElement;
import com.intellij.util.io.KeyDescriptor;
import org.jetbrains.annotations.NotNull;

public abstract class CharSequenceHashStubIndexExtension<Psi extends PsiElement> extends AbstractStubIndex<CharSequence, Psi> {

  @Override
  public int getVersion() {
    return 1;
  }

  @Override
  @NotNull
  public final KeyDescriptor<CharSequence> getKeyDescriptor() {
    return CharSequenceHashInlineKeyDescriptor.INSTANCE;
  }

  public boolean doesKeyMatchPsi(@NotNull CharSequence key, @NotNull Psi psi) {
    return true;
  }
}


text:
require('travis_build_service')
require('shell_build_service')

class CreateBuildService
  def execute(project, params)
    params = params.push_data if params.kind_of?(Build)

    before_sha = params[:before]
    sha = params[:checkout_sha] || params[:after]
    ref = params[:ref]

    return nil unless ref and sha

    if ref.include?('refs/heads/')
      type = 'heads'
      ref = ref.scan(/heads\/(.*)$/).flatten[0]
    elsif ref.include?('refs/tags/')
      type = 'tags'
      ref = ref.scan(/tags\/(.*)$/).flatten[0]
    else
      return nil # not supported other ref types
    end

    # hack: skip duplicate commits
    build_group = project.build_groups.tags.where(sha: sha, ref: ref).first
    if build_group
      if params[:ref_message]
        build_group.update_attributes(
          ref_message: params[:ref_message],
          build_method: project.build_method
        )
      end
      return build_group
    end

    return nil if project.skip_ref?(ref, type)

    data = {
        ref: ref,
        ref_type: type,
        sha: sha,
        before_sha: before_sha,
        ref_message: params[:ref_message],
        build_method: project.build_method,
        push_data: {
            before: params[:before],
            after: params[:after],
            ref: params[:ref],
            user_name: params[:user_name],
            repository: params[:repository],
            commits: params[:commits],
            total_commits_count: params[:total_commits_count]
      }
    }

    build_service(project.build_method).execute(project, data)
  end

  def detect_build_method(project)
    CreateBuildService.local_constants.each do |build_class|
      build_service = CreateBuildService.const_get(build_class).new
      return build_class.downcase if build_service.detected?(project)
    end
    nil
  end

  def build_end(build)
    build_service(build.project.build_method).build_end(build)
  end

  def build_service(build_method)
    CreateBuildService.const_get(build_method.capitalize).new
  end
end


text:
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using Octokit.Internal;

namespace Octokit
{
    /// <summary>
    /// Describes a new deployment status to create. Deployments are a request for a specific ref(branch,sha,tag) to
    /// be deployed.
    /// </summary>
    /// <remarks>
    /// API: https://developer.github.com/v3/repos/deployments/
    /// </remarks>
    [DebuggerDisplay("{DebuggerDisplay,nq}")]
    public class NewDeployment
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="NewDeployment"/> class.
        /// </summary>
        /// <param name="ref">The ref to deploy.</param>
        public NewDeployment(string @ref)
        {
            Ref = @ref;
        }

        /// <summary>
        /// The ref to deploy. This can be a branch, tag, or sha. (REQUIRED)
        /// </summary>
        public string Ref { get; private set; }

        /// <summary>
        /// Gets or sets the optional task used to specify a task to execute, e.g. deploy or deploy:migrations.
        /// Default: deploy
        /// </summary>
        /// <value>
        /// The task.
        /// </value>
        public DeployTask Task { get; set; }

        /// <summary>
        /// Merges the default branch into the requested deployment branch if true;
        /// Does nothing if false. (DEFAULT if not specified: True)
        /// </summary>
        public bool? AutoMerge { get; set; }

        /// <summary>
        /// Optional array of status contexts verified against commit status checks. If this property is null then
        /// all unique contexts will be verified before a deployment is created. To bypass checking entirely, set this
        /// to an empty collection. Defaults to all unique contexts (aka null).
        /// </summary>
        /// <value>
        /// The required contexts.
        /// </value>
        [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public Collection<string> RequiredContexts { get; set; }

        /// <summary>
        /// JSON payload with extra information about the deployment.
        /// </summary>
        public string Payload { get; set; }

        /// <summary>
        /// Optional name for the target deployment environment (e.g., production, staging, qa). Default: "production"
        /// </summary>
        /// <value>
        /// The environment.
        /// </value>
        public string Environment { get; set; }

        /// <summary>
        /// A short description of the deployment.
        /// </summary>
        public string Description { get; set; }

        internal string DebuggerDisplay
        {
            get
            {
                return string.Format(CultureInfo.InvariantCulture, "Description: {0}", Description);
            }
        }
    }

    /// <summary>
    /// The types of deployments tasks that are availabel.
    /// </summary>
    public enum DeployTask
    {
        /// <summary>
        /// Deploy everything (default)
        /// </summary>
        Deploy,

        /// <summary>
        /// Deploy migrations only.
        /// </summary>
        [Parameter(Value = "deploy:migrations")]
        DeployMigrations
    }
}


text:
layout: default
---

{% include header.html page='dongles' %}

Two Factor Auth (2FA) Dongles

      List of 2FA
      dongle providers and the platforms they support.

      Also see the list of sites offering 2FA.

      Add your own favorite by submitting a pull request on the
      GitHub repo.

Dongle

                    One Time Passwords (OTP)
                    Universal 2nd Factor (U2F)

              {% assign sorted_providers = site.data.providers.providers | sort: 'name' %}
              {% for provider in sorted_providers %}

                {% if provider.u2f or provider.otp %}

                    {% if provider.img %}

                    {% endif %}
                        {{ provider.name }}

                    {% if provider.otp %}

                    {% endif %}

                    {% if provider.u2f %}

                    {% endif %}

                {% endif %}
              {% endfor %}


text:
package com.frameworkset.platform.cms.statisticManage.entity;

import java.io.Serializable;

public class UserStatistic implements Serializable{
	private int userId;
	private String userName;
	private String userRealName;
	//用户状态
	private int userStatus;
	//所属角色
	private String role;
	//录稿篇数
	private int writeDocs=0;
	//审稿篇数
	private int auditDocs=0;
	//发稿篇数
	private int publishDocs=0;
	//使用率
	private float frequency=0;
	//总字数
	private int totalWords=0;
	//单价(元/千字)
	private float price=0;
	//稿酬
	private float payment=0;
	//机构ID
	private String org_id;
	public float getFrequency() {
		return frequency;
	}
	public void setFrequency(float frequency) {
		this.frequency = frequency;
	}
	public float getPrice() {
		return price;
	}
	public void setPrice(float price) {
		this.price = price;
	}
	public int getPublishDocs() {
		return publishDocs;
	}
	public void setPublishDocs(int publishDocs) {
		this.publishDocs = publishDocs;
	}
	public String getRole() {
		return role;
	}
	public void setRole(String role) {
		this.role = role;
	}
	public int getTotalWords() {
		return totalWords;
	}
	public void setTotalWords(int totalWords) {
		this.totalWords = totalWords;
	}
	public String getUserName() {
		return userName;
	}
	public void setUserName(String userName) {
		this.userName = userName;
	}
	public String getUserRealName() {
		return userRealName;
	}
	public void setUserRealName(String userRealName) {
		this.userRealName = userRealName;
	}
	public int getUserStatus() {
		return userStatus;
	}
	public void setUserStatus(int userStatus) {
		this.userStatus = userStatus;
	}
	public int getWriteDocs() {
		return writeDocs;
	}
	public void setWriteDocs(int writeDocs) {
		this.writeDocs = writeDocs;
	}
	public float getPayment() {
		return payment;
	}
	public void setPayment(float payment) {
		this.payment = payment;
	}
	public int getUserId() {
		return userId;
	}
	public void setUserId(int userId) {
		this.userId = userId;
	}
	public int getAuditDocs() {
		return auditDocs;
	}
	public void setAuditDocs(int auditDocs) {
		this.auditDocs = auditDocs;
	}
	public String getOrg_id() {
		return org_id;
	}
	public void setOrg_id(String org_id) {
		this.org_id = org_id;
	}
}


text:
<link rel='stylesheet' type='text/css' href='../defold.css'>

JSON

Manipulation of JSON data strings.

json.decode()

decode JSON from a string to a lua-table

Decode a string of JSON data into a Lua table.
A Lua error is raised for syntax errors.

PARAMETERS

json
string json data

RETURN

data -
table decoded json

EXAMPLES

Converting a string containing JSON data into a Lua table:

function init(self)
    local jsonstring = '{"persons":[{"name":"John Doe"},{"name":"Darth Vader"}]}'
    local data = json.decode(jsonstring)
    pprint(data)
end

Results in the following printout:

{
  persons = {
    1 = {
      name = John Doe,
    }
    2 = {
      name = Darth Vader,
    }
  }
}


text:
// Copyright 2020 Jon Skeet. All rights reserved.
// Use of this source code is governed by the Apache License 2.0,
// as found in the LICENSE.txt file.

using System.Text;

namespace CameraControl.Visca
{
    /// <summary>
    /// Packet within the VISCA protocol.
    /// </summary>
    internal readonly struct ViscaPacket
    {
        // VISCA packets can contain up to 16 bytes. It's simplest to represent those as two long values.
        private readonly long head;
        private readonly long tail;

        /// <summary>
        /// The text representation, cached for efficiency for commonly-used packets.
        /// </summary>
        private readonly string? text;

        /// <summary>
        /// The number of bytes in the packet, excluding the trailing 0xFF.
        /// </summary>
        public int Length { get; }

        private ViscaPacket(long head, long tail, int length, string? text) =>
            (this.head, this.tail, this.Length, this.text) = (head, tail, length, text);

        internal static ViscaPacket FromBytes(byte[] bytes, int start, int length) =>
            FromBytes(bytes, start, length, false);

        internal static ViscaPacket FromBytesWithPreformatting(params byte[] bytes) =>
            FromBytes(bytes, 0, bytes.Length, true);

        private static ViscaPacket FromBytes(byte[] bytes, int start, int length, bool preformatText)
        {
            Preconditions.CheckNotNull(bytes);
            // Start must be within the array
            Preconditions.CheckRange(start, 0, bytes.Length - 1);
            // Packets have 1-16 bytes
            Preconditions.CheckRange(length, 1, 16);
            // The end of the packet must be within the array
            Preconditions.CheckRange(length, 0, bytes.Length - start);

            long head = GetByteOrZero(0, 56) |
                GetByteOrZero(1, 48) |
                GetByteOrZero(2, 40) |
                GetByteOrZero(3, 32) |
                GetByteOrZero(4, 24) |
                GetByteOrZero(5, 16) |
                GetByteOrZero(6, 8) |
                GetByteOrZero(7, 0);

            long tail = GetByteOrZero(8, 56) |
                GetByteOrZero(9, 48) |
                GetByteOrZero(10, 40) |
                GetByteOrZero(11, 32) |
                GetByteOrZero(12, 24) |
                GetByteOrZero(13, 16) |
                GetByteOrZero(14, 8) |
                GetByteOrZero(15, 0);

            var unformatted = new ViscaPacket(head, tail, length, null);
            return preformatText ? new ViscaPacket(head, tail, length, unformatted.ToString()) : unformatted;

            long GetByteOrZero(int index, int shift) =>
                index >= length ? 0L : ((long) bytes[start + index]) << shift;
        }

        // TODO: Make this an indexer?
        internal byte GetByte(int index)
        {
            Preconditions.CheckRange(index, 0, Length);
            return index < 8
                ? (byte) (head >> (56 - (index * 8)))
                : (byte) (tail >> (120 - (index * 8)));
        }

        internal short GetInt16(int index)
        {
            Preconditions.CheckRange(index, 0, Length - 4);
            return (short) (
                (GetByte(index) << 12) |
                (GetByte(index + 1) << 8) |
                (GetByte(index + 2) << 4) |
                (GetByte(index + 3) << 0)
            );
        }

        public override string ToString()
        {
            if (text is not null)
            {
                return text;
            }
            var builder = new StringBuilder();
            for (int i = 0; i < Length; i++)
            {
                builder.AppendFormat("{0:x2}", GetByte(i));
                builder.Append('-');
            }
            builder.Length--;
            return builder.ToString();
        }
    }
}


text:
'use strict';

function foo() {}

exports.foo = foo;


text:
package home.smart.fly.animations.widget.clearbadge.impl;

import android.annotation.TargetApi;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Collections;
import java.util.List;

import home.smart.fly.animations.widget.clearbadge.Badger;
import home.smart.fly.animations.widget.clearbadge.ShortcutBadgeException;
import home.smart.fly.animations.widget.clearbadge.util.BroadcastHelper;
import home.smart.fly.animations.widget.clearbadge.util.CloseHelper;

/**
 * Created by NingSo on 2016/10/14.上午10:09
 *
 * @author: NingSo
 * Email: ningso.ping@gmail.com
 * <p>
 * OPPO R9 not supported
 * Version number 6 applies only to chat-type apps
 */

public class OPPOHomeBader implements Badger {

    private static final String PROVIDER_CONTENT_URI = "content://com.android.badge/badge";
    private static final String INTENT_ACTION = "com.oppo.unsettledevent";
    private static final String INTENT_EXTRA_PACKAGENAME = "pakeageName";
    private static final String INTENT_EXTRA_BADGE_COUNT = "number";
    private static final String INTENT_EXTRA_BADGE_UPGRADENUMBER = "upgradeNumber";
    private static final String INTENT_EXTRA_BADGEUPGRADE_COUNT = "app_badge_count";
    private static int ROMVERSION = -1;

    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    @Override
    public void executeBadge(Context context, ComponentName componentName, int badgeCount) throws ShortcutBadgeException {
        if (badgeCount == 0) {
            badgeCount = -1;
        }
        Intent intent = new Intent(INTENT_ACTION);
        intent.putExtra(INTENT_EXTRA_PACKAGENAME, componentName.getPackageName());
        intent.putExtra(INTENT_EXTRA_BADGE_COUNT, badgeCount);
        intent.putExtra(INTENT_EXTRA_BADGE_UPGRADENUMBER, badgeCount);
        if (BroadcastHelper.canResolveBroadcast(context, intent)) {
            context.sendBroadcast(intent);
        } else {
            int version = getSupportVersion();
            if (version == 6) {
                try {
                    Bundle extras = new Bundle();
                    extras.putInt(INTENT_EXTRA_BADGEUPGRADE_COUNT, badgeCount);
                    context.getContentResolver().call(Uri.parse(PROVIDER_CONTENT_URI), "setAppBadgeCount", null, extras);
                } catch (Throwable th) {
                    throw new ShortcutBadgeException("unable to resolve intent: " + intent.toString());
                }
            }
        }
    }

    @Override
    public List<String> getSupportLaunchers() {
        return Collections.singletonList("com.oppo.launcher");
    }

    private int getSupportVersion() {
        int i = ROMVERSION;
        if (i >= 0) {
            return ROMVERSION;
        }
        try {
            i = ((Integer) executeClassLoad(getClass("com.color.os.ColorBuild"), "getColorOSVERSION", null, null)).intValue();
        } catch (Exception e) {
            i = 0;
        }
        if (i == 0) {
            try {
                String str = getSystemProperty("ro.build.version.opporom");
                if (str.startsWith("V1.4")) {
                    return 3;
                }
                if (str.startsWith("V2.0")) {
                    return 4;
                }
                if (str.startsWith("V2.1")) {
                    return 5;
                }
            } catch (Exception ignored) {

            }
        }
        ROMVERSION = i;
        return ROMVERSION;
    }

    private Object executeClassLoad(Class cls, String str, Class[] clsArr, Object[] objArr) {
        Object obj = null;
        if (!(cls == null || checkObjExists(str))) {
            Method method = getMethod(cls, str, clsArr);
            if (method != null) {
                method.setAccessible(true);
                try {
                    obj = method.invoke(null, objArr);
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                }
            }
        }
        return obj;
    }

    private Method getMethod(Class cls, String str, Class[] clsArr) {
        Method method = null;
        if (cls == null || checkObjExists(str)) {
            return method;
        }
        try {
            cls.getMethods();
            cls.getDeclaredMethods();
            return cls.getDeclaredMethod(str, clsArr);
        } catch (Exception e) {
            try {
                return cls.getMethod(str, clsArr);
            } catch (Exception e2) {
                return cls.getSuperclass() != null ? getMethod(cls.getSuperclass(), str, clsArr) : method;
            }
        }
    }

    private Class getClass(String str) {
        Class cls = null;
        try {
            cls = Class.forName(str);
        } catch (ClassNotFoundException ignored) {
        }
        return cls;
    }

    private boolean checkObjExists(Object obj) {
        return obj == null || obj.toString().equals("") || obj.toString().trim().equals("null");
    }

    private String getSystemProperty(String propName) {
        String line;
        BufferedReader input = null;
        try {
            Process p = Runtime.getRuntime().exec("getprop " + propName);
            input = new BufferedReader(new InputStreamReader(p.getInputStream()), 1024);
            line = input.readLine();
            input.close();
        } catch (IOException ex) {
            return null;
        } finally {
            CloseHelper.closeQuietly(input);
        }
        return line;
    }
}


text:
<?php

namespace System\Repositories\Common;

/**
 * This is the base repository trait.
 */
trait BaseRepositoryTrait
{
    /**
     * Create a new model.
     *
     * @param  array  $input
     * @return mixed
     */
    public function create(array $input)
    {
        $model = $this->model;
        return $model::create($input);
    }

    /**
     * Find an existing model.
     *
     * @param  int    $id
     * @param  array  $columns
     * @return mixed
     */
    public function find($id, array $columns = array('*'))
    {
        $model = $this->model;
        return $model::find($id, $columns);
    }

    /**
     * Find an existing model.
     *
     * @param  int    $id
     * @param  array  $columns
     * @return mixed
     */
    public function findOrFail($id, array $columns = array('*'))
    {
        $model = $this->model;
        return $model::findOrFail($id, $columns);
    }

    /**
     * Find all models.
     *
     * @param  array  $columns
     * @return mixed
     */
    public function all(array $columns = array('*'))
    {
        $model = $this->model;
        return $model::all($columns);
    }

    /**
     * Get a list of the models.
     *
     * @return \Illuminate\Database\Eloquent\Collection
     */
    public function index()
    {
        $model = $this->model;

        if (property_exists($model, 'order')) {
            return $model::orderBy($model::$order, $model::$sort)->get($model::$index);
        }

        return $model::get($model::$index);
    }

    /**
     * Get the number of rows.
     *
     * @return int
     */
    public function count()
    {
        $model = $this->model;
        return $model::where('id', '>=', 1)->count();
    }

    /**
     * Register an observer.
     *
     * @param  object  $class
     * @return $this
     */
    public function observe($class)
    {
        $model = $this->model;
        $model::observe($class);

        return $this;
    }

    /**
     * Return the rules.
     *
     * @param  array|string  $query
     * @return array
     */
    public function rules($query = null)
    {
        $model = $this->model;

        // get rules from the model if set
        if (isset($model::$rules)) {
            $rules = $model::$rules;
        }

        // return an empty array
        if (!is_array($rules)) {
            return array();
        }

        // return all of the rules
        if (is_null($query)) {
            return array_filter($rules);
        }

        // convert string to array
        if (is_string($query)) {
            $query = array($query);
        }

        // get the relevant rules
        return array_filter(array_only($rules, $query));
    }

    /**
     * Validate the data.
     *
     * @param  array         $data
     * @param  array|string  $rules
     * @param  bool          $custom
     * @return \Illuminate\Validation\Validator
     */
    public function validate(array $data, $rules = null, $custom = false)
    {
        if (!$custom) {
            $rules = $this->rules($rules);
        }

        return $this->validator->make($data, $rules);
    }
}


text:
layout: post
title: "#2 - Dubai..."
date: 2015-12-10
categories:
author: "Stefan Kapferer"
---
## Thursday, 10. December 2015

### Introduction
Yesterday in the evening I updated the client-api's, because Wolfgang told us to do so...
Updating the api's was easy. But then I started a first test with the new track **dubai** and had to realize that our track recognition doesn't work with that track :-/

So I have to work on that one again :-/

### Track recognition again...
It's a tricky one this *dubai* track, because it has a lot of sub-patterns which repeat very often.
That caused that our *track recognizer* always matched these smaller patterns, but not the correct track pattern.

#### Solution
We improved the whole logic a little. After we matched one of these *smaller* patterns, we start driving based on that pattern.
Of course after a short time, the driving actors comes into problems. He loses the position very often. Of cource, because the pattern is not correct.

There is also one single left curve in the track, which isn't contained by that short patterns.

So we added an improvement. We have to start the whole process of track recognition again, if we detect these problems while driving.
But we have to remember the *failed* patterns! If we start again we have ignore the already failed patterns.

These changes did the trick to get **dubai** working:

 - start track recognition again, if the pattern produces too much problems while driving
   - start again, if there is a LEFT- or RIGHT- part detected which is not in the pattern
   - start again, if we lost the position very often in a short time
 - store already *failed* patterns
 - ignore *failed* patterns in the next track recognition round

#### Conclusion
That's it. It works with dubai too... We hope that our solution is stable now. Also in the final :-)


text:
Erebus
==============

C++ Development can be a pain. Project setup is dependent on the tools used in the project and the developer.  This tool is a command line tool for generating project and files independent of any ide or editor.

Installation
---------------

Install it yourself as:

   $ gem install erebus

Usage
-----------

To see a list of tasks erebus can do:

   erebus

To create a new C++ project:

   erebus project NAME

To create a new C++ project without Tests:

   erebus project NAME --no-testing

To add Igloo Testing to an existing project:

   erebus setup_test .

To create a header file:

    erebus header NAME

To create a C++ source file:

    erebus source NAME

To create a Igloo Test Spec:

    erebus spec <Name of the class to test>

To create a C source file:

    erebus source NAME --ext c

To generate a C++ class:

    erebus cpp_class NAME

To generate a C++ class without Tests:

    erebus cpp_class NAME --no-testing

Contributing
--------------

Project tracking is on a Pivotal Tracker Project https://www.pivotaltracker.com/projects/751383

1. Fork it
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request


text:
package com.github.wtopolski.testingworkshopapp;

import android.graphics.drawable.ColorDrawable;
import android.support.test.espresso.Espresso;
import android.support.test.espresso.IdlingResource;
import android.support.test.espresso.UiController;
import android.support.test.espresso.ViewAction;
import android.support.test.espresso.contrib.RecyclerViewActions;
import android.support.test.espresso.matcher.BoundedMatcher;
import android.support.test.filters.LargeTest;
import android.support.test.internal.util.Checks;
import android.support.test.rule.ActivityTestRule;
import android.support.test.runner.AndroidJUnit4;
import android.text.format.DateUtils;
import android.view.View;
import android.widget.TextView;

import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;

import static android.support.test.espresso.Espresso.onView;
import static android.support.test.espresso.action.ViewActions.click;
import static android.support.test.espresso.assertion.ViewAssertions.matches;
import static android.support.test.espresso.matcher.ViewMatchers.isDisplayed;
import static android.support.test.espresso.matcher.ViewMatchers.withId;
import static android.support.test.espresso.matcher.ViewMatchers.withText;

@RunWith(AndroidJUnit4.class)
@LargeTest
public class MainActivityEspressoTest {
    @Rule
    public ActivityTestRule<MainActivity> mActivityRule = new ActivityTestRule<>(MainActivity.class);

    @Test
    public void checkVisibilityOfColorLabel() {
        onView(withId(R.id.color_label)).check(matches(isDisplayed()));
    }

    @Test
    public void initialStateOfColorLabel() {
        onView(withId(R.id.color_label)).check(matches(withText("#FFFFFF")));
        onView(withId(R.id.color_label)).check(matches(withBackgroundColor("#FFFFFF")));
        onView(withId(R.id.color_label)).check(matches(withTextColor("#000000")));
    }

    @Test
    public void initialStateOfClear() {
        onView(withId(R.id.clear)).check(matches(withText("Clear")));
    }

    @Test
    public void clearExecution() {
        onView(withId(R.id.clear)).perform(click());

        onView(withId(R.id.color_label)).check(matches(withText("#FFFFFF")));
        onView(withId(R.id.color_label)).check(matches(withBackgroundColor("#FFFFFF")));
        onView(withId(R.id.color_label)).check(matches(withTextColor("#000000")));
    }

    @Test
    public void redExecution() {
        onView(withId(R.id.red)).perform(click());

        onView(withId(R.id.color_label)).check(matches(withText("#FF0000")));
        onView(withId(R.id.color_label)).check(matches(withBackgroundColor("#FF0000")));
        onView(withId(R.id.color_label)).check(matches(withTextColor("#00FFFF")));
    }

    @Test
    public void greenExecution() {
        onView(withId(R.id.green)).perform(click());

        onView(withId(R.id.color_label)).check(matches(withText("#00FF00")));
        onView(withId(R.id.color_label)).check(matches(withBackgroundColor("#00FF00")));
        onView(withId(R.id.color_label)).check(matches(withTextColor("#FF00FF")));
    }

    @Test
    public void blueExecution() {
        onView(withText("Blue")).perform(click());

        onView(withId(R.id.color_label)).check(matches(withText("#0000FF")));
        onView(withId(R.id.color_label)).check(matches(withBackgroundColor("#0000FF")));
        onView(withId(R.id.color_label)).check(matches(withTextColor("#FFFF00")));
    }

    @Test
    public void recycleViewScroll() {
        onView(withId(R.id.recycleView)).perform(RecyclerViewActions.scrollToPosition(12));
        onView(withText("#f5f5dc")).check(matches(isDisplayed()));
    }

    @Test
    public void recycleViewScrollAndClick() {
        onView(withId(R.id.recycleView)).perform(RecyclerViewActions.scrollToPosition(12));
        onView(withText("#f5f5dc")).check(matches(isDisplayed()));

        onView(withId(R.id.clear)).perform(click());
        onView(withId(R.id.recycleView)).perform(RecyclerViewActions.actionOnItemAtPosition(12, click()));
        onView(withId(R.id.color_label)).check(matches(withText("#FAFAED")));

        onView(withId(R.id.red)).perform(click());
        onView(withId(R.id.recycleView)).perform(RecyclerViewActions.actionOnItemAtPosition(12, click()));
        onView(withId(R.id.color_label)).check(matches(withText("#FA7A6E")));

        onView(withId(R.id.green)).perform(click());
        onView(withId(R.id.recycleView)).perform(RecyclerViewActions.actionOnItemAtPosition(12, click()));
        onView(withId(R.id.color_label)).check(matches(withText("#7AFA6E")));

        onView(withId(R.id.blue)).perform(click());
        onView(withId(R.id.recycleView)).perform(RecyclerViewActions.actionOnItemAtPosition(11, click()));
        onView(withId(R.id.color_label)).check(matches(withText("#4145C5")));
    }

    @Test
    public void recycleViewAndCustomViewAction() {
        onView(withId(R.id.blue)).perform(click());

        // Now we wait
        IdlingResource idlingResource1 = new ElapsedTimeIdlingResource(DateUtils.SECOND_IN_MILLIS * 2);
        Espresso.registerIdlingResources(idlingResource1);

        // Now we do
        ClickChildViewAction viewAction = new ClickChildViewAction();
        onView(withId(R.id.recycleView)).perform(RecyclerViewActions.actionOnItemAtPosition(11, viewAction.clickChildViewWithId(R.id.element)));

        Espresso.unregisterIdlingResources(idlingResource1);

        // Now we wait again
        IdlingResource idlingResource2 = new ElapsedTimeIdlingResource(DateUtils.SECOND_IN_MILLIS * 2);
        Espresso.registerIdlingResources(idlingResource2);

        // Do again
        onView(withId(R.id.color_label)).check(matches(withText("#4145C5")));

        Espresso.unregisterIdlingResources(idlingResource2);
    }

    public static Matcher<View> withBackgroundColor(final String expectedHexColor) {
        Checks.checkNotNull(expectedHexColor);

        return new BoundedMatcher<View, TextView>(TextView.class) {
            private String msg = "";

            @Override
            public boolean matchesSafely(TextView widget) {
                ColorDrawable colorDrawable = (ColorDrawable) widget.getBackground();
                String hexCurrentColor = String.format("#%06X", (0xFFFFFF & colorDrawable.getColor()));
                msg = " " + expectedHexColor + " Current: " + hexCurrentColor;
                return expectedHexColor.equals(hexCurrentColor);
            }

            @Override
            public void describeTo(Description description) {
                description.appendText(msg);
            }
        };
    }

    public static Matcher<View> withTextColor(final String expectedHexColor) {
        Checks.checkNotNull(expectedHexColor);

        return new BoundedMatcher<View, TextView>(TextView.class) {
            private String msg = "";

            @Override
            public boolean matchesSafely(TextView widget) {
                String hexCurrentColor = String.format("#%06X", (0xFFFFFF & widget.getCurrentTextColor()));
                msg = " " + expectedHexColor + " Current: " + hexCurrentColor;
                return expectedHexColor.equals(hexCurrentColor);
            }

            @Override
            public void describeTo(Description description) {
                description.appendText(msg);
            }
        };
    }

    public class ClickChildViewAction {
        ViewAction clickChildViewWithId(final int id) {
            return new ViewAction() {
                @Override
                public Matcher<View> getConstraints() {
                    return null;
                }

                @Override
                public String getDescription() {
                    return "Click on a child view with specified id.";
                }

                @Override
                public void perform(UiController uiController, View view) {
                    View v = view.findViewById(id);
                    v.performClick();
                }
            };
        }
    }
}


text:
package org.kie.workbench.common.stunner.client.lienzo.canvas;

import com.ait.lienzo.client.core.shape.IPrimitive;
import com.ait.lienzo.client.core.shape.Layer;
import com.ait.lienzo.client.core.shape.Scene;
import com.ait.lienzo.client.core.shape.Viewport;
import com.ait.lienzo.client.core.types.OnLayerAfterDraw;
import com.ait.lienzo.client.core.types.Transform;
import com.ait.lienzo.test.LienzoMockitoTestRunner;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.kie.workbench.common.stunner.core.graph.content.view.Point2D;
import org.mockito.Mock;
import org.uberfire.mvp.Command;

import static org.junit.Assert.assertEquals;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

@RunWith(LienzoMockitoTestRunner.class)
public class LienzoLayerTest {

    @Mock
    private Layer layer;
    @Mock
    private Scene scene;
    @Mock
    private Viewport viewport;
    @Mock
    private Layer topLayer;
    @Mock
    private IPrimitive<?> shape;

    private LienzoLayer tested;
    private Transform transform;

    @Before
    public void setUp() throws Exception {
        transform = new Transform();
        when(layer.getScene()).thenReturn(scene);
        when(layer.getViewport()).thenReturn(viewport);
        when(scene.getTopLayer()).thenReturn(topLayer);
        when(layer.getAbsoluteTransform()).thenReturn(transform);
        when(viewport.getTransform()).thenReturn(transform);
        this.tested = new LienzoLayer(layer);
    }

    @Test
    public void testAdd() {
        tested.add(shape);
        verify(layer, times(1)).add(eq(shape));
    }

    @Test
    public void testDelete() {
        tested.delete(shape);
        verify(layer, times(1)).remove(eq(shape));
    }

    @Test
    public void testClear() {
        tested.clear();
        verify(layer, times(1)).clear();
    }

    @Test
    public void testOnAfterDraw() {
        tested.onAfterDraw(mock(Command.class));
        verify(layer, times(1)).setOnLayerAfterDraw(any(OnLayerAfterDraw.class));
    }

    @Test
    public void testGetTopLayer() {
        assertEquals(topLayer, tested.getTopLayer());
    }

    @Test
    public void testDestroy() {
        tested.destroy();
        verify(layer, times(1)).removeAll();
        verify(layer, times(1)).removeFromParent();
    }

    @Test
    public void testGetTranslate() {
        transform.translate(11, 33);
        Point2D translate = tested.getTranslate();
        assertEquals(11d, translate.getX(), 0d);
        assertEquals(33d, translate.getY(), 0d);
    }

    @Test
    public void testGetScale() {
        transform.scale(0.11, 0.666);
        Point2D translate = tested.getScale();
        assertEquals(0.11d, translate.getX(), 0d);
        assertEquals(0.666d, translate.getY(), 0d);
    }

    @Test
    public void testTranslate() {
        tested.translate(11, 33);
        assertEquals(11d, transform.getTranslateX(), 0d);
        assertEquals(33d, transform.getTranslateY(), 0d);
    }

    @Test
    public void testScaleUnit() {
        tested.scale(0.22d);
        assertEquals(0.22d, transform.getScaleX(), 0d);
        assertEquals(0.22d, transform.getScaleY(), 0d);
    }

    @Test
    public void testScaleUnits() {
        tested.scale(0.22d, 0.33d);
        assertEquals(0.22d, transform.getScaleX(), 0d);
        assertEquals(0.33d, transform.getScaleY(), 0d);
    }
}


text:
SHIM_ALWAYS_EXPORT void* operator new(size_t size) {
  return ShimCppNew(size);
}

SHIM_ALWAYS_EXPORT void operator delete(void* p) __THROW {
  ShimCppDelete(p);
}

SHIM_ALWAYS_EXPORT void* operator new[](size_t size) {
  return ShimCppNew(size);
}

SHIM_ALWAYS_EXPORT void operator delete[](void* p) __THROW {
  ShimCppDelete(p);
}

SHIM_ALWAYS_EXPORT void* operator new(size_t size,
                                      const std::nothrow_t&) __THROW {
  return ShimCppNew(size);
}

SHIM_ALWAYS_EXPORT void* operator new[](size_t size,
                                        const std::nothrow_t&) __THROW {
  return ShimCppNew(size);
}

SHIM_ALWAYS_EXPORT void operator delete(void* p, const std::nothrow_t&) __THROW {
  ShimCppDelete(p);
}

SHIM_ALWAYS_EXPORT void operator delete[](void* p,
                                          const std::nothrow_t&) __THROW {
  ShimCppDelete(p);
}

SHIM_ALWAYS_EXPORT void operator delete(void* p, size_t) __THROW {
  ShimCppDelete(p);
}

SHIM_ALWAYS_EXPORT void operator delete[](void* p, size_t) __THROW {
  ShimCppDelete(p);
}


text:
package edu.harvard.iq.dataverse.util.json;

public class JsonLDNamespace {

	String prefix;

	String url;

	public static JsonLDNamespace dvcore = new JsonLDNamespace("dvcore", "https://dataverse.org/schema/core#");
	public static JsonLDNamespace dcterms = new JsonLDNamespace("dcterms","http://purl.org/dc/terms/");
	public static JsonLDNamespace ore = new JsonLDNamespace("ore","http://www.openarchives.org/ore/terms/");
	public static JsonLDNamespace schema = new JsonLDNamespace("schema","http://schema.org/");

	public JsonLDNamespace(String prefix, String url) {
		this.prefix = prefix;
		this.url = url;
	}

	public String getPrefix() {
		return prefix;
	}

	public String getUrl() {
		return url;
	}

}


text:
ERL					?= erl
ERLC				= erlc
EBIN_DIRS		:= $(wildcard deps/*/ebin)
APPS				:= $(shell dir apps)

.PHONY: rel deps

all: deps compile

compile: deps
	@rebar compile

deps:
	@rebar get-deps
	@rebar check-deps

clean:
	@rebar clean

realclean: clean
	@rebar delete-deps

test:
	@rebar skip_deps=true ct

rel: deps
	@rebar compile generate

doc:
	rebar skip_deps=true doc
	for app in $(APPS); do \
		cp -R apps/$${app}/doc doc/$${app}; \
	done;

console:
	@erl -pa deps/*/ebin deps/*/include ebin include -boot start_sasl

analyze: checkplt
	@rebar skip_deps=true dialyze

buildplt:
	@rebar skip_deps=true build-plt

checkplt: buildplt
	@rebar skip_deps=true check-plt


text:
If you want an overview of how VS Code differs from traditional TextMate clones, read Orta's [post on the Artsy blog](http://artsy.github.io/blog/2016/08/15/vscode/).

## Running Metaphysics

Ideally you should run Metaphysics

## Debugging Metaphysics

![Debugging](imgs/debugger.png)

This repo uses babel at runtime via `require('babel-core/register');` and so there are no source-mapping files, this means that VS Code does not support LOC breakpoints from your source code into the real transpiled code in Metaphysics.

You can work around this though [using the `debugger` function](https://developers.google.com/web/tools/chrome-devtools/console/command-line-reference?hl=en#debugfunction) inside your source code instead.

To start the debugger, run the debugger (VS Code defaults this to `f5`, I typically re-bind this to `cmd + r`) and the bar at the bottom should turn orange. Then in the LOC you want to debug inside, add `debugger;`. This will open the transpiled source code, and on the left in the debugger menu you can see all of the state, and the console should work at the bottom.

You can also open a new tab with `about:inspector` in Chrome and it will provide a button to load up the chrome inspector in Chrome Dev Tools.

### Related Tangentially

There is more information about using VS Code, with terminology and keybinding recommendations, inside [the Emission repo](https://github.com/artsy/emission/blob/master/docs/vscode.md).


text:
<?php

// autoload_psr4.php @generated by Composer

$vendorDir = dirname(dirname(__FILE__));
$baseDir = dirname($vendorDir);

return array(
    'yii\\swiftmailer\\' => array($vendorDir . '/yiisoft/yii2-swiftmailer'),
    'yii\\gii\\' => array($vendorDir . '/yiisoft/yii2-gii'),
    'yii\\faker\\' => array($vendorDir . '/yiisoft/yii2-faker'),
    'yii\\debug\\' => array($vendorDir . '/yiisoft/yii2-debug'),
    'yii\\composer\\' => array($vendorDir . '/yiisoft/yii2-composer'),
    'yii\\codeception\\' => array($vendorDir . '/yiisoft/yii2-codeception'),
    'yii\\bootstrap\\' => array($vendorDir . '/yiisoft/yii2-bootstrap'),
    'yii\\' => array($vendorDir . '/yiisoft/yii2'),
    'miloschuman\\highcharts\\' => array($vendorDir . '/miloschuman/yii2-highcharts-widget/src'),
    'kartik\\widgets\\' => array($vendorDir . '/kartik-v/yii2-widgets'),
    'kartik\\typeahead\\' => array($vendorDir . '/kartik-v/yii2-widget-typeahead'),
    'kartik\\touchspin\\' => array($vendorDir . '/kartik-v/yii2-widget-touchspin'),
    'kartik\\time\\' => array($vendorDir . '/kartik-v/yii2-widget-timepicker'),
    'kartik\\switchinput\\' => array($vendorDir . '/kartik-v/yii2-widget-switchinput'),
    'kartik\\spinner\\' => array($vendorDir . '/kartik-v/yii2-widget-spinner'),
    'kartik\\sidenav\\' => array($vendorDir . '/kartik-v/yii2-widget-sidenav'),
    'kartik\\select2\\' => array($vendorDir . '/kartik-v/yii2-widget-select2'),
    'kartik\\rating\\' => array($vendorDir . '/kartik-v/yii2-widget-rating'),
    'kartik\\range\\' => array($vendorDir . '/kartik-v/yii2-widget-rangeinput'),
    'kartik\\popover\\' => array($vendorDir . '/kartik-v/yii2-popover-x'),
    'kartik\\plugins\\popover\\' => array($vendorDir . '/kartik-v/bootstrap-popover-x'),
    'kartik\\plugins\\fileinput\\' => array($vendorDir . '/kartik-v/bootstrap-fileinput'),
    'kartik\\plugins\\depdrop\\' => array($vendorDir . '/kartik-v/dependent-dropdown'),
    'kartik\\mpdf\\' => array($vendorDir . '/kartik-v/yii2-mpdf'),
    'kartik\\growl\\' => array($vendorDir . '/kartik-v/yii2-widget-growl'),
    'kartik\\grid\\' => array($vendorDir . '/kartik-v/yii2-grid'),
    'kartik\\form\\' => array($vendorDir . '/kartik-v/yii2-widget-activeform'),
    'kartik\\file\\' => array($vendorDir . '/kartik-v/yii2-widget-fileinput'),
    'kartik\\editable\\' => array($vendorDir . '/kartik-v/yii2-editable'),
    'kartik\\depdrop\\' => array($vendorDir . '/kartik-v/yii2-widget-depdrop'),
    'kartik\\datetime\\' => array($vendorDir . '/kartik-v/yii2-widget-datetimepicker'),
    'kartik\\date\\' => array($vendorDir . '/kartik-v/yii2-widget-datepicker'),
    'kartik\\color\\' => array($vendorDir . '/kartik-v/yii2-widget-colorinput'),
    'kartik\\base\\' => array($vendorDir . '/kartik-v/yii2-krajee-base'),
    'kartik\\alert\\' => array($vendorDir . '/kartik-v/yii2-widget-alert'),
    'kartik\\affix\\' => array($vendorDir . '/kartik-v/yii2-widget-affix'),
    'hscstudio\\mimin\\' => array($vendorDir . '/hscstudio/yii2-mimin'),
    'chillerlan\\QRCode\\' => array($vendorDir . '/chillerlan/php-qrcode/src'),
    'cebe\\markdown\\' => array($vendorDir . '/cebe/markdown'),
    'c006\\utility\\migration\\' => array($vendorDir . '/c006/yii2-migration-utility'),
    'bupy7\\cropbox\\' => array($vendorDir . '/bupy7/yii2-widget-cropbox'),
    'Faker\\' => array($vendorDir . '/fzaninotto/faker/src/Faker'),
);


text:
<?xml version="1.0" encoding="UTF-8"?>
${ivy.pom.license}
${ivy.pom.header}
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

	<modelVersion>4.0.0</modelVersion>
	<groupId>${ivy.pom.groupId}</groupId>
	<artifactId>${ivy.pom.artifactId}</artifactId>
	<packaging>${ivy.pom.packaging}</packaging>
	<version>${ivy.pom.version}</version>
	<name>${ivy.pom.name}</name>
	<description>${ivy.pom.description}</description>
	<url>${ivy.pom.url}</url>
	<lastUpdated>${ivy.now}</lastUpdated>
</project>


text:
package nl.han.ica.core.parser;

import nl.han.ica.core.SourceFile;
import nl.han.ica.core.util.FileUtil;
import org.apache.log4j.Logger;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.dom.AST;
import org.eclipse.jdt.core.dom.ASTParser;
import org.eclipse.jdt.core.dom.CompilationUnit;

import java.util.Set;

/**
 * Parses SourceFiles and constructs their AST trees.
 */
public class Parser {

    private ASTParser astParser;
    private Set<SourceFile> sourceFiles;
    private Logger logger;

    /**
     * Instantiate a new Parser.
     */
    public Parser() {
        logger = Logger.getLogger(getClass().getName());

        initializeASTParser();
    }

    private void initializeASTParser() {
        astParser = ASTParser.newParser(AST.JLS3);
        astParser.setKind(ASTParser.K_COMPILATION_UNIT);
        astParser.setResolveBindings(true);
        astParser.setCompilerOptions(JavaCore.getOptions());
    }

    /**
     * Parse a set of {@link SourceFile}s.
     *
     * @param sourceFiles The SourceFiles to parse.
     * @return
     */
    public Set<CompilationUnit> parse(Set<SourceFile> sourceFiles) {
        this.sourceFiles = sourceFiles;

        astParser.setEnvironment(FileUtil.directoryPaths(sourceFiles), null, null, true);
        astParser.setUnitName("Refactor-Tool"); // TODO: Check what this does (and whether it can be useful);

        String[] bindings = new String[0]; //TODO: see todo above
        ASTRequestor astRequestor = new ASTRequestor(sourceFiles);
        astParser.createASTs(FileUtil.filePaths(sourceFiles), null, bindings, astRequestor, null);
        return astRequestor.getCompilationUnits();
    }

}


text:
if nil ~= require then
	require "wow/Frame-Layout";
	require "wow/api/Frame";

	require "fritomod/Functions";
	require "fritomod/OOP-Class";
	require "fritomod/Lists";
	require "fritomod/Frames";
	require "fritomod/Frames-Mouse";
	require "fritomod/Anchors";
end;

Labs=Labs or {};

local TitleFrame=OOP.Class();

function TitleFrame:Constructor(parent)
	self.frameTypeText=Frames.Text(parent, "friz", 14);
	Frames.Color(self.frameTypeText, "gold");

	self.nameText=Frames.Text(parent, "friz", 10);
	Anchors.VFlipBottom(self.nameText, self.frameTypeText, 4);
end;

function TitleFrame:Set(f)
	self.frameTypeText:Hide();
	self.nameText:Hide();
	if not f then
		return;
	end;
	if f:GetObjectType() then
		self.frameTypeText:Show();
		self.frameTypeText:SetText(f:GetObjectType());
	end;
	if f:GetName() then
		self.nameText:Show();
		self.nameText:SetText(('"%s"'):format(f:GetName()));
	end;
end;

function TitleFrame:Top()
	if self.frameTypeText:IsShown() then
		return self.frameTypeText;
	end;
end;

function TitleFrame:Bottom()
	if self.nameText:IsShown() then
		return self.nameText;
	else
		return self.frameTypeText;
	end;
end;

local PointFrame=OOP.Class();

function PointFrame:Constructor(parent)
	self.container=CreateFrame("Frame", nil, parent);
	self.container:SetHeight(40);
	parent=self.container;
	self.anchorText=Frames.Text(parent, "friz", 12);
	self.refText=Frames.Text(parent, "friz", 10);

	self.anchorText:SetJustifyH("left");
	self.refText:SetJustifyH("left");

	Anchors.ShareTop(self.anchorText);
	Anchors.VFlipBottom(self.refText, self.anchorText);
end;

function PointFrame:Set(frame, index)
	self.container:Hide();
	self.anchorText:Hide();
	self.refText:Hide();
	if not frame then
		return;
	end;
	local anchor, ref, anchorTo, gapX, gapY=frame:GetPoint(index);
	if not anchor then
		return;
	end;
	self.container:Show();
	self.anchorText:Show();
	if not anchorTo then
		anchorTo="("..anchor..")";
	end;
	self.anchorText:SetText(("%s : %s"):format(anchor, anchorTo));
	if not ref then
		ref=UIParent;
	end;
	local n, t;
	if ref:GetName() then
		n=' "'..ref:GetName()..'"';
	elseif ref==frame:GetParent() then
		n=" (parent)";
	end;
	t=ref:GetObjectType();
	self.refText:Show();
	self.refText:SetText(("[%s%s]"):format(t, n));
end;

function PointFrame:GetContainer()
	if self.container:IsShown() then
		return self.container;
	end;
end;

FrameFinder=OOP.Class();

function FrameFinder:Constructor()
	self.container=CreateFrame("Frame");
	self.container:SetFrameStrata("dialog");
	Frames.Size(self.container, 300, 200);
	Frames.Backdrop(self.container, "black");

	local close=CreateFrame("Button", nil, self.container);
	Frames.Button(close, "close");
	Frames.Size(close, 15);
	Anchors.Share(close, "topright");
	Callbacks.Click(close, self.container, "Hide");

	self.titleFrame=TitleFrame:New(self.container);

	self.points={};
end;

function FrameFinder:GetContainer()
	return self.container;
end;

function FrameFinder:Set(f)
	if self.target == f then
		return;
	end;
	self.target=f;
	self.titleFrame:Set(f);
	local frames={};
	if self.titleFrame:Top() then
		table.insert(frames, self.titleFrame:Top());
		table.insert(frames, self.titleFrame:Bottom());
	end;
	if f:GetNumPoints() > 0 then
		local pointFrames={};
		Lists.Each(self.points, function(p)
			p:Set();
		end);
		for i=1, f:GetNumPoints() do
			local point=self.points[i]
			if not point then
				point=PointFrame:New(self.container);
				table.insert(self.points, point);
			end;
			point:Set(f, i);
			if point:GetContainer() then
				table.insert(pointFrames, point:GetContainer());
			end;
		end;
		Lists.FlipMarch(pointFrames, Anchors.VFlipBottom);
		table.insert(frames, pointFrames[1]);
		table.insert(frames, pointFrames[#pointFrames]);
	end;
	Lists.FlipMarch(frames, function(a, b)
		if a ~= b then
			Anchors.VFlipBottom(a, b);
		end;
	end);
	Anchors.ShareTop(frames[1]);
end;

function Labs.FrameFinder()
	local finder=FrameFinder:New();

	local f=finder:GetContainer();

	f:SetParent(UIParent);
	f:SetPoint("center");
	Frames.InstantDraggable(f);
	f:Hide();

	Slash.Register("ff", Frames.ToggleShow, f);
	Callbacks.ShowFrame(f, Timing.Every, .3, function()
		if not IsAltKeyDown() then
			return;
		end;
		local focusedFrame = GetMouseFocus()
		if focusedFrame then
			finder:Set(focusedFrame);
		end
	end);
end


text:
package empty

import (
	"encoding/json"
	"errors"

	v1 "github.com/google/go-containerregistry/pkg/v1"
	"github.com/google/go-containerregistry/pkg/v1/partial"
	"github.com/google/go-containerregistry/pkg/v1/types"
)

// Index is a singleton empty index, think: FROM scratch.
var Index = emptyIndex{}

type emptyIndex struct{}

func (i emptyIndex) MediaType() (types.MediaType, error) {
	return types.OCIImageIndex, nil
}

func (i emptyIndex) Digest() (v1.Hash, error) {
	return partial.Digest(i)
}

func (i emptyIndex) Size() (int64, error) {
	return partial.Size(i)
}

func (i emptyIndex) IndexManifest() (*v1.IndexManifest, error) {
	return base(), nil
}

func (i emptyIndex) RawManifest() ([]byte, error) {
	return json.Marshal(base())
}

func (i emptyIndex) Image(v1.Hash) (v1.Image, error) {
	return nil, errors.New("empty index")
}

func (i emptyIndex) ImageIndex(v1.Hash) (v1.ImageIndex, error) {
	return nil, errors.New("empty index")
}

func base() *v1.IndexManifest {
	return &v1.IndexManifest{
		SchemaVersion: 2,
	}
}


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.facebook.presto.cli;

import com.facebook.presto.client.ClientSession;
import com.facebook.presto.client.QueryResults;
import com.facebook.presto.client.StatementClient;
import io.airlift.http.client.AsyncHttpClient;
import io.airlift.http.client.HttpClientConfig;
import io.airlift.http.client.jetty.JettyHttpClient;
import io.airlift.json.JsonCodec;
import io.airlift.units.Duration;

import java.io.Closeable;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

import static com.google.common.base.Preconditions.checkNotNull;
import static io.airlift.json.JsonCodec.jsonCodec;

public class QueryRunner
        implements Closeable
{
    private final JsonCodec<QueryResults> queryResultsCodec;
    private final AtomicReference<ClientSession> session;
    private final AsyncHttpClient httpClient;

    public QueryRunner(ClientSession session, JsonCodec<QueryResults> queryResultsCodec)
    {
        this.session = new AtomicReference<>(checkNotNull(session, "session is null"));
        this.queryResultsCodec = checkNotNull(queryResultsCodec, "queryResultsCodec is null");
        this.httpClient = new JettyHttpClient(new HttpClientConfig().setConnectTimeout(new Duration(10, TimeUnit.SECONDS)));
    }

    public ClientSession getSession()
    {
        return session.get();
    }

    public void setSession(ClientSession session)
    {
        this.session.set(checkNotNull(session, "session is null"));
    }

    public Query startQuery(String query)
    {
        return new Query(startInternalQuery(query));
    }

    public StatementClient startInternalQuery(String query)
    {
        return new StatementClient(httpClient, queryResultsCodec, session.get(), query);
    }

    @Override
    public void close()
    {
        httpClient.close();
    }

    public static QueryRunner create(ClientSession session)
    {
        return new QueryRunner(session, jsonCodec(QueryResults.class));
    }
}


text:
package info.ipeanut.googletrainingcoursedemos.scheduler;

import android.app.IntentService;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;
import android.util.Log;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import info.ipeanut.googletrainingcoursedemos.R;

/**
 * This {@code IntentService} does the app's actual work.
 * {@code SampleAlarmReceiver} (a {@code WakefulBroadcastReceiver}) holds a
 * partial wake lock for this service while the service does its work. When the
 * service is finished, it calls {@code completeWakefulIntent()} to release the
 * wake lock.
 */
public class SampleSchedulingService extends IntentService {
    public SampleSchedulingService() {
        super("SchedulingService");
    }

    public static final String TAG = "Scheduling Demo";
    // An ID used to post the notification.
    public static final int NOTIFICATION_ID = 1;
    // The string the app searches for in the Google home page content. If the app finds
    // the string, it indicates the presence of a doodle.
    public static final String SEARCH_STRING = "doodle";
    // The Google home page URL from which the app fetches content.
    // You can find a list of other Google domains with possible doodles here:
    // http://en.wikipedia.org/wiki/List_of_Google_domains
    public static final String URL = "http://www.google.com";
    private NotificationManager mNotificationManager;
    NotificationCompat.Builder builder;

    @Override
    protected void onHandleIntent(Intent intent) {
        // BEGIN_INCLUDE(service_onhandle)
        // The URL from which to fetch content.
        String urlString = URL;

        String result ="";

        // Try to connect to the Google homepage and download content.
        try {
            result = loadFromNetwork(urlString);
        } catch (IOException e) {
            Log.i(TAG, getString(R.string.connection_error));
        }

        // If the app finds the string "doodle" in the Google home page content, it
        // indicates the presence of a doodle. Post a "Doodle Alert" notification.
        if (result.indexOf(SEARCH_STRING) != -1) {
            sendNotification(getString(R.string.doodle_found));
            Log.i(TAG, "Found doodle!!");
        } else {
            sendNotification(getString(R.string.no_doodle));
            Log.i(TAG, "No doodle found. :-(");
        }
        // Release the wake lock provided by the BroadcastReceiver.
        SampleAlarmReceiver.completeWakefulIntent(intent);
        // END_INCLUDE(service_onhandle)
    }

    // Post a notification indicating whether a doodle was found.
    private void sendNotification(String msg) {
        mNotificationManager = (NotificationManager)
               this.getSystemService(Context.NOTIFICATION_SERVICE);

        PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
            new Intent(this, MainActivity.class), 0);

        NotificationCompat.Builder mBuilder =
                new NotificationCompat.Builder(this)
        .setSmallIcon(R.mipmap.ic_launcher)
        .setContentTitle(getString(R.string.doodle_alert))
        .setStyle(new NotificationCompat.BigTextStyle()
        .bigText(msg))
        .setContentText(msg);

        mBuilder.setContentIntent(contentIntent);
        mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
    }

//
// The methods below this line fetch content from the specified URL and return the
// content as a string.
//
    /** Given a URL string, initiate a fetch operation. */
    private String loadFromNetwork(String urlString) throws IOException {
        InputStream stream = null;
        String str ="";

        try {
            stream = downloadUrl(urlString);
            str = readIt(stream);
        } finally {
            if (stream != null) {
                stream.close();
            }
        }
        return str;
    }

    /**
     * Given a string representation of a URL, sets up a connection and gets
     * an input stream.
     * @param urlString A string representation of a URL.
     * @return An InputStream retrieved from a successful HttpURLConnection.
     * @throws IOException
     */
    private InputStream downloadUrl(String urlString) throws IOException {

        URL url = new URL(urlString);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setReadTimeout(10000 /* milliseconds */);
        conn.setConnectTimeout(15000 /* milliseconds */);
        conn.setRequestMethod("GET");
        conn.setDoInput(true);
        // Start the query
        conn.connect();
        InputStream stream = conn.getInputStream();
        return stream;
    }

    /**
     * Reads an InputStream and converts it to a String.
     * @param stream InputStream containing HTML from www.google.com.
     * @return String version of InputStream.
     * @throws IOException
     */
    private String readIt(InputStream stream) throws IOException {

        StringBuilder builder = new StringBuilder();
        BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
        for(String line = reader.readLine(); line != null; line = reader.readLine())
            builder.append(line);
        reader.close();
        return builder.toString();
    }
}


text:
/*
 * This script prevents a navbar with the #navbar-fix identifier
 * from scrolling off the top of the browser window. It does this by
 * detecting when that's about to occur and creating a copy that's
 * added to the page with a fixed position, aligned to the top of
 * the page.
 *
 * When the user scrolls back up then this copy is
 * removed so the normal navbar is fully visible again.
 *
 * Because you can't scroll the fixed copy we're not able to use this
 * for the collapsed navigation where menu items are shown vertically.
 */

var isFixed = 0;

processScroll()
$(window).on('scroll', processScroll)

function processScroll() {

  var navbar = document.getElementById("navbar-fix");

  if (navbar == null) {
    return
  }

  if (!isFixed && $(window).scrollTop() >= $('.navbar#navbar-fix').offset().top) {
    var element = navbar.cloneNode(true);
    element.id = "navbar-fixed";
    navbar.parentNode.appendChild(element);
    isFixed = 1;
  }
  else if (isFixed && $(window).scrollTop() < $('.navbar#navbar-fix').offset().top)  {
    element = document.getElementById("navbar-fixed");
    element.parentNode.removeChild(element);
    isFixed = 0
  }
}