text:
package org.opennms.newts.stress;

import org.kohsuke.args4j.Argument;
import org.kohsuke.args4j.CmdLineException;
import org.kohsuke.args4j.CmdLineParser;
import org.kohsuke.args4j.Option;
import org.opennms.newts.api.Duration;
import org.opennms.newts.api.Timestamp;

class Config {

    enum Command {
        INSERT, SELECT;
    }

    static {
        CmdLineParser.registerHandler(Timestamp.class, TimestampOptionHandler.class);
        CmdLineParser.registerHandler(Duration.class, DurationOptionHandler.class);
    }

    /** Number of seconds to keep Cassandra-stored samples. */
    static int CASSANDRA_TTL = 86400;

    private boolean m_needHelp = false;
    private int m_threads = 4;
    private String m_cassandraHost = "localhost";
    private int m_cassandraPort = 9042;
    private String m_cassandraKeyspace = "newts";
    private String m_cassandraCompression = "NONE";
    private Timestamp m_start = Timestamp.fromEpochSeconds(900000000);
    private Timestamp m_end = Timestamp.fromEpochSeconds(931536000);
    private Duration m_interval = Duration.seconds(300);
    private int m_numResources = 1;
    private int m_numMetrics = 1;
    private Command m_command;

    protected void checkArgument(boolean condition, String msg, Object... msgArgs) throws CmdLineException {
        if (!condition) {
            throw new CmdLineException(null, String.format(msg, msgArgs));

        }
    }

    @Argument(required = true, metaVar = "<command>", index = 0, usage = "The operation to run.")
    void setCommandArgument(String command) throws CmdLineException {
        try {
            m_command = Command.valueOf(command.toUpperCase());
        }
        catch (IllegalArgumentException ex) {
            throw new CmdLineException(null, String.format("Unknown command: %s", command));
        }
    }

    @Option(name="-h", aliases="--help", usage="Print usage informations.")
    void setHelp(boolean help) {
        m_needHelp = help;
    }

    @Option(name = "-n", aliases = "--num-threads", metaVar = "<threads>", usage = "Concurrency level.")
    void setThreads(int threads) throws CmdLineException {
        checkArgument(threads > 0, "-n/--num-threads must be at least 1");
        m_threads = threads;
    }

    @Option(name = "-H", aliases = "--cassandra-host", metaVar = "<hostname>", usage = "Cassandra hostname.")
    void setCassandraHost(String host) {
        m_cassandraHost = host;
    }

    @Option(name = "-p", aliases = "--cassandra-port", metaVar = "<port>", usage = "Cassandra port number.")
    void setCassandraPort(int port) throws CmdLineException {
        checkArgument(port > 0, "Cassandra port number must be greater than zero");
        m_cassandraPort = port;
    }

    @Option(name = "-k", aliases = "--cassandra-keyspace", metaVar = "<keyspace>", usage = "Cassandra keyspace.")
    void setCassandraKeyspace(String keyspace) {
        m_cassandraKeyspace = keyspace;
    }

    @Option(name = "-s", aliases = "--start", metaVar = "<start>", usage = "ISO8601 formatted start time.")
    void setStart(Timestamp start) {
        m_start = start;
    }

    @Option(name = "-e", aliases = "--end", metaVar = "<end>", usage = "ISO8601 formatted ending time.")
    void setEnd(Timestamp end) {
        m_end = end;
    }

    @Option(name = "-i", aliases = "--interval", metaVar = "<interval>", usage = "Sample interval in seconds.")
    void setInterval(Duration interval) {
        m_interval = interval;
    }

    @Option(name = "-r", aliases = "--num-resources", metaVar = "<resources>", usage = "Number of resources.")
    void setNumResources(int numResources) throws CmdLineException {
        checkArgument(numResources > 0, "Number of resources must be greater than zero.");
        m_numResources = numResources;
    }

    @Option(name = "-m", aliases = "--num-metrics", metaVar = "<metrics>", usage = "Number of metrics.")
    void setNumMetrics(int numMetrics) throws CmdLineException {
        checkArgument(numMetrics > 0, "Number of metrics must be greater than zero.");
        m_numMetrics = numMetrics;
    }

    String getCassandraHost() {
        return m_cassandraHost;
    }

    int getCassandraPort() {
        return m_cassandraPort;
    }

    String getCassandraKeyspace() {
        return m_cassandraKeyspace;
    }

    String getCassandraCompression() {
        return m_cassandraCompression;
    }

    Command getCommand() {
        return m_command;
    }

    boolean needHelp() {
        return m_needHelp;
    }

    Timestamp getStart() {
        return m_start;
    }

    Timestamp getEnd() {
        return m_end;
    }

    Duration getInterval() {
        return m_interval;
    }

    int getNumResources() {
        return m_numResources;
    }

    int getNumMetrics() {
        return m_numMetrics;
    }

    int getThreads() {
        return m_threads;
    }

    // There is (presently )no command option to assign this; Hard-coded to 2x the sample interval.
    Duration getHeartbeat() {
        return m_interval.times(2);
    }

    String[] getResources() {
        String[] resources = new String[getNumResources()];
        for (int i = 0; i < getNumResources(); i++) {
            resources[i] = String.format("r%d", i);
        }
        return resources;
    }

    String[] getMetrics() {
        String[] metrics = new String[getNumMetrics()];
        for (int i = 0; i < getNumMetrics(); i++) {
            metrics[i] = String.format("m%d", i);
        }
        return metrics;
    }

}


text:
> 🚨 This package is no longer under development. If you wish to take over this project, please [get in touch](https://github.com/idleberg/discussion/discussions/2)!
>
> # Inno Setup for Sublime Text

[![The MIT License](https://img.shields.io/badge/license-MIT-orange.svg?style=flat-square)](http://opensource.org/licenses/MIT)
[![Package Control](https://packagecontrol.herokuapp.com/downloads/Inno%20Setup.svg?style=flat-square)](https://packagecontrol.io/packages/Inno%20Setup)
[![GitHub](https://img.shields.io/github/release/idleberg/sublime-innosetup.svg?style=flat-square)](https://github.com/idleberg/sublime-innosetup/releases)
[![Travis](https://img.shields.io/travis/idleberg/sublime-innosetup.svg?style=flat-square)](https://travis-ci.org/idleberg/sublime-innosetup)

[Inno Setup](http://www.jrsoftware.org/isinfo.php) syntax definitions, completions and build system for [Sublime Text](http://www.sublimetext.com/).

**Note**: This package is compatible with Sublime Text 3 ([Build 3103](http://www.sublimetext.com/blog/articles/sublime-text-3-build-3103) or higher). Click [here](https://github.com/idleberg/sublime-innosetup/tree/subl2) for a Sublime Text 2 version of this package.

![Screenshot](https://raw.githubusercontent.com/idleberg/sublime-innosetup/master/screenshot.png)

*Screenshot of Inno Setup in Sublime Text with [Hopscotch](https://github.com/idleberg/Hopscotch) color scheme*

## Installation

### Package Control

1. Make sure you already have [Package Control](https://packagecontrol.io/) installed
2. Choose *"Install Package"* from the Command Palette (Super+Shift+p)
3. Type *"Inno Setup"* and press Enter

### Using Git

1. Change to your Sublime Text `Packages` directory
2. Clone repository `git clone https://github.com/idleberg/sublime-innosetup.git 'Inno Setup'`

### Manual installation

1. Download the latest [stable release](https://github.com/idleberg/sublime-innosetup/releases)
2. Unzip the archive to your Sublime Text `Packages` directory

## Usage

### Completions

Auto-completion will always list all available flags for a command, the first flag displayed is always the default.

### Building

Building requires a properly installed Inno Setup, and to build on macOS/Linux you need [Wine](https://www.winehq.org/). You can build your script using the default Super+b shortcut or from selecting the build option in the Tools menu. Output files will be placed in the same folder as your input.

#### Windows

Make sure that Inno Setup is installed properly and that `ISCC.exe` is in your PATH [environment variable](http://superuser.com/a/284351/195953) (it *isn't* by default!) Use the *Legacy Windows* build variant if you can't run PowerShell 3.0 (or higher) scripts.

#### macOS / Linux

With Wine and Inno Setup properly installed, use the default shortcut Super+b to build your script.

### Linter

You can install a separate [linting package](https://packagecontrol.io/packages/SublimeLinter-contrib-iscc) to highlight errors in your InnoSetup script.

## License

This work is licensed under the [The MIT License](LICENSE).

redpajama_set_name: RedPajamaGithub


text:
layout: post
title: "Using Git hook templates to avoid committing secrets to public repositories"
date: 2018-05-11 21:00:00
comments: true
published: true
tags: git security github aws
redirect_to: https://bacchi.org/posts/git-hook-templates/
---

Git doesn't have the concept of a per user global hook. It would be nice if you could create hooks in your home directory that could be executed in all repositories that you work with. Instead, it does allow you to write hooks that reside in a user specific template directory to then be copied into any repositories that you clone or create from scratch.

After following this guide to configure template hooks, when you clone or create a new repository using the `git init` command, your hooks will be copied into your new repositories.

#### Why would I want hooks in every new repository?

There could be many reasons why you want to setup a hook in every new repository. My current use case has to do with preventing AWS credentials from accidentally being committed to any of my GitHub repositories. This prevents you from having someone get into your AWS account and potentially racking up a large bill you would be responsible for. Automatically scanning your commit for any patterns that look like AWS secrets will prevent this costly mistake.

#### Template configuration

The `git init` [man page](https://git-scm.com/docs/git-init#_template_directory) talks about the Template Directory which gives us the ability to copy hooks into new repositories. It must first be configured using the `git config` command, specfying the [`init.templatedir`](https://git-scm.com/docs/git-config#git-config-inittemplateDir) which is the directory where you will store your hooks. You will run a command such as:

```
git config --global init.templatedir '~/.git_template'
```

This config directive is added to the `[init]` section in your `.gitconfig` file, which looks like the following:

```
[init]
	templatedir = ~/.git_template
```

#### Create the hook

Now we can create our hook and place it in the template hooks directory (which is actually templatedir/hooks). This hook employs `git-secrets` to prevent me from accidentally committing my AWS credentials to GitHub:

```
#!/bin/bash
#
# A git hook to run git-secrets (locally 'installed') against a repository.
# This should be extended to do much more verification and error handling,
# but is presented as a demonstration.
#
# This assumes you've already setup git-secrets patterns (i.e. "git-secrets --register-aws").

# Verify that the git-secrets file is in our path
secretspath=$(which git-secrets)
if [[ -z "${secretspath}" || ! -x "${secretspath}" ]]; then
  echo "git-secrets not found!"
  exit 1
fi

RESPONSE=`git-secrets --scan -r .`
RC=$?

if [[ $RC -eq 1 ]]; then
    # return code 1 from git-secrets indicates scan found a verboten string
    echo
    echo
    echo "ERROR: [pre-commit hook] Aborting commit because git-secrets found a prohibited pattern in this repository"
    echo "Please remove the file with the pattern in the output above from this repository!"
    echo
    exit 1
else
    # no secrets found in repo
    exit 0
fi
```

Looking in that directory we see the new hook, but we need to make it executable so I will run the command `chmod 744` on the file:

```
[user1@host hooks]$ chmod 744 ~/.git_template/hooks/pre-commit
[user1@host hooks]$ ls -l ~/.git_template/hooks
total 4
-rwxrw-r--. 1 user1 user1 931 May 11 20:34 pre-commit
```

#### Prepare a file containing a pattern that will fail the git-secrets scan

At this point we will create a new directory to test our hook. Start by creating a directory to work in:

```
[user1@host repos]$ mkdir template-dir-demo && cd template-dir-demo
```

Then create a file with a string that looks like an AWS secret(hint, the AWS secret access key is a 40 character string containing lower, upper and digit characters):

```
[user1@host template-dir-demo]$ ipython
Python 3.6.4 (default, Mar 13 2018, 18:18:20)
Type 'copyright', 'credits' or 'license' for more information
IPython 6.2.1 -- An enhanced Interactive Python. Type '?' for help.

In [1]: import random

In [2]: from string import ascii_uppercase, ascii_lowercase, digits

In [3]: chars = ascii_uppercase + ascii_lowercase + digits

In [4]: key = ''.join(random.choice(chars) for _ in range(40))

In [5]: key
Out[5]: 'dbMi8e8YYNnTUnlTEEyyYbK3KfQExuaRXF8roC9d'

[user1@host template-dir-demo]$ echo 'aws_secret_access_key = dbMi8e8YYNnTUnlTEEyyYbK3KfQExuaRXF8roC9d' > blah1.txt
[user1@host template-dir-demo]$ cat blah1.txt
aws_secret_access_key = dbMi8e8YYNnTUnlTEEyyYbK3KfQExuaRXF8roC9d
```

Now we will run `git init .` to initialize a git repository in the current directory, and we see that the pre-commit hook is copied from the template directory:

```
[user1@host template-dir-demo]$ git init .
Initialized empty Git repository in /home/user1/repos/template-dir-demo/.git/
[user1@host template-dir-demo]$ ls -altr .git/hooks/
total 12
-rwxrwxr-x. 1 user1 user1  931 May 11 20:39 pre-commit
```

#### Perform a commit

Finally, lets stage and commit the file and see if the pre-commit hook allows the file to be staged and committed:

```
[user1@host template-dir-demo]$ git add blah1.txt
[user1@host template-dir-demo]$ git commit -m "blah1 file with a secret"
./blah1.txt:1:aws_secret_access_key = dbMi8e8YYNnTUnlTEEyyYbK3KfQExuaRXF8roC9d

[ERROR] Matched one or more prohibited patterns

Possible mitigations:
- Mark false positives as allowed using: git config --add secrets.allowed ...
- Mark false positives as allowed by adding regular expressions to .gitallowed at repository's root directory
- List your configured patterns: git config --get-all secrets.patterns
- List your configured allowed patterns: git config --get-all secrets.allowed
- List your configured allowed patterns in .gitallowed at repository's root directory
- Use --no-verify if this is a one-time false positive

ERROR: [pre-commit hook] Aborting commit because git-secrets found a prohibited pattern in this repository
Please remove the file with the pattern in the output above from this repository!
```

As you can see using a Git template for hooks will help us automatically setup hooks to use in any new repository whether it is cloned or created with the `git init` command.

I hope this was helpful to you.


text:
using System.Net;
using System.Net.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;

namespace FlitBit.WebApi.Filters
{
  public class ApiModelValidationFilterAttribute : ActionFilterAttribute
  {
    public override void OnActionExecuting(HttpActionContext actionContext)
    {
      if (actionContext.ModelState.IsValid == false)
      {
        actionContext.Response = actionContext.Request.CreateErrorResponse(
            HttpStatusCode.BadRequest, actionContext.ModelState);
      }
    }
  }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace WpfUtils.Extensions
{
    public static class PropertyMethods
    {
        public static string GetName<T>(Expression<Func<T>> selector)
        {
            if (selector == null)
                return String.Empty;

            MemberExpression b = selector.Body as MemberExpression;
            if (b == null)
                throw new ArgumentException("The body must be a member expression");
            return b.Member.Name;
        }
    }
}


text:
namespace PAaaS.Server.Controllers
{
    using System;

    using Data.Repositories;
    using PAaaS.Models;
    using System.Web.Http;
    using AutoMapper.QueryableExtensions;
    using ViewModels;
    using System.Linq;

    using AutoMapper;

    using Microsoft.AspNet.Identity;
    using System.Threading;
    public class AssignmentsController : ApiController
    {
        private IRepository<Assignment> assignments;
        private IRepository<User> users;

        public AssignmentsController(IRepository<Assignment> assignments, IRepository<User> users)
        {
            Thread.Sleep(1000);
            this.users = users;
            this.assignments = assignments;
        }

        [HttpGet]
        [Route("api/Assignments/Get")]
        public IHttpActionResult GetAssignments()
        {
            var result =
                this.assignments.All()
                    .Where(x => x.State == AssignmentState.NotTakenYet)
                    .ProjectTo<AssignmentViewModel>()
                    .ToList();

            return this.Ok(result);
        }

        [HttpGet]
        [Route("api/Assignments/Get/{id}")]
        public IHttpActionResult GetAssignment(int id)
        {
            var assignment = this.assignments.GetById(id);

            if (assignment == null)
            {
                return this.NotFound();
            }

            var result = Mapper.Map<AssignmentViewModel>(assignment);
            return this.Ok(result);
        }

        [Authorize]
        [HttpGet]
        [Route("api/Assignments/GetMyPostedAssignments")]
        public IHttpActionResult GetMyPostedAssignments()
        {
            var userId = this.users
                .All()
                .Where(x => x.UserName == this.User.Identity.Name)
                .Select(x => x.Id)
                .FirstOrDefault();

            var ownAssignments = this.assignments
                .All()
                .Where(x => x.OwnerId == userId)
                .ProjectTo<AssignmentViewModel>()
                .ToList();

            return this.Ok(ownAssignments);
        }

        [Authorize]
        [HttpGet]
        [Route("api/Assignments/GetMyTakenAssignments")]
        public IHttpActionResult GetMyTakenAssignments()
        {
            var userId = this.users
                .All()
                .Where(x => x.UserName == this.User.Identity.Name)
                .Select(x => x.Id)
                .FirstOrDefault();

            var ownAssignments =
                this.assignments.All()
                    .Where(x => x.AssigneeId == userId)
                    .Where(x => x.State == AssignmentState.InProgress)
                    .ProjectTo<AssignmentViewModel>()
                    .ToList();

            return this.Ok(ownAssignments);
        }

        [Authorize]
        [HttpGet]
        [Route("api/Assignments/GetMyFinishedAssignments")]
        public IHttpActionResult GetMyFinishedAssignments()
        {
            var userId = this.users
                .All()
                .Where(x => x.UserName == this.User.Identity.Name)
                .Select(x => x.Id)
                .FirstOrDefault();

            var ownAssignments =
                this.assignments.All()
                    .Where(x => x.AssigneeId == userId)
                    .Where(x => x.State == AssignmentState.Finihed)
                    .ProjectTo<AssignmentViewModel>()
                    .ToList();

            return this.Ok(ownAssignments);
        }

        [Authorize]
        [HttpPut]
        [Route("api/Assignments/TakeAssignment/{id}")]
        public IHttpActionResult TakeAssignment(int id)
        {
            var assignment = this.assignments.GetById(id);

            if (assignment == null)
            {
                return this.NotFound();
            }

            var userId = this.User.Identity.GetUserId();
            assignment.State = AssignmentState.InProgress;
            assignment.AssigneeId = userId;

            this.assignments.SaveChanges();

            return this.Ok(Mapper.Map<AssignmentViewModel>(assignment));
        }

        [HttpPut]
        [Route("api/Assignments/FinishAssignment/{id}")]
        public IHttpActionResult FinishAssignment(int id)
        {
            var assignment = this.assignments.GetById(id);

            if (assignment == null)
            {
                return this.NotFound();
            }

            assignment.State = AssignmentState.Finihed;

            this.assignments.SaveChanges();

            return this.Ok(Mapper.Map<AssignmentViewModel>(assignment));
        }

        [Authorize]
        [HttpPost]
        [Route("api/Assignments/CreateAssignment")]
        public IHttpActionResult CreateAssignment([FromBody]AssignmentBindingModel assignment)
        {
            // TODO: Fix mapping
            var assignmentToAdd = Mapper.Map<Assignment>(assignment);
            assignmentToAdd.CreatedOn = DateTime.Now;
            assignmentToAdd.OwnerId = this.User.Identity.GetUserId();
            assignmentToAdd.State = AssignmentState.NotTakenYet;
            this.assignments.Add(assignmentToAdd);
            this.assignments.SaveChanges();

            return this.Created(this.Url.ToString(), assignment);
        }
    }
}


text:
require('dotenv').config();
if (!process.env.slacktoken) {
    console.log('Error: Specify token in environment');
    process.exit(1);
}

var Botkit = require('botkit');

var controller = Botkit.slackbot({
    debug: true,
});

var bot = controller.spawn({
    token: process.env.slacktoken
}).startRTM();

controller.on('bot_channel_join', function(bot, message){
    bot.say({
        channel: message.channel,
        text: "Yo wassup"
    });
});

controller.hears(['hello','hi'],'direct_message,direct_mention,mention',function(bot, message) {

    bot.api.reactions.add({
        timestamp: message.ts,
        channel: message.channel,
        name: 'muscle',
    },function(err, res) {
        if (err) {
            bot.botkit.log('Failed to add emoji reaction :(',err);
        }
    });

    controller.storage.users.get(message.user,function(err, user) {
        if (user && user.name) {
            bot.reply(message,'Hello ' + user.name + '!!');
        } else {
            bot.reply(message,'Hello.');
        }
    });
});


text:
<!DOCTYPE html>

  <meta charset="UTF-8">

  <title>CSS Values and Units Test: calc() function with angle values</title>

  <link rel="author" title="Gérard Talbot" href="http://www.gtalbot.org/BrowserBugsSection/css21testsuite/">
  <link rel="help" href="https://www.w3.org/TR/css-values-3/#calc-computed-value">
  <link rel="help" href="https://www.w3.org/TR/css-values-3/#angles">

  <meta content="This test checks that additions, subtractions, multiplications and divisions in calc() function when applied to angle units." name="assert">


text:
import {Injectable} from "@angular/core";
import {Observable} from "rxjs/Observable";
import {ReplaySubject} from "rxjs/ReplaySubject";
import {AppExecutionContext, ExecutorConfig} from "../../../electron/src/storage/types/executor-config";
import {AppHelper} from "../core/helpers/AppHelper";
import {LocalRepositoryService} from "../repository/local-repository.service";
import {PlatformRepositoryService} from "../repository/platform-repository.service";
import {IpcService} from "../services/ipc.service";
import {switchMap, take, takeWhile, map} from "rxjs/operators";

@Injectable()
export class ExecutorService {

    private config = new ReplaySubject<ExecutorConfig>(1);

    constructor(private ipc: IpcService,
                private localRepository: LocalRepositoryService,
                private platformRepository: PlatformRepositoryService) {

        this.localRepository.getExecutorConfig().subscribe(this.config);
    }

    getConfig<T extends keyof ExecutorConfig>(key: T): Observable<ExecutorConfig[T]> {
        return this.config.pipe(
            map(c => c[key])
        );
    }

    /**
     * Probes the executor path for Bunny version.
     * Returns a message in the format "Version: #" if successful, or a description why it failed
     */
    getVersion(): Observable<string> {
        return this.getConfig("path").pipe(
            switchMap(path => this.ipc.request("probeExecutorVersion"))
        );
    }

    /**
     * @deprecated
     */
    run(appID: string, content: string, options = {}): Observable<string> {

        const isLocal   = AppHelper.isLocal(appID);
        const appSource = isLocal ? "local" : "user";

        return this.config.pipe(
            take(1),
            switchMap(config => {
                return this.ipc.watch("executeApp", {
                    appID,
                    content,
                    appSource,
                    options,
                    config
                }).pipe(
                    takeWhile(val => val !== null)
                );
            })
        );
    }

    /**
     * Gets the configuration parameters for the execution context of a specific app
     */
    getAppConfig(appID: string): Observable<AppExecutionContext | null> {
        const metaFetch = AppHelper.isLocal(appID)
            ? this.localRepository.getAppMeta(appID, "executionConfig")
            : this.platformRepository.getAppMeta(appID, "executionConfig");

        // any is a hack-cast, but "executionConfig" key is actually of type AppExecutionContext
        return (metaFetch as any).map(meta => meta || {});
    }

    setAppConfig(appID: string, data: AppExecutionContext) {
        const isLocal = AppHelper.isLocal(appID);

        if (isLocal) {
            return this.localRepository.patchAppMeta(appID, "executionConfig", data);
        }

        return this.platformRepository.patchAppMeta(appID, "executionConfig", data);

    }
}


text:
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { RouterModule } from '@angular/router';
import { DragDropModule } from '@angular/cdk/drag-drop';

import { SharedModule } from '../shared/shared.module';

import { BoardDisplayComponent } from './board.component';
import { ColumnDisplayComponent } from './column/column.component';
import { TaskDisplayComponent } from './task/task.component';
import { BoardService } from './board.service';

@NgModule({
  imports: [
    CommonModule,
    DragDropModule,
    FormsModule,
    RouterModule,
    SharedModule
  ],
  declarations: [
    BoardDisplayComponent,
    ColumnDisplayComponent,
    TaskDisplayComponent
  ],
  providers: [ BoardService ],
  exports: [
    BoardDisplayComponent,
    ColumnDisplayComponent,
    TaskDisplayComponent,
  ]
})
export class BoardModule { }


text:
package uk.gov.hmrc.ct.ct600.v2

import uk.gov.hmrc.ct.box.{CtBoxIdentifier, CtOptionalString, Input}

case class B156(value: Option[String]) extends CtBoxIdentifier("Full Name of Nominee") with CtOptionalString with Input


text:
package com.orionplatform.math.geometry.shape.cylinder.tasks;

import com.orionplatform.core.abstraction.Orion;
import com.orionplatform.math.geometry.shape.cylinder.Cylinder;
import com.orionplatform.math.geometry.shape.cylinder.CylinderRules;

public class CylinderEqualsTask extends Orion
{
    public static synchronized boolean run(Cylinder x, Object y)
    {
        CylinderRules.isValid(x);

        if(y == null || x.getClass() != y.getClass())
        {
            return false;
        }
        else
        {
            Cylinder other = (Cylinder)y;
            return x.getRadius().equal(other.getRadius()) && x.getHeight().equal(other.getHeight());
        }
    }
}


text:
var eventTest = require("../public/json/eventTest.json");
exports.viewEvents = function(req, res){
	res.render('upcomingEvents', eventTest);
};

exports.viewGroupsEvents = function(req, res){

	var groupName = req.params.groupName;
	var date = "";
	var members = "";
	var group = "";
	var title ="";

	var events_array = [];
	var event_detail = {};
	var groupsEvents;

	var len = eventTest.groups2.length;
	var i = 0;
	for( ; i < len; i++) {
		if(eventTest.groups2[i].group == groupName) {
			title   = eventTest.groups2[i].title;
			date    = eventTest.groups2[i].when;
			members = eventTest.groups2[i].whoisgoing;
			group   = eventTest.groups2[i].group;

			event_detail = {
				"title": title,
				'when': date,
				'members': members
			}

			var d1 = new Date(); // Current time
			var d2 = new Date(eventTest.groups2[i].start); // Event time
			console.log("currently: " + d1.getTime() +   "    -- eventime: " + d2.getTime());
			if(d1.getTime() < d2.getTime()){
				events_array.push(event_detail);
				groupsEvents = {'groupsEvents': events_array};
			}
			//console.log(groupsEvents);
		}
		else {
			console.log("Couldn't initialize event fields from json!");
		}
	}
	res.render('groupsUpcomingEvents', groupsEvents);
};

exports.viewGroupsPastEvents = function(req, res){

	var groupName = req.params.groupName;
	var date = "";
	var members = "";
	var group = "";
	var title ="";

	var events_array = [];
	var event_detail = {};
	var groupsEvents;

	var len = eventTest.groups2.length;
	var i = 0;
	for( ; i < len; i++) {
		if(eventTest.groups2[i].group == groupName) {
			title   = eventTest.groups2[i].title;
			date    = eventTest.groups2[i].when;
			members = eventTest.groups2[i].whoisgoing;
			group   = eventTest.groups2[i].group;

			event_detail = {
				"title": title,
				'when': date,
				'members': members
			}

			var d1 = new Date(); // Current time
			var d2 = new Date(eventTest.groups2[i].start); // Event time
			if(d1.getTime() > d2.getTime()){
				events_array.push(event_detail);
				groupsEvents = {'groupsEvents': events_array};
			}
			//console.log(groupsEvents);
		}
		else {
			console.log("Couldn't initialize event fields from json!");
		}
	}
	res.render('groupsPastEvents', groupsEvents);
};

exports.deleteEvent = function(req,res) {

	var currEvent = req.params.eventTitle;
	var len = eventTest.groups2.length;
	for(var i = 0; i < len; i++) {
		if(typeof eventTest["groups2"][i] === 'undefined') {
			continue;
		}
		else if(eventTest["groups2"][i].title == currEvent) {
			delete eventTest["groups2"][i];
			eventTest["groups2"].splice(i,1);
			break;
		}
	}
	res.render('upcomingEvents', eventTest);
};


text:
using System;
using System.Collections.Generic;
using System.Threading;

namespace Microsoft.Owin.Throttling.Implementation
{
    public class RequestQueue
    {
        private readonly IThreadingServices _threading;
        private readonly ThreadCounts _maxThreads;
        private readonly Queue<RequestInstance> _remote = new Queue<RequestInstance>();
        private readonly Queue<RequestInstance> _local = new Queue<RequestInstance>();
        private readonly object _sync = new object();
        private readonly WaitCallback _executeIfNeeded;
        private readonly int _activeThreadsBeforeRemoteRequestsQueue;
        private readonly int _activeThreadsBeforeLocalRequestsQueue;
        private readonly int _queueLengthBeforeIncomingRequestsRejected;

        private int _count;
        private bool _stopping;
        private int _scheduled;
        private IDisposable _timer;

        public RequestQueue(ThrottlingOptions options)
        {
            if (options == null)
            {
                throw new ArgumentNullException("options");
            }
            _threading = options.ThreadingServices;
            _activeThreadsBeforeLocalRequestsQueue = options.ActiveThreadsBeforeLocalRequestsQueue;
            _activeThreadsBeforeRemoteRequestsQueue = options.ActiveThreadsBeforeRemoteRequestsQueue;
            _queueLengthBeforeIncomingRequestsRejected = options.QueueLengthBeforeIncomingRequestsRejected;

            _maxThreads = _threading.GetMaxThreads();

            _executeIfNeeded = ExecuteIfNeeded;
        }

        public void Start()
        {
            _timer = _threading.TimerCallback(TimeSpan.FromSeconds(10), ScheduleExecuteIfNeeded);
        }

        public void Stop()
        {
            _stopping = true;
            if (_timer != null)
            {
                _timer.Dispose();
                _timer = null;
            }
            while (_scheduled > 0)
            {
                Thread.Sleep(100);
            }
            if (_count != 0)
            {
                while (true)
                {
                    RequestInstance instance = DequeueInstance(false);
                    if (instance == null)
                    {
                        break;
                    }
                    instance.Reject();
                }
            }
        }

        public RequestInstance GetInstanceToExecute(RequestInstance requestInstance)
        {
            ThreadCounts availableCounts = _threading.GetAvailableThreads();
            ThreadCounts activeCounts = _maxThreads.Subtract(availableCounts);
            int active = activeCounts.Greatest();
            if (_count == 0 && active < _activeThreadsBeforeRemoteRequestsQueue)
            {
                return requestInstance;
            }

            bool isLocal = requestInstance.IsLocal;
            if (_count >= _queueLengthBeforeIncomingRequestsRejected)
            {
                requestInstance.Reject();
                return null;
            }

            requestInstance.Defer();
            QueueInstance(requestInstance, isLocal);
            if (active < _activeThreadsBeforeRemoteRequestsQueue)
            {
                return DequeueInstance(false);
            }

            if (active < _activeThreadsBeforeLocalRequestsQueue)
            {
                return DequeueInstance(true);
            }

            ScheduleExecuteIfNeeded();
            return null;
        }

        private void QueueInstance(RequestInstance instance, bool isLocal)
        {
            lock (_sync)
            {
                if (isLocal)
                {
                    _local.Enqueue(instance);
                }
                else
                {
                    _remote.Enqueue(instance);
                }
                _count++;
            }
        }

        private RequestInstance DequeueInstance(bool localOnly)
        {
            while (_count != 0)
            {
                RequestInstance instance;
                lock (_sync)
                {
                    if (_local.Count != 0)
                    {
                        instance = _local.Dequeue();
                        _count--;
                    }
                    else if (!localOnly && _remote.Count != 0)
                    {
                        instance = _remote.Dequeue();
                        _count--;
                    }
                    else
                    {
                        return null;
                    }
                }

                if (instance.IsConnected)
                {
                    return instance;
                }
                instance.RejectSilent();
            }
            return null;
        }

        private void ScheduleExecuteIfNeeded()
        {
            if (_stopping)
            {
                return;
            }
            if (_count == 0)
            {
                return;
            }
            if (_scheduled >= 2)
            {
                return;
            }
            ThreadCounts available = _threading.GetAvailableThreads();
            int active = _maxThreads.WorkerThreads - available.WorkerThreads;
            if (active >= _activeThreadsBeforeLocalRequestsQueue)
            {
                return;
            }
            Interlocked.Increment(ref _scheduled);
            _threading.QueueCallback(_executeIfNeeded, null);
        }

        private void ExecuteIfNeeded(object state)
        {
            Interlocked.Decrement(ref _scheduled);
            if (_stopping)
            {
                return;
            }
            if (_count == 0)
            {
                return;
            }
            ThreadCounts available = _threading.GetAvailableThreads();
            int active = _maxThreads.WorkerThreads - available.WorkerThreads;
            if (active >= _activeThreadsBeforeLocalRequestsQueue)
            {
                return;
            }
            bool localOnly = active >= _activeThreadsBeforeRemoteRequestsQueue;
            RequestInstance instance = DequeueInstance(localOnly);
            if (instance == null)
            {
                return;
            }
            ScheduleExecuteIfNeeded();
            instance.Execute();
        }
    }
}


text:
<!doctype html>

        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
        <title>Foam Fest | Remorker Architects</title>
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="apple-touch-icon" href="apple-touch-icon.png">

        <link rel="stylesheet" href="../css/bootstrap.min.css">
        <link rel="stylesheet" href="../css/bootstrap-theme.min.css">
        <link rel="stylesheet" href="../css/main.css">
		    <link rel="stylesheet" href="../css/sidebar-p.css">
		<link rel="stylesheet" href="../css/lightbox.css">

		<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">
		<link href='https://fonts.googleapis.com/css?family=Lato:400,300,700&subset=latin,latin-ext' rel='stylesheet' type='text/css'>

			<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#hidden-navbar">
				Menu

			</button>

01 News

02 Projects

Interior design

Architecture

Competitions

                        Furniture design

03 Publications

04 Team

05 Contact

06 Backstage

01 News

02 Projects

Interior design

Architecture

Competitions

                      Furniture design

03 Publications

04 Team

05 Contact

06 Backstage

Foam Fest

location:

design team:

co-workers:

area:

project year:

 Belgrade, Serbia

Marko Korošec

Darko Rašeta, Vanja Paunović, Ivana Radović

450.0 sqm

2014

The first Belgrade Foam Fest was hosted in 2009 and in the next six years, it has grown into the largest foam party in Europe, with over 70,000 visitors. "Belgrade Arena" hosted the event during the first five years. For the sixth edition, the event changed location, to Ada Lake.

The proposition for several stages design was given, together with the mail stage which was to be on water. The speaker-like stage on water with a DJ in its woofer's center is the main accent of the design.


text:
package org.sakaiproject.entitybroker.entityprovider.extension;

import java.util.List;

import org.sakaiproject.entitybroker.entityprovider.capabilities.TagProvideable;
import org.sakaiproject.entitybroker.entityprovider.capabilities.Taggable;

/**
 * Defines the methods necessary for searching for entities by tags (shared interface)
 * @deprecated use {@link TagProvideable} and {@link TagProvider} instead
 *
 * @author Aaron Zeckoski (aaron@caret.cam.ac.uk)
 */
public interface TagSearchProvider {

   /**
    * Search for all entities with a set of tags (as defined by the {@link Taggable} interface)
    *
    * @param tags a set of tags defined on these entities in the {@link Taggable} interface
    * @param params (optional) incoming set of parameters which may be used to send data specific to this request, may be null
    * @return a list of globally unique references to entities with these tags
    * @deprecated use {@link TagProvideable} and {@link TagProvider} instead
    */
   public List<String> findEntityRefsByTags(String[] tags);
//   public List<String> findEntityRefsByTags(String[] tags, Map<String, Object> params);

}


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

  <meta http-equiv="content-type" content="text/html; charset=UTF-8">
  <title>Create a new secondary index for a relation</title>

dbplus_rrename

dbplus_runlink

DB++ Functions

PHP Manual

dbplus_rsecindex

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_rsecindex — Create a new secondary index for a relation

Description

   mixed dbplus_rsecindex
    ( resource $relation
   , mixed $domlist
   , int $type
   )

   dbplus_rsecindex() will create a new secondary
   index for relation with consists of the
   domains specified by domlist and is of
   type type

Parameters

relation

       A relation opened by dbplus_open().

domlist

       A combination of domains. May be passed as a single domain name
       string or as an array of domain names.

type

Return Values

   Returns resource on success or DBPLUS_ERR_UNKNOWN on
   failure.

Notes

Warning
This function is
EXPERIMENTAL. The behaviour of this function, its name, and
surrounding documentation may change without notice in a future release of PHP.
This function should be used at your own risk.

dbplus_rrename

dbplus_runlink

DB++ Functions

PHP Manual


text:
<?xml version="1.0" encoding="UTF-8"?>
<script xmlns="http://dtf.org/v1" name="create_delete_collection_box.net">
    <info>
        <author>
            <name>Rodney Gomes</name>
            <email>rlgomes@yahoo-inc.com</email>
        </author>
        <description></description>
    </info>

    <local>
        <createstorage id="INPUT" path="${dtf.xml.path}/input" />
        <createstorage id="OUTPUT" path="${dtf.xml.path}/output" />
        <loadproperties uri="storage://INPUT/box.net.properties" />
    </local>

    <http_config id="CONFIG">
        <credentials username="dtftesting@gmail.com" password="pass4dtftesting" />
    </http_config>

    <record uri="storage://OUTPUT/mkcol_events.txt">
        <for property="i" range="1..3">
            <http_request method="MKCOL" uri="http://www.box.net/dav/test${i}">
                <http_config refid="CONFIG" />
            </http_request>
            <log>created ${http.MKCOL.uri}</log>
        </for>
    </record>

    <query uri="storage://OUTPUT/mkcol_events.txt" cursor="events" />

    <iterate cursor="events">
        <http_delete uri="${events.uri}">
            <http_config refid="CONFIG" />
        </http_delete>
        <log>deleted ${events.uri}</log>
    </iterate>

</script>


text:
"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = formatRelative;
var formatRelativeLocale = {
  lastWeek: "'지난' eeee p",
  yesterday: "'어제' p",
  today: "'오늘' p",
  tomorrow: "'내일' p",
  nextWeek: "'다음' eeee p",
  other: 'P'
};

function formatRelative(token, _date, _baseDate, _options) {
  return formatRelativeLocale[token];
}

module.exports = exports.default;


text:
import Mock from 'mockjs'

let printer = []

for (let i = 0; i < 10; i++) {
  printer.push(Mock.mock({
    id: Mock.Random.integer(),
    printname: Mock.Random.cname(),
    ip: Mock.Random.integer(),
    machine_key: Mock.Random.integer(),
    regionname: '区域负责人'
  }))
}

export default printer


text:
using System;

namespace _05.PizzaCalories
{
    public class Topping
    {
        private const int MinWeight = 1;
        private const int MaxWeight = 50;
        private const double BaseCalloriesPerGram = 2;
        private string type;
        private double weight;

        public Topping(string type, double weight)
        {
            this.Type = type;
            this.Weight = weight;
        }

        public string Type
        {
            get
            {
                return this.type;
            }

            set
            {
                if (value.ToLower() != "meat" && value.ToLower() != "veggies" && value.ToLower() != "cheese" && value.ToLower() != "sauce")
                {
                    throw new ArgumentException($"Cannot place {value} on top of your pizza.");
                }

                this.type = value;
            }
        }

        public double Weight
        {
            get
            {
                return this.weight;
            }

            set
            {
                if (value < MinWeight || value > MaxWeight)
                {
                    throw new ArgumentException($"{this.Type} weight should be in the range [{MinWeight}..{MaxWeight}].");
                }

                this.weight = value;
            }
        }

        public double CalculateCalories()
        {
            var type = 0d;

            if (this.Type.ToLower() == "meat")
            {
                type = 1.2;
            }
            else if (this.Type.ToLower() == "veggies")
            {
                type = 0.8;
            }
            else if (this.Type.ToLower() == "cheese")
            {
                type = 1.1;
            }
            else if (this.Type.ToLower() == "sauce")
            {
                type = 0.9;
            }

            var result = BaseCalloriesPerGram * this.Weight * type;
            return result;
        }
    }
}


text:
/*global angular*/

var WebChess = angular.module('WebChess', ['ngRoute']);

WebChess.config(['$routeProvider', function ($routeProvider) {
    'use strict';
    $routeProvider
        .when('/home', {
            templateUrl: 'partials/home.html',
            controller: 'HomeCtrl'
        })
        .when('/about', {
            templateUrl: 'partials/about.html'
        })
        .otherwise({
            redirectTo : '/home'
        });
}]);


text:
package impl

import (
	"fmt"
	"reflect"
	"strconv"

	"google.golang.org/protobuf/encoding/prototext"
	"google.golang.org/protobuf/internal/errors"
	"google.golang.org/protobuf/proto"
	pref "google.golang.org/protobuf/reflect/protoreflect"
	piface "google.golang.org/protobuf/runtime/protoiface"
)

// Export is a zero-length named type that exists only to export a set of
// functions that we do not want to appear in godoc.
type Export struct{}

// NewError formats a string according to the format specifier and arguments and
// returns an error that has a "proto" prefix.
func (Export) NewError(f string, x ...interface{}) error {
	return errors.New(f, x...)
}

// enum is any enum type generated by protoc-gen-go
// and must be a named int32 type.
type enum = interface{}

// EnumOf returns the protoreflect.Enum interface over e.
// It returns nil if e is nil.
func (Export) EnumOf(e enum) pref.Enum {
	switch e := e.(type) {
	case nil:
		return nil
	case pref.Enum:
		return e
	default:
		return legacyWrapEnum(reflect.ValueOf(e))
	}
}

// EnumDescriptorOf returns the protoreflect.EnumDescriptor for e.
// It returns nil if e is nil.
func (Export) EnumDescriptorOf(e enum) pref.EnumDescriptor {
	switch e := e.(type) {
	case nil:
		return nil
	case pref.Enum:
		return e.Descriptor()
	default:
		return LegacyLoadEnumDesc(reflect.TypeOf(e))
	}
}

// EnumTypeOf returns the protoreflect.EnumType for e.
// It returns nil if e is nil.
func (Export) EnumTypeOf(e enum) pref.EnumType {
	switch e := e.(type) {
	case nil:
		return nil
	case pref.Enum:
		return e.Type()
	default:
		return legacyLoadEnumType(reflect.TypeOf(e))
	}
}

// EnumStringOf returns the enum value as a string, either as the name if
// the number is resolvable, or the number formatted as a string.
func (Export) EnumStringOf(ed pref.EnumDescriptor, n pref.EnumNumber) string {
	ev := ed.Values().ByNumber(n)
	if ev != nil {
		return string(ev.Name())
	}
	return strconv.Itoa(int(n))
}

// message is any message type generated by protoc-gen-go
// and must be a pointer to a named struct type.
type message = interface{}

// legacyMessageWrapper wraps a v2 message as a v1 message.
type legacyMessageWrapper struct{ m pref.ProtoMessage }

func (m legacyMessageWrapper) Reset()         { proto.Reset(m.m) }
func (m legacyMessageWrapper) String() string { return Export{}.MessageStringOf(m.m) }
func (m legacyMessageWrapper) ProtoMessage()  {}

// ProtoMessageV1Of converts either a v1 or v2 message to a v1 message.
// It returns nil if m is nil.
func (Export) ProtoMessageV1Of(m message) piface.MessageV1 {
	switch mv := m.(type) {
	case nil:
		return nil
	case piface.MessageV1:
		return mv
	case unwrapper:
		return Export{}.ProtoMessageV1Of(mv.protoUnwrap())
	case pref.ProtoMessage:
		return legacyMessageWrapper{mv}
	default:
		panic(fmt.Sprintf("message %T is neither a v1 or v2 Message", m))
	}
}

func (Export) protoMessageV2Of(m message) pref.ProtoMessage {
	switch mv := m.(type) {
	case nil:
		return nil
	case pref.ProtoMessage:
		return mv
	case legacyMessageWrapper:
		return mv.m
	case piface.MessageV1:
		return nil
	default:
		panic(fmt.Sprintf("message %T is neither a v1 or v2 Message", m))
	}
}

// ProtoMessageV2Of converts either a v1 or v2 message to a v2 message.
// It returns nil if m is nil.
func (Export) ProtoMessageV2Of(m message) pref.ProtoMessage {
	if m == nil {
		return nil
	}
	if mv := (Export{}).protoMessageV2Of(m); mv != nil {
		return mv
	}
	return legacyWrapMessage(reflect.ValueOf(m)).Interface()
}

// MessageOf returns the protoreflect.Message interface over m.
// It returns nil if m is nil.
func (Export) MessageOf(m message) pref.Message {
	if m == nil {
		return nil
	}
	if mv := (Export{}).protoMessageV2Of(m); mv != nil {
		return mv.ProtoReflect()
	}
	return legacyWrapMessage(reflect.ValueOf(m))
}

// MessageDescriptorOf returns the protoreflect.MessageDescriptor for m.
// It returns nil if m is nil.
func (Export) MessageDescriptorOf(m message) pref.MessageDescriptor {
	if m == nil {
		return nil
	}
	if mv := (Export{}).protoMessageV2Of(m); mv != nil {
		return mv.ProtoReflect().Descriptor()
	}
	return LegacyLoadMessageDesc(reflect.TypeOf(m))
}

// MessageTypeOf returns the protoreflect.MessageType for m.
// It returns nil if m is nil.
func (Export) MessageTypeOf(m message) pref.MessageType {
	if m == nil {
		return nil
	}
	if mv := (Export{}).protoMessageV2Of(m); mv != nil {
		return mv.ProtoReflect().Type()
	}
	return legacyLoadMessageInfo(reflect.TypeOf(m), "")
}

// MessageStringOf returns the message value as a string,
// which is the message serialized in the protobuf text format.
func (Export) MessageStringOf(m pref.ProtoMessage) string {
	return prototext.MarshalOptions{Multiline: false}.Format(m)
}


text:
export function changeLocation(location) {
  return {
    type: 'CHANGE_LOCATION',
    location
  };
}

export function changeUnitType(unitType) {
  return {
    type: 'CHANGE_UNIT_TYPE',
    unitType
  };
}

export function setAlert({type, message}) {
  return {
    type: 'SET_ALERT',
    alert: {
      type,
      message
    }
  };
}

export function hideAlert() {
  return {
    type: 'SET_ALERT',
    alert: {}
  };
}

export function setTooltip({x, y, contentElement, originTarget, title}) {
  return {
    type: 'SET_TOOLTIP',
    tooltip: {
      x,
      y,
      contentElement,
      originTarget,
      title
    }
  };
}

export function hideTooltip() {
  return {
    type: 'SET_TOOLTIP',
    tooltip: {}
  };
}


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

#include "chrome/browser/ui/search/instant_page.h"

#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/search/search.h"
#include "chrome/browser/ui/search/search_model.h"
#include "chrome/browser/ui/search/search_tab_helper.h"
#include "chrome/common/url_constants.h"
#include "content/public/browser/navigation_controller.h"
#include "content/public/browser/navigation_details.h"
#include "content/public/browser/navigation_entry.h"
#include "content/public/browser/notification_service.h"
#include "content/public/browser/notification_source.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/web_contents.h"
#include "content/public/common/frame_navigate_params.h"

InstantPage::Delegate::~Delegate() {
}

InstantPage::~InstantPage() {
  if (web_contents()) {
    SearchTabHelper::FromWebContents(web_contents())->model()->RemoveObserver(
        this);
  }
}

bool InstantPage::supports_instant() const {
  return web_contents() &&
      SearchTabHelper::FromWebContents(web_contents())->SupportsInstant();
}

const std::string& InstantPage::instant_url() const {
  return instant_url_;
}

bool InstantPage::IsLocal() const {
  return web_contents() &&
      web_contents()->GetURL() == GURL(chrome::kChromeSearchLocalNtpUrl);
}

InstantPage::InstantPage(Delegate* delegate,
                         const std::string& instant_url,
                         Profile* profile)
    : profile_(profile),
      delegate_(delegate),
      instant_url_(instant_url) {
}

void InstantPage::SetContents(content::WebContents* new_web_contents) {
  ClearContents();

  if (!new_web_contents)
    return;

  Observe(new_web_contents);
  SearchModel* model =
      SearchTabHelper::FromWebContents(web_contents())->model();
  model->AddObserver(this);

  // Already know whether the page supports instant.
  if (model->instant_support() != INSTANT_SUPPORT_UNKNOWN)
    InstantSupportDetermined(model->instant_support() == INSTANT_SUPPORT_YES);
}

bool InstantPage::ShouldProcessAboutToNavigateMainFrame() {
  return false;
}

void InstantPage::DidCommitProvisionalLoadForFrame(
    content::RenderFrameHost* render_frame_host,
    const GURL& url,
    ui::PageTransition /* transition_type */) {
  if (!render_frame_host->GetParent() &&
      ShouldProcessAboutToNavigateMainFrame())
    delegate_->InstantPageAboutToNavigateMainFrame(web_contents(), url);
}

void InstantPage::ModelChanged(const SearchModel::State& old_state,
                               const SearchModel::State& new_state) {
  if (old_state.instant_support != new_state.instant_support)
    InstantSupportDetermined(new_state.instant_support == INSTANT_SUPPORT_YES);
}

void InstantPage::InstantSupportDetermined(bool supports_instant) {
  delegate_->InstantSupportDetermined(web_contents(), supports_instant);

  // If the page doesn't support Instant, stop listening to it.
  if (!supports_instant)
    ClearContents();
}

void InstantPage::ClearContents() {
  if (web_contents()) {
    SearchTabHelper::FromWebContents(web_contents())->model()->RemoveObserver(
        this);
  }

  Observe(NULL);
}


text:
const _         = require('lodash');
const Immutable = require('immutable');
const util      = require('./helper-util.js');
const _M        = require('../manager/manager-index.js');

/**
 * Not going to lie this sorta melted my mind a bit to recursive for my taste.
 * The basic gist is we need to recusivly find/check if a key exsits in the obj
 * and if it does remove the key and its value from said object.
 * @param  {obj} obj        -> raw data obj
 * @param  {arr} keys       -> An array of keys
 * @param  {bln} removeKey  -> to remove key and value from return obj
 * @return {obj}            -> cleaned prbly of key
 */
const findKey = function (obj, keys, option = {}) {
  option = _.defaults(option, {
    removeKey: true,
    processAnim: false,
    moveGlobal: false,
    addToStatic: false,
    addToOption: false,
    depth: 0
  });
  let removeKey   = option.removeKey;
  let processAnim = option.processAnim;
  let moveGlobal  = option.moveGlobal;
  let addToOption = option.addToOption;
  let optionKey   = option.optionKey;
  let lookupDepth = option.depth;

  /**
   * This is just a recusive funk to see if the key exsits in the obj
   * but the catch is we need to keep track of the path so we can latter remove
   * the key/val from the object need be. I'm not sure if there is an easier way
   * to do this but fuck it, I'm fucking done with this funk, I'm happy enough.
   * @param  {obj}  _obj      -> data obj
   * @param  {str}  _key      -> key for which we are looking to see if a val
   *                             is present in obj
   * @param  {arr}   keyPath  -> The current path of the object
   *                             ex. {one: {two: ...} => ['one', 'two']
   * @param  {arr}  rootKeys  -> The base root keys for the objected needed to
   *                             keep of the path
   * @param  {num}  keyLength -> For slicing bullshit
   * @return {obj || fasle}   -> Depends if it finds shit.
  */
  const hasKey = function (_obj, _key, keyPath = [], rootKeys, keyLength = 0, depth = 0) {
    //set init rootKey
    rootKeys = rootKeys ? rootKeys : _.keys(_obj);
    //if key exsists in cur obj rtn
    if (_obj[_key]) {
      keyPath.push(_key);
      let val = _obj[_key];
      return {
        val,
        keyPath
      };
    }

    //Cycle through obj keys
    for (let p in _obj) {
      //eslint tells me I should do this, I really should just forEach
      //but when in rome
      if ({}.hasOwnProperty.call(_obj, p)) {
        //verify we are working with a obj
        if (_.isObject(_obj[p])) {
          //push in current key at hand
          keyPath.push(p);
          //check to make sure path exisits in original obj, note this is not `_obj`
          if (!_.has(obj, keyPath)) {
            //if key is OG then set it
            if (_.includes(rootKeys, p)) {
              keyPath = [p];
            }else {
              //Otherwise we take a step back and slice off the end depending
              //on how deep we are so we can push on the new to key to check
              //if it exsits otherwiser we revert back to the OG rootkey
              keyPath = keyPath.slice(0, (keyLength * -1));
              keyPath.push(p);
              if (!_.has(obj, keyPath)) {
                keyPath = [keyPath[0]];
              }
            }
          }
          //bump depth
          depth += 1;
          let res;
          //The recurive magic
          if (lookupDepth !== 0 && depth < lookupDepth) {
            res = hasKey(_obj[p], _key, keyPath, rootKeys, keyPath.length, depth);
          }
          //no depth limit
          if (lookupDepth === 0) {
            res = hasKey(_obj[p], _key, keyPath, rootKeys, keyPath.length, depth);
          }
          if (res) {
            return res;
          }
        }
      }
    }
    //default
    return false;
  };

  /**
   * This baby removes the key/val, using the keyPath from our hasKey funk
   * not sure if this is the best way to do this as well but like I said before
   * I am done working on this funk. Its recursive too.
   * @param  {obj} _obj -> object which remove key/val
   * @param  {arr} path -> made up of string, its our path reffrance
   * @return {obj}      -> cleaned of key/val
   */
  const removeObjKey = function (_obj, path) {
    //reduce and reuse in life.
    return _.reduce(path, function (prv, key, index, list) {
      if (!key) {
        return prv;
      }else if (list.length === 1) {
        if (processAnim && (key === 'anim' || key === 'animation')) {
          //if we get here this means there is a global animation within the
          //state, ie hover: {anim: {..}} so we place that anim within a
          //on object for that state and throw it back into the queueu to be
          //processed as such
          let animProps = _.cloneDeep(prv[key]);
          //format object to be prossed
          animProps = {[option.key]: {on: {
            animation: animProps
          }}};
          //process animation via throwing it back into queue
          _M._queue.add(Immutable.fromJS({
            data: animProps,
            target: option.target
          }));

          return _.omit(prv, key);
        }
        //backs key out and places in parent
        if (moveGlobal) {
          let globalVal = prv[key];
          let _prv = _.omit(prv, key);
          return _.defaults(_prv, globalVal);
        }
        return _.omit(prv, key);
      }
      path.shift();
      //recursive magic
      prv[key] = removeObjKey(_obj[key], path);
      return prv;
    }, _obj);
  };

  //Loop though the key array
  for (let i = 0; i < keys.length; i++) {
    let key = keys[i];
    let res = hasKey(obj, key);
    if (res) {
      let keyVal = res.val;
      //remove key
      if (removeKey) {
        obj = removeObjKey(obj, res.keyPath);
      }
      //add to option obj
      if (addToOption) {
        let optKey = optionKey || key;
        if (!obj.option) {
          obj.option = {[optKey]: keyVal};
        }else {
          obj.option = util.merge(obj.option, {[optKey]: keyVal});
        }
      }
      return {
        data: obj,
        keyVal: keyVal
      };
    }
  }

  return {
    data: obj,
    keyVal: null
  };
};

module.exports = findKey;


text:
using Autofac;
using PocketHub.Server.Lib.MainWindows;
using PocketHub.Server.Lib.SignalRHubs;
using Repo2.SDK.WPF45.Extensions.IOCExtensions;
using System;
using System.Windows;

namespace PocketHub.Server.Lib.ComponentRegistry
{
    public abstract class ServerRegistryBase2 : ServerRegistryBase
    {
        protected abstract void RegisterServerComponents(ContainerBuilder b, Application app);

        protected override void RegisterHubComponents(ContainerBuilder b, Application app)
        {
            MainHubWindowVM1.Title = MainWindowTitle;

            b.Solo<MainHubWindowVM1>();
            b.Hub<UserAccountHub>();

            RegisterServerComponents(b, app);
        }

        protected override void RegisterHubs()
        {
        }

        protected virtual string MainWindowTitle => "Hub Server";

        protected override object ResolveMainWindowVM()
            => Resolve<MainHubWindowVM1>();

        protected override void AddResourceDictionaries(Application app)
            => AddToMergedDictionaries(app,
                @"/Repo2.SDK.WPF45;component/Styles/BasicDatagridTheme1.xaml",
                @"/Repo2.SDK.WPF45;component/Styles/DatagridTheme2.xaml",
                @"/Repo2.SDK.WPF45;component/Styles/FontAwesomeButtonTheme1.xaml",
                @"/Repo2.SDK.WPF45;component/Styles/ConvertersSet1.xaml",
                @"/Repo2.SDK.WPF45;component/Styles/NonReloadingTabControlTheme1.xaml",
                @"/Repo2.SDK.WPF45;component/Styles/ButtonsTheme1.xaml",
                @"/Repo2.SDK.WPF45;component/Styles/TextBlockTheme1.xaml");

        private void AddToMergedDictionaries(Application app, params string[] sources)
        {
            foreach (var src in sources)
            {
                var uri = new Uri(src, UriKind.Relative);
                var res = new ResourceDictionary { Source = uri };
                app.Resources.MergedDictionaries.Add(res);
            }
        }
    }
}


text:
from datetime import datetime
import mock
import unittest

from airflow.utils import operator_helpers

class TestOperatorHelpers(unittest.TestCase):

    def setUp(self):
        super(TestOperatorHelpers, self).setUp()
        self.dag_id = 'dag_id'
        self.task_id = 'task_id'
        self.execution_date = '2017-05-21T00:00:00'
        self.context = {
            'dag': mock.MagicMock(name='dag', dag_id=self.dag_id),
            'dag_run': mock.MagicMock(
                name='dag_run',
                execution_date=datetime.strptime(self.execution_date,
                                                 '%Y-%m-%dT%H:%M:%S'),
            ),
            'task': mock.MagicMock(name='task', task_id=self.task_id),
            'task_instance': mock.MagicMock(
                name='task_instance',
                execution_date=datetime.strptime(self.execution_date,
                                                 '%Y-%m-%dT%H:%M:%S'),
            ),
        }

    def test_context_to_airflow_vars_empty_context(self):
        self.assertDictEqual(operator_helpers.context_to_airflow_vars({}), {})

    def test_context_to_airflow_vars_all_context(self):
        self.assertDictEqual(
            operator_helpers.context_to_airflow_vars(self.context),
            {
                'airflow.ctx.dag.dag_id': self.dag_id,
                'airflow.ctx.dag_run.execution_date': self.execution_date,
                'airflow.ctx.task.task_id': self.task_id,
                'airflow.ctx.task_instance.execution_date': self.execution_date,
            }
        )

if __name__ == '__main__':
    unittest.main()