text:
[![Build Status](https://dev.azure.com/asottile/asottile/_apis/build/status/asottile.css-explore?branchName=main)](https://dev.azure.com/asottile/asottile/_build/latest?definitionId=42&branchName=main)
[![Azure DevOps coverage](https://img.shields.io/azure-devops/coverage/asottile/asottile/42/main.svg)](https://dev.azure.com/asottile/asottile/_build/latest?definitionId=42&branchName=main)
[![pre-commit.ci status](https://results.pre-commit.ci/badge/github/asottile/css-explore/main.svg)](https://results.pre-commit.ci/latest/github/asottile/css-explore/main)

css-explore
===========

This originally started as a tool to visualize the parse tree of a css
document, but more or less turned into a pretty printer.

The reason I made this project was to compare compilation outputs of various
implementations of scss in an effort to switch a codebase from one compiler
to another.

This uses:
- [reworkcss/css](https://github.com/reworkcss/css) for parsing
- [ekalinin/nodeenv](https://github.com/ekalinin/nodeenv) for bootstrapping node

## Usage

```console
$ css-format --help
usage: css-format [-h] filename

positional arguments:
  filename

optional arguments:
  -h, --help  show this help message and exit
```

Example run:

```console
$ echo 'body{color:red}' > test.css
$ css-format test.css
body {
    color: red;
}
```


text:
*Sets up VSCode for ultimate productivity with React Native*

Use `yo rn-toolbox:vscode` to set it up

redpajama_set_name: RedPajamaGithub


text:
import java.io.File;
import com.badlogic.gdx.jnigen.AntScriptGenerator;
import com.badlogic.gdx.jnigen.BuildConfig;
import com.badlogic.gdx.jnigen.BuildTarget;
import com.badlogic.gdx.jnigen.NativeCodeGenerator;
import com.badlogic.gdx.jnigen.BuildTarget.TargetOs;

public class build {
    public static void main (String[] args) throws Exception {
        String[] headers = {"nonlua", "luajit"};

        BuildTarget win32 = BuildTarget.newDefaultTarget(TargetOs.Windows, false);
        win32.headerDirs = headers;
        win32.cFlags += " -DLUASOCKET_INET_PTON";
        win32.cppFlags += " -DLUASOCKET_INET_PTON";
        win32.libraries = "-lws2_32 -lwinmm -L./../../../libs/windows32 -lluajit ";
        win32.linkerFlags = win32.linkerFlags.replace(" -static ", " ");

        BuildTarget win64 = BuildTarget.newDefaultTarget(TargetOs.Windows, true);
        win64.headerDirs = headers;
        win64.cFlags += " -DLUASOCKET_INET_PTON";
        win64.cppFlags += " -DLUASOCKET_INET_PTON";
        win64.libraries = "-lws2_32 -lwinmm -L./../../../libs/windows64 -lluajit64";
        win64.linkerFlags = win64.linkerFlags.replace(" -static ", " ");

        BuildTarget lin32 = BuildTarget.newDefaultTarget(TargetOs.Linux, false);
        lin32.headerDirs = headers;
        lin32.cFlags += " -DLUASOCKET_INET_PTON";
        lin32.cppFlags += " -DLUASOCKET_INET_PTON";
        lin32.libraries = "-L./../../../libs/linux32 -lluajit ";

        BuildTarget lin64 = BuildTarget.newDefaultTarget(TargetOs.Linux, true);
        lin64.headerDirs = headers;
        lin64.cFlags += " -DLUASOCKET_INET_PTON";
        lin64.cppFlags += " -DLUASOCKET_INET_PTON";
        lin64.libraries = "-L./../../../libs/linux64 -lluajit64";

        BuildTarget mac32 = BuildTarget.newDefaultTarget(TargetOs.MacOsX, false);
        mac32.headerDirs = headers;
        mac32.libraries = "-L./../../../libs/macosx32 -lluajit ";

        BuildTarget mac64 = BuildTarget.newDefaultTarget(TargetOs.MacOsX, true);
        mac64.headerDirs = headers;
        mac64.libraries = "-L./../../../libs/macosx64 -lluajit64 ";

        BuildTarget android = BuildTarget.newDefaultTarget(TargetOs.Android, false);
        android.headerDirs = headers;

        BuildTarget ios = BuildTarget.newDefaultTarget(TargetOs.IOS, false);
        ios.headerDirs = headers;
        ios.libraries = "-L./../../../libs/ios32 -lluajit";

        new NativeCodeGenerator().generate("src", "target/classes", "jni");
        new AntScriptGenerator().generate(new BuildConfig("nonlua"), win32, win64, lin32, lin64, mac32, mac64, android, ios);
    }
}


text:
using Microsoft.CodeAnalysis;

namespace Orleans.CodeGenerator.Diagnostics;

public class InaccessibleSetterDiagnostic
{
    public const string RuleId = "ORLEANS0101";
    private const string Category = "Usage";
    private static readonly LocalizableString Title = new LocalizableResourceString(nameof(Resources.InaccessibleSetterTitle), Resources.ResourceManager, typeof(Resources));
    private static readonly LocalizableString MessageFormat = new LocalizableResourceString(nameof(Resources.InaccessibleSetterMessageFormat), Resources.ResourceManager, typeof(Resources));
    private static readonly LocalizableString Description = new LocalizableResourceString(nameof(Resources.InaccessibleSetterDescription), Resources.ResourceManager, typeof(Resources));

    internal static DiagnosticDescriptor Rule { get; } = new(RuleId, Title, MessageFormat, Category, DiagnosticSeverity.Error, isEnabledByDefault: true, description: Description);

    public static Diagnostic CreateDiagnostic(Location location, string identifier) => Diagnostic.Create(Rule, location, identifier);
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<CustomFieldTranslation xmlns="http://soap.sforce.com/2006/04/metadata">
    <name>Active__c</name>
    <help>Ilmaisee, onko tämä käynnistimen käsittelijä käytössä.</help>
    <label>Aktiivinen</label>
</CustomFieldTranslation>


text:
Pattern: Use of `I18n.locale=`

Issue: -

## Description

Checks for the use of `I18n.locale=` method.

The `locale` attribute persists for the rest of the Ruby runtime, potentially causing unexpected behavior at a later time. Using `I18n.with_locale` ensures the code passed in the block is the only place `I18n.locale` is affected. It eliminates the possibility of a `locale` sticking around longer than intended.

## Examples

```ruby
# bad
I18n.locale = :fr

# good
I18n.with_locale(:fr) do
end
```

## Further Reading

* [RuboCop - Rails/I18nLocaleAssignment](https://docs.rubocop.org/rubocop-rails/cops_rails.html#railsi18nlocaleassignment)


text:
<?php

function smilies_content(&$a) { return smilies('',true); }


text:
.class Landroid/support/v4/print/PrintHelperKitkat$2$1$1;
.super Ljava/lang/Object;
.source "PrintHelperKitkat.java"

# interfaces
.implements Landroid/os/CancellationSignal$OnCancelListener;

# annotations
.annotation system Ldalvik/annotation/EnclosingMethod;
    value = Landroid/support/v4/print/PrintHelperKitkat$2$1;->onPreExecute()V
.end annotation

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

# instance fields
.field final synthetic this$2:Landroid/support/v4/print/PrintHelperKitkat$2$1;

# direct methods
.method constructor <init>(Landroid/support/v4/print/PrintHelperKitkat$2$1;)V
    .locals 0

    .prologue
    .line 351
    iput-object p1, p0, Landroid/support/v4/print/PrintHelperKitkat$2$1$1;->this$2:Landroid/support/v4/print/PrintHelperKitkat$2$1;

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

    return-void
.end method

# virtual methods
.method public onCancel()V
    .locals 2

    .prologue
    .line 354
    iget-object v0, p0, Landroid/support/v4/print/PrintHelperKitkat$2$1$1;->this$2:Landroid/support/v4/print/PrintHelperKitkat$2$1;

    iget-object v0, v0, Landroid/support/v4/print/PrintHelperKitkat$2$1;->this$1:Landroid/support/v4/print/PrintHelperKitkat$2;

    # invokes: Landroid/support/v4/print/PrintHelperKitkat$2;->cancelLoad()V
    invoke-static {v0}, Landroid/support/v4/print/PrintHelperKitkat$2;->access$200(Landroid/support/v4/print/PrintHelperKitkat$2;)V

    .line 355
    iget-object v0, p0, Landroid/support/v4/print/PrintHelperKitkat$2$1$1;->this$2:Landroid/support/v4/print/PrintHelperKitkat$2$1;

    const/4 v1, 0x0

    invoke-virtual {v0, v1}, Landroid/support/v4/print/PrintHelperKitkat$2$1;->cancel(Z)Z

    .line 356
    return-void
.end method


text:
/*jslint sub: true */
var BUILD_AS_SINGLE_FILE;
if (!BUILD_AS_SINGLE_FILE) {
var url = require('url');
var util = require('../util');
var EventEmitter = require('events').EventEmitter;
var EndpointClient = require('./endpointclient').EndpointClient;
var NODELOAD_CONFIG = require('../config').NODELOAD_CONFIG;
}

/** Slave represents a remote slave instance from the master server's perspective. It holds the slave
method defintions, defined by calling defineMethod(), as Javascript strings. When start() is called,
the definitions are POSTed to /remote on the remote instance which causes the instance to create a new
endpoint with those methods. Subsequent calls to Slave simply POST parameters to the remote instance:

    slave = new Slave(...);
    slave.defineMethod('slave_method_1', function(master, name) { return 'hello ' + name });
    slave.start();
    slave.on('start', function() {
        slave.method_1('tom');
        slave.end();
    });

will POST the definition of method_1 to /remote, followed by ['tom'] to /remote/.../method_1.

Slave emits the following events:
- 'slaveError', error: The underlying HTTP connection returned an error.
- 'start': The remote instance accepted the slave definition and slave methods can now be called.
- 'end': The slave endpoint has been removed from the remote instance.

Slave.state can be:
- 'initialized': The slave is ready to be started.
- 'connecting': The slave definition is being sent to the remote instance.
- 'started': The remote instance is running and methods defined through defineMethod can be called. */
var Slave = exports.Slave = function Slave(id, host, port, masterEndpoint, pingInterval) {
    EventEmitter.call(this);
    this.id = id;
    this.client = new EndpointClient(host, port);
    this.client.on('error', this.emit.bind(this, 'slaveError'));
    this.masterEndpoint = masterEndpoint;
    this.pingInterval = pingInterval || NODELOAD_CONFIG.SLAVE_UPDATE_INTERVAL_MS;
    this.methodDefs = [];
    this.state = 'initialized';
};
util.inherits(Slave, EventEmitter);
/** POST method definitions and information about this instance (the slave's master) to /remote */
Slave.prototype.start = function() {
    if (this.masterEndpoint && this.masterEndpoint.state !== 'started') {
        throw new Error('Slave must be started after its Master.');
    }

    var self = this,
        masterUrl = self.masterEndpoint ? self.masterEndpoint.url : null,
        masterMethods = self.masterEndpoint ? self.masterEndpoint.methodNames : [],
        req = self.client.rawRequest('POST', '/remote');

    req.end(JSON.stringify({
        id: self.id,
        master: masterUrl,
        masterMethods: masterMethods,
        slaveMethods: self.methodDefs,
        pingInterval: self.pingInterval
    }));
    req.on('response', function(res) {
        if (!res.headers['location']) {
            self.emit('error', new Error('Remote slave does not have proper /remote handler.'));
        }
        self.client.basepath = url.parse(res.headers['location']).pathname;
        self.state = 'started';
        self.emit('start');
    });

    self.state = 'connecting';
};
/** Stop this slave by sending a DELETE request to terminate the slave's endpoint. */
Slave.prototype.end = function() {
    var self = this,
        req = self.client.rawRequest('DELETE', self.client.basepath),
        done = function() {
            self.client.basepath = '';
            self.state = 'initialized';
            self.emit('end');
        };

    self.client.once('error', function(e) {
        self.emit('slaveError', e);
        done();
    });
    req.on('response', function(res) {
        if (res.statusCode !== 204) {
            self.emit('slaveError', new Error('Error stopping slave.'), res);
        }
        done();
    });
    req.end();
};
/** Define a method that will be sent to the slave instance */
Slave.prototype.defineMethod = function(name, fun) {
    var self = this;
    self.client.defineMethod(name, fun);
    self[name] = function() { return self.client[name].apply(self.client, arguments); };
    self.methodDefs.push({name: name, fun: fun.toString()});
};


text:
import {Injector} from '@angular/core';
import {IInjectorService} from './angular1';
import {$INJECTOR, INJECTOR_KEY} from './constants';
import {getTypeName, isFunction, validateInjectionKey} from './util';

/**
 * @description
 *
 * A helper function to allow an Angular service to be accessible from AngularJS.
 *
 * *Part of the [upgrade/static](api?query=upgrade%2Fstatic)
 * library for hybrid upgrade apps that support AOT compilation*
 *
 * This helper function returns a factory function that provides access to the Angular
 * service identified by the `token` parameter.
 *
 * @usageNotes
 * ### Examples
 *
 * First ensure that the service to be downgraded is provided in an `NgModule`
 * that will be part of the upgrade application. For example, let's assume we have
 * defined `HeroesService`
 *
 * {@example upgrade/static/ts/full/module.ts region="ng2-heroes-service"}
 *
 * and that we have included this in our upgrade app `NgModule`
 *
 * {@example upgrade/static/ts/full/module.ts region="ng2-module"}
 *
 * Now we can register the `downgradeInjectable` factory function for the service
 * on an AngularJS module.
 *
 * {@example upgrade/static/ts/full/module.ts region="downgrade-ng2-heroes-service"}
 *
 * Inside an AngularJS component's controller we can get hold of the
 * downgraded service via the name we gave when downgrading.
 *
 * {@example upgrade/static/ts/full/module.ts region="example-app"}
 *
 *

 *
 *   When using `downgradeModule()`, downgraded injectables will not be available until the Angular
 *   module that provides them is instantiated. In order to be safe, you need to ensure that the
 *   downgraded injectables are not used anywhere _outside_ the part of the app where it is
 *   guaranteed that their module has been instantiated.
 *
 *   For example, it is _OK_ to use a downgraded service in an upgraded component that is only used
 *   from a downgraded Angular component provided by the same Angular module as the injectable, but
 *   it is _not OK_ to use it in an AngularJS component that may be used independently of Angular or
 *   use it in a downgraded Angular component from a different module.
 *
 *

 *
 * @param token an `InjectionToken` that identifies a service provided from Angular.
 * @param downgradedModule the name of the downgraded module (if any) that the injectable
 * "belongs to", as returned by a call to `downgradeModule()`. It is the module, whose injector will
 * be used for instantiating the injectable.

 * (This option is only necessary when using `downgradeModule()` to downgrade more than one Angular
 * module.)
 *
 * @returns a [factory function](https://docs.angularjs.org/guide/di) that can be
 * used to register the service on an AngularJS module.
 *
 * @publicApi
 */
export function downgradeInjectable(token: any, downgradedModule: string = ''): Function {
  const factory = function($injector: IInjectorService) {
    const injectorKey = `${INJECTOR_KEY}${downgradedModule}`;
    const injectableName = isFunction(token) ? getTypeName(token) : String(token);
    const attemptedAction = `instantiating injectable '${injectableName}'`;

    validateInjectionKey($injector, downgradedModule, injectorKey, attemptedAction);

    try {
      const injector: Injector = $injector.get(injectorKey);
      return injector.get(token);
    } catch (err) {
      throw new Error(`Error while ${attemptedAction}: ${err.message || err}`);
    }
  };
  (factory as any)['$inject'] = [$INJECTOR];

  return factory;
}


text:
'use strict'

var assert = require('assert'),
  chkr = require('../index')

describe('lottosjekker - inputs', function () {
  it('requires opts and callback to be supplied', function (done) {
    var opts = false

    chkr(opts, function (err, data) {
      assert.throws(function () {
        if (err) throw err
      }, function (err) {
        if ((err instanceof Error) && /Missing required input. Both opts and callback is required./.test(err)) {
          return true
        }
      },
        'Unexpected error'
      )
      done()
    })
  })

  it('requires opts.result to exist', function (done) {
    var opts = {
      result: false,
      rows: true
    }

    chkr(opts, function (err, data) {
      assert.throws(function () {
        if (err) throw err
      }, function (err) {
        if ((err instanceof Error) && /Missing required param: opts.result/.test(err)) {
          return true
        }
      },
        'Unexpected error'
      )
      done()
    })
  })

  it('requires opts.rows to exist', function (done) {
    var opts = {
      result: true,
      rows: false
    }

    chkr(opts, function (err, data) {
      assert.throws(function () {
        if (err) throw err
      }, function (err) {
        if ((err instanceof Error) && /Missing required param: opts.rows/.test(err)) {
          return true
        }
      },
        'Unexpected error'
      )
      done()
    })
  })

  it('requires opts.rows to be an array', function (done) {
    var opts = {
      result: true,
      rows: true
    }

    chkr(opts, function (err, data) {
      assert.throws(function () {
        if (err) throw err
      }, function (err) {
        if ((err instanceof Error) && /Wrong input. opts.rows must be an array/.test(err)) {
          return true
        }
      },
        'Unexpected error'
      )
      done()
    })
  })
})


text:
const WEB_PREFIX = "http://localhost:9876";

// Blockly crashes if this isn't defined
(Blockly as any).Msg.DELETE_VARIABLE = "Delete the '%1' variable";

// Just needs to exist
pxt.setAppTarget({
    id: "core",
    name: "Microsoft MakeCode",
    title: "Microsoft MakeCode",
    versions: undefined,
    description: "A toolkit to build JavaScript Blocks editors.",
    bundleddirs: [],
    compile: {
        isNative: false,
        hasHex: false,
        jsRefCounting: true,
    },
    bundledpkgs: {},
    appTheme: {},
    tsprj: undefined,
    runtime: {
        pauseUntilBlock: { category: "Loops", color: "0x0000ff" }
    },
    blocksprj: undefined,
    corepkg: undefined
});

// Webworker needs this config to run
pxt.webConfig = {
    relprefix: undefined,
    verprefix: undefined,
    workerjs: WEB_PREFIX + "/blb/worker.js",
    monacoworkerjs: undefined,
    pxtVersion: undefined,
    pxtRelId: undefined,
    pxtCdnUrl: undefined,
    commitCdnUrl: undefined,
    blobCdnUrl: undefined,
    cdnUrl: undefined,
    targetVersion: undefined,
    targetRelId: undefined,
    targetUrl: undefined,
    targetId: undefined,
    simUrl: undefined,
    partsUrl: undefined,
    runUrl: undefined,
    docsUrl: undefined,
    isStatic: undefined,
};

class BlocklyCompilerTestHost implements pxt.Host {
    static cachedFiles: pxt.Map<string> = {};

    static createTestHostAsync() {
        if (!BlocklyCompilerTestHost.cachedFiles["pxt-core.d.ts"]) {
            return ts.pxtc.Util.httpGetTextAsync(WEB_PREFIX + "/common/pxt-core.d.ts")
                .then(res => {
                    BlocklyCompilerTestHost.cachedFiles["pxt-core.d.ts"] = res;
                    return ts.pxtc.Util.httpGetTextAsync(WEB_PREFIX + "/common/pxt-helpers.ts")
                })
                .then(res => {
                    BlocklyCompilerTestHost.cachedFiles["pxt-helpers.ts"] = res;
                    return pxt.Util.httpGetTextAsync(WEB_PREFIX + '/test-library/pxt.json')
                })
                .then(res => {
                    BlocklyCompilerTestHost.cachedFiles[`test-library/pxt.json`] = res;
                    let json: pxt.PackageConfig;

                    try {
                        json = JSON.parse(res);
                    }
                    catch (e) { }

                    if (json && json.files && json.files.length) {
                        return Promise.all(json.files.map(f => {
                            return pxt.Util.httpGetTextAsync(WEB_PREFIX + '/test-library/' + f)
                                .then(txt => {
                                    BlocklyCompilerTestHost.cachedFiles[`test-library/${f}`] = txt;
                                });
                        }))
                            .then(() => { });
                    }

                    return Promise.resolve()
                })
                .then(() => {
                    return new BlocklyCompilerTestHost();
                })
        }

        return Promise.resolve(new BlocklyCompilerTestHost())
    }

    constructor() {
    }

    readFile(module: pxt.Package, filename: string): string {
        if (module.id == "this") {
            if (filename == "pxt.json") {
                return JSON.stringify({
                    "name": "blocklycompilertest",
                    "dependencies": {
                        "testlib": "file:."
                    },
                    "description": "",
                    "files": [
                        "main.blocks",
                        "main.ts",
                        "pxt-core.d.ts",
                        "pxt-helpers.ts"
                    ]
                });
            }
            else if (filename == "main.blocks") {
                return "";
            }
            else if (filename == "pxt-core.d.ts" || filename == "pxt-helpers.ts") {
                return BlocklyCompilerTestHost.cachedFiles[filename];
            }
        } else if (pxt.appTarget && pxt.appTarget.bundledpkgs[module.id] && filename === pxt.CONFIG_NAME) {
            return pxt.appTarget.bundledpkgs[module.id][pxt.CONFIG_NAME];
        }

        if (module.id == "testlib") {
            const split = filename.split(/[/\\]/);
            filename = "test-library/" + split[split.length - 1];
            return BlocklyCompilerTestHost.cachedFiles[filename];
        }

        return "";
    }

    writeFile(module: pxt.Package, filename: string, contents: string): void {
        if (filename == pxt.CONFIG_NAME)
            return; // ignore config writes
        throw ts.pxtc.Util.oops("trying to write " + module + " / " + filename)
    }

    getHexInfoAsync(extInfo: pxtc.ExtensionInfo): Promise<pxtc.HexInfo> {
        return pxt.hex.getHexInfoAsync(this, extInfo)
    }

    cacheStoreAsync(id: string, val: string): Promise<void> {
        return Promise.resolve()
    }

    cacheGetAsync(id: string): Promise<string> {
        return Promise.resolve(null as string)
    }

    downloadPackageAsync(pkg: pxt.Package) {
        return Promise.resolve();
    }
}

function fail(msg: string) {
    chai.assert(false, msg);
}

let cachedBlocksInfo: pxtc.BlocksInfo;

function getBlocksInfoAsync(): Promise<pxtc.BlocksInfo> {
    if (cachedBlocksInfo) {
        return Promise.resolve(cachedBlocksInfo);
    }

    return BlocklyCompilerTestHost.createTestHostAsync()
        .then(host => {
            const pkg = new pxt.MainPackage(host);
            return pkg.getCompileOptionsAsync();
        }, err => fail('Unable to create test host'))
        .then(opts => {
            opts.ast = true
            let resp = pxtc.compile(opts)
            if (resp.diagnostics && resp.diagnostics.length > 0)
                resp.diagnostics.forEach(diag => console.error(diag.messageText));
            if (!resp.success)
                return Promise.reject("Could not compile");

            // decompile to blocks
            let apis = pxtc.getApiInfo(opts, resp.ast);
            let blocksInfo = pxtc.getBlocksInfo(apis);
            pxt.blocks.initializeAndInject(blocksInfo);

            cachedBlocksInfo = blocksInfo;

            return cachedBlocksInfo;
        }, err => fail('Could not get compile options'))
}

function blockTestAsync(name: string) {
    let blocksFile: string;
    let tsFile: string;
    return pxt.Util.httpGetTextAsync(WEB_PREFIX + '/tests/' + name + '.blocks')
        .then(res => {
            blocksFile = res;
            return pxt.Util.httpGetTextAsync(WEB_PREFIX + '/baselines/' + name + '.ts')
        }, err => fail(`Unable to get ${name}.blocks: ` + JSON.stringify(err)))
        .then(res => {
            tsFile = res;
            return getBlocksInfoAsync();
        }, err => fail(`Unable to get ${name}.ts: ` + JSON.stringify(err)))
        .then(blocksInfo => {
            const workspace = new Blockly.Workspace();
            (Blockly as any).mainWorkspace = workspace;
            const xml = Blockly.Xml.textToDom(blocksFile);
            Blockly.Xml.domToWorkspace(xml, workspace);

            return pxt.blocks.compileAsync(workspace, blocksInfo)
        }, err => fail(`Unable to get block info: ` + JSON.stringify(err)))
        .then((res: pxt.blocks.BlockCompilationResult) => {
            chai.expect(res).to.not.be.undefined;

            const compiledTs = res.source.trim().replace(/\s+/g, " ");
            const baselineTs = tsFile.trim().replace(/\s+/g, " ");

            if (compiledTs !== baselineTs) {
                console.log(compiledTs);
            }

            chai.assert(compiledTs === baselineTs, "Compiled result did not match baseline");
        }, err => fail('Compiling blocks failed'));
}

describe("blockly compiler", function () {
    this.timeout(5000);

    describe("compiling lists", () => {
        it("should handle unambiguously typed list generics", (done: () => void) => {
            blockTestAsync("lists_generics1").then(done, done);
        });

        it("should handle generic types of lists with empty inputs", (done: () => void) => {
            blockTestAsync("lists_generics2").then(done, done);
        });

        it("should handle generic list return types in uninitialized lists", (done: () => void) => {
            blockTestAsync("lists_generics3").then(done, done);
        });

        it("should handle generic list return types from non-builtin blocks", (done: () => void) => {
            blockTestAsync("lists_generics4").then(done, done);
        });

        it("should handle generic lists types that reference each other", (done: () => void) => {
            blockTestAsync("lists_generics5").then(done, done);
        });

        it("should handle empty inputs in list blocks by placing literals", (done: () => void) => {
            blockTestAsync("lists_empty_inputs2").then(done, done);
        });

        it("should properly place semicolons when necessary", (done: () => void) => {
            blockTestAsync("lists_semicolons").then(done, done);
        });

        it("should properly handle type declaration for double arrays", (done: () => void) => {
            blockTestAsync("lists_double_arrays").then(done, done);
        });

        it("should not place semicolons in expressions", (done: () => void) => {
            blockTestAsync("lists_semicolons2").then(done, done);
        });

        it("should not infinitely recurse if both parent and child types are not concrete", (done: () => void) => {
            blockTestAsync("lists_infinite").then(done, done);
        });

        it("should not infinitely recurse for unininitialized arrays used in a for of loop", (done: () => void) => {
            blockTestAsync("lists_infinite2").then(done, done);
        });

        it("should not declare lists as strings when using the length block", (done: () => void) => {
            blockTestAsync("lists_length_with_for_of").then(done, done);
        });

        it("should handle empty array blocks", (done: () => void) => {
            blockTestAsync("lists_empty_arrays").then(done, done);
        });

        it("should handle functions with list return types", (done: () => void) => {
            blockTestAsync("array_return_type").then(done, done);
        });
    });

    describe("compiling logic", () => {
        it("should handle all the logic blocks in the toolbox", (done: () => void) => {
            blockTestAsync("logic_all").then(done, done);
        });

        it("should handle all the logic operators", (done: () => void) => {
            blockTestAsync("logic_all_operators").then(done, done);
        });
    });

    describe("compiling math", () => {
        it("should handle all the math operators", (done: () => void) => {
            blockTestAsync("math_operators").then(done, done);
        });

        it("should handle all the math library functions", (done: () => void) => {
            blockTestAsync("math_library").then(done, done);
        });

        it("should handle exponentiation operator", (done: () => void) => {
            blockTestAsync("math_exponents").then(done, done);
        });
    });

    describe("compiling text", () => {
        it("should handle the text blocks", (done: () => void) => {
            blockTestAsync("text").then(done, done);
        });

        it("should handle text join", (done: () => void) => {
            blockTestAsync("text_join").then(done, done);
        });
    });

    describe("compiling loops", () => {
        it("should handle the loops blocks", (done: () => void) => {
            blockTestAsync("loops").then(done, done);
        });

        it("should generate proper variable declarations for loop variables", (done: () => void) => {
            blockTestAsync("loops_local_variables").then(done, done);
        });
    });

    describe("compiling variables", () => {
        it("should handle the variables blocks", (done: () => void) => {
            blockTestAsync("variables").then(done, done);
        });

        it("should change invalid names and preserve unicode names", (done: () => void) => {
            blockTestAsync("variables_names").then(done, done);
        });

        it("should change variable names that collide with tagged template function names", (done: () => void) => {
            blockTestAsync("tagged_template_variable").then(done, done);
        });

        it("should change function names that collide with tagged template function names", (done: () => void) => {
            blockTestAsync("tagged_template_function").then(done, done);
        });

        it("should change variable and function names that collide with namespace names", (done: () => void) => {
            blockTestAsync("namespace_variable_rename").then(done, done);
        });

        it("should change reserved names", (done: () => void) => {
            blockTestAsync("variables_reserved_names").then(done, done);
        });
    });

    describe("compiling functions", () => {
        it("should handle name collisions", (done: () => void) => {
            blockTestAsync("functions_names").then(done, done);
        });
    });

    describe("compiling special blocks", () => {
        it("should compile the predicate in pause until", done => {
            blockTestAsync("pause_until").then(done, done);
        });

        it("should implicitly convert arguments marked as toString to a string", done => {
            blockTestAsync("to_string_arg").then(done, done);
        });

        it("should convert handler parameters to draggable variables", done => {
            blockTestAsync("draggable_parameters").then(done, done);
        });
    });

    describe("compiling expandable blocks", () => {
        it("should handle blocks with optional arguments", done => {
            blockTestAsync("expandable_basic").then(done, done);
        });
    });

    describe("compiling ENUM_GET blocks", () => {
        it("should handle simple enum values", done => {
            blockTestAsync("enum_define").then(done, done);
        });

        describe("with start value set", () => {
            it("should handle conformant values", done => {
                blockTestAsync("enum_define_start_value").then(done, done);
            });

            it("should compile values even if they are invalid", done => {
                blockTestAsync("enum_define_start_value_bad_start").then(done, done);
            });
        });

        describe("with bit mask set", () => {
            it("should handle conformant values", done => {
                blockTestAsync("enum_define_bit_mask").then(done, done);
            });

            it("should compile values even if they are invalid", done => {
                blockTestAsync("enum_define_bit_mask_bad_values").then(done, done);
            });
        });
    });

    describe("compiling events blocks", () => {
        it("should handle APIs where the handler's type uses the Action alias", done => {
            blockTestAsync("action_event").then(done, done);
        });
    })
});


text:
/*
 * REVISION HISTORY:
 *
 * Date          Author(s)
 * CR            Headline
 * ============  ==============================================================
 * Aug 18, 2005  Luiz Felipe Guimaraes
 * 23            Update test cases according to changes in the Acl API
 * ============  ==============================================================
 */

package org.osgi.test.cases.dmt.tc2.tbc.Constraints;

import java.lang.reflect.Modifier;

import org.osgi.service.dmt.Acl;
import org.osgi.service.dmt.DmtException;
import org.osgi.service.dmt.DmtSession;
import org.osgi.service.dmt.security.DmtPrincipalPermission;
import org.osgi.service.permissionadmin.PermissionInfo;
import org.osgi.test.cases.dmt.tc2.tbc.DmtConstants;
import org.osgi.test.cases.dmt.tc2.tbc.DmtTestControl;
import org.osgi.test.cases.dmt.tc2.tbc.Plugin.ExecPlugin.TestExecPlugin;
import org.osgi.test.cases.dmt.tc2.tbc.Plugin.ExecPlugin.TestExecPluginActivator;
import org.osgi.test.support.compatibility.DefaultTestBundleControl;

import junit.framework.TestCase;

/**
 * @author Luiz Felipe Guimaraes
 *
 * This class validates the constraints of Acl, according to MEG specification
 *
 */
public class AclConstraints {
	private DmtTestControl tbc;

	public AclConstraints(DmtTestControl tbc) {
		this.tbc = tbc;
	}

	public void run() {
		testAclConstraints001();
		testAclConstraints002();
		testAclConstraints003();
		testAclConstraints004();
		testAclConstraints005();
		testAclConstraints006();
		testAclConstraints007();
		testAclConstraints008();
        testAclConstraints009();
        testAclConstraints010();
        testAclConstraints011();
        testAclConstraints012();

	}

	/**
	 * This test asserts that white space between tokens is not allowed.
	 *
	 * @spec 117.7 Access Control Lists
	 */
	private void testAclConstraints001() {

		try {
			DefaultTestBundleControl.log("#testAclConstraints001");

            new org.osgi.service.dmt.Acl("Add=test&Exec=test &Get=*");

            DefaultTestBundleControl.failException("",IllegalArgumentException.class);
		} catch (IllegalArgumentException e) {
			DefaultTestBundleControl.pass("White space between tokens of a Acl is not allowed.");
		} catch (Exception e) {
			tbc.failExpectedOtherException(IllegalArgumentException.class, e);
		}
	}

	/**
	 * This test asserts that if the root node ACL is not explicitly set, it should be set to Add=*&Get=*&Replace=*.
	 *
	 * @spec 117.7 Access Control Lists
	 */
	private void testAclConstraints002() {
		DmtSession session = null;
		try {
			DefaultTestBundleControl.log("#testAclConstraints002");
			session = tbc.getDmtAdmin().getSession(".",DmtSession.LOCK_TYPE_EXCLUSIVE);
			String expectedRootAcl = "Add=*&Get=*&Replace=*";
			String rootAcl = session.getNodeAcl(".").toString();
			TestCase.assertEquals("This test asserts that if the root node ACL is not explicitly set, it should be set to Add=*&Get=*&Replace=*.",expectedRootAcl,rootAcl);
		} catch (Exception e) {
			tbc.failUnexpectedException(e);
		} finally {
			tbc.closeSession(session);
		}
	}

	/**
	 * This test asserts that the root node of DMT must always have an ACL associated with it
	 *
	 * @spec 117.7 Access Control Lists
	 */
	private void testAclConstraints003() {
		DmtSession session = null;
		try {
			DefaultTestBundleControl.log("#testAclConstraints003");
			session = tbc.getDmtAdmin().getSession(".",DmtSession.LOCK_TYPE_EXCLUSIVE);
			session.setNodeAcl(".",null);
			DefaultTestBundleControl.failException("",DmtException.class);
		} catch (DmtException e) {
			TestCase.assertEquals("Asserts that the root node of DMT must always have an ACL associated with it",
			    DmtException.COMMAND_NOT_ALLOWED,e.getCode());

		} catch (Exception e) {
			tbc.failExpectedOtherException(DmtException.class, e);
		} finally {
			try {
				session.setNodeAcl(".",new org.osgi.service.dmt.Acl("Add=*&Get=*&Replace=*"));
			} catch (Exception e) {
				tbc.failUnexpectedException(e);
			} finally {
				tbc.closeSession(session);
			}
		}
	}

	/**
	 * This test asserts that the root's ACL can be changed
	 *
	 * @spec 117.7 Access Control Lists
	 */
	private void testAclConstraints004() {
		DmtSession session = null;
		try {
			DefaultTestBundleControl.log("#testAclConstraints004");
			session = tbc.getDmtAdmin().getSession(".",DmtSession.LOCK_TYPE_EXCLUSIVE);
			String expectedRootAcl = "Add=*&Exec=*&Replace=*";
			session.setNodeAcl(".",new org.osgi.service.dmt.Acl(expectedRootAcl));
			String rootAcl = session.getNodeAcl(".").toString();
			TestCase.assertEquals("Asserts that the root's ACL can be changed.",expectedRootAcl,rootAcl);
		} catch (Exception e) {
			tbc.failUnexpectedException(e);
		} finally {
			try {
				session.setNodeAcl(".",new org.osgi.service.dmt.Acl("Add=*&Get=*&Replace=*"));
			} catch (Exception e) {
				tbc.failUnexpectedException(e);
			} finally {
				tbc.closeSession(session);
			}
		}
	}

	/**
	 * The Dmt Admin service synchronizes the ACLs with any change
	 * in the DMT that is made through its service interface.
	 * This test case we test if the deleteNode method deletes also the ACL of that node.
	 *
	 * @spec 117.7.2 Ghost Acls
	 */
	private void testAclConstraints005() {
		DmtSession session = null;
		try {
			DefaultTestBundleControl.log("#testAclConstraints005");
			session = tbc.getDmtAdmin().getSession(".",
					DmtSession.LOCK_TYPE_EXCLUSIVE);

			session.setNodeAcl(TestExecPluginActivator.INTERIOR_NODE,
					new org.osgi.service.dmt.Acl("Replace=*"));

			session.deleteNode(TestExecPluginActivator.INTERIOR_NODE);

			TestCase.assertNull("This test asserts that the Dmt Admin service synchronizes the ACLs with any change "
							+ "in the DMT that is made through its service interface",
							session.getNodeAcl(TestExecPluginActivator.INTERIOR_NODE));
		} catch (Exception e) {
			tbc.failUnexpectedException(e);
		} finally {
			tbc.closeSession(session);
		}
	}

	/**
	 * This test case we test if the rename method renames also the ACL of that node.
	 *
	 * @spec 117.7.2 Ghost Acls
	 */

	private void testAclConstraints006() {
		DmtSession session = null;
		try {
			DefaultTestBundleControl.log("#testAclConstraints006");
			session = tbc.getDmtAdmin().getSession(".",
					DmtSession.LOCK_TYPE_EXCLUSIVE);

			String expectedRootAcl = "Add=*";
			session.setNodeAcl(TestExecPluginActivator.INTERIOR_NODE,
					new org.osgi.service.dmt.Acl(expectedRootAcl));

			session.renameNode(TestExecPluginActivator.INTERIOR_NODE,TestExecPluginActivator.RENAMED_NODE_NAME);
			TestExecPlugin.setAllUriIsExistent(true);
			TestCase.assertNull("Asserts that the method rename deletes the ACL of the source.",session.getNodeAcl(TestExecPluginActivator.INTERIOR_NODE));

			TestCase.assertEquals("Asserts that the method rename moves the ACL from the source to the destiny.",
					expectedRootAcl,session.getNodeAcl(TestExecPluginActivator.RENAMED_NODE).toString());

		} catch (Exception e) {
			tbc.failUnexpectedException(e);
		} finally {
			tbc.cleanUp(session,TestExecPluginActivator.RENAMED_NODE);
			TestExecPlugin.setAllUriIsExistent(false);
		}
	}

	/**
	 * This test asserts that if a principal has Replace access to a node,
	 * the principal is permitted to change the ACL of all its child nodes,
	 * regardless of the ACLs that are set on the child nodes.
	 *
	 * @spec 117.7 Access Control Lists
	 */
	private void testAclConstraints007() {
		DmtSession session = null;
		try {
			DefaultTestBundleControl.log("#testAclConstraints007");
            tbc.openSessionAndSetNodeAcl(TestExecPluginActivator.LEAF_NODE, DmtConstants.PRINCIPAL_2, Acl.GET );
            tbc.openSessionAndSetNodeAcl(TestExecPluginActivator.INTERIOR_NODE, DmtConstants.PRINCIPAL, Acl.REPLACE );
			tbc.setPermissions(new PermissionInfo(DmtPrincipalPermission.class.getName(),DmtConstants.PRINCIPAL,"*"));
			session = tbc.getDmtAdmin().getSession(DmtConstants.PRINCIPAL,TestExecPluginActivator.ROOT,DmtSession.LOCK_TYPE_EXCLUSIVE);
			session.setNodeAcl(TestExecPluginActivator.LEAF_NODE,new org.osgi.service.dmt.Acl("Get=*"));

			DefaultTestBundleControl.pass("If a principal has Replace access to a node, the principal is permitted to change the ACL of all its child nodes");

		} catch (Exception e) {
			tbc.failUnexpectedException(e);
		} finally {
			tbc.cleanUp(session,TestExecPluginActivator.LEAF_NODE);
			tbc.cleanAcl(TestExecPluginActivator.INTERIOR_NODE);

		}
	}
	/**
	 * This test asserts that Replace access on a leaf node does not allow changing the ACL property itself.
	 *
	 * @spec 117.7 Access Control Lists
	 */
	private void testAclConstraints008() {
		DmtSession session = null;
		try {
			DefaultTestBundleControl.log("#testAclConstraints008");
            //We need to set that a parent of the node does not have Replace else the acl of the root "." is gotten
            tbc.openSessionAndSetNodeAcl(TestExecPluginActivator.INTERIOR_NODE, DmtConstants.PRINCIPAL, Acl.DELETE );
            tbc.openSessionAndSetNodeAcl(TestExecPluginActivator.LEAF_NODE, DmtConstants.PRINCIPAL, Acl.REPLACE );

            tbc.setPermissions(new PermissionInfo(DmtPrincipalPermission.class.getName(),DmtConstants.PRINCIPAL,"*"));
            session = tbc.getDmtAdmin().getSession(DmtConstants.PRINCIPAL,TestExecPluginActivator.LEAF_NODE,DmtSession.LOCK_TYPE_EXCLUSIVE);
            session.setNodeAcl(TestExecPluginActivator.LEAF_NODE,new org.osgi.service.dmt.Acl("Get=*"));
			DefaultTestBundleControl.failException("",DmtException.class);
		} catch (DmtException e) {
			TestCase.assertEquals("Asserts that Replace access on a leaf node does not allow changing the ACL property itself.",
			    DmtException.PERMISSION_DENIED,e.getCode());

		} catch (Exception e) {
			tbc.failUnexpectedException(e);
		} finally {
			tbc.cleanUp(session,TestExecPluginActivator.LEAF_NODE);
            tbc.cleanAcl(TestExecPluginActivator.INTERIOR_NODE);

		}
	}

    /**
     * Asserts that ACLs must only be verified by the Dmt Admin service when the session
     * has an associated principal.
     *
     * @spec 117.7 Access Control Lists
     */
    private void testAclConstraints009() {
        DmtSession session = null;
        try {
			DefaultTestBundleControl.log("#testAclConstraints009");
            session = tbc.getDmtAdmin().getSession(TestExecPluginActivator.ROOT,
                    DmtSession.LOCK_TYPE_EXCLUSIVE);

            session.setNodeAcl(TestExecPluginActivator.INTERIOR_NODE,
                    new org.osgi.service.dmt.Acl("Replace=*"));

            session.deleteNode(TestExecPluginActivator.INTERIOR_NODE);

            DefaultTestBundleControl.pass("ACLs is only verified by the Dmt Admin service when the session has an associated principal.");
        } catch (Exception e) {
        	tbc.failUnexpectedException(e);
        } finally {
            tbc.closeSession(session);
        }
    }

    /**
     * This method asserts that the copy methods does not copy the Acl.
     * It also tests that the copied nodes inherit the access rights
     * from the parent of the destination node.
     *
     * @spec 117.4.10 Copying Nodes
     */
    private void testAclConstraints010() {
        DmtSession session = null;
        try {
			DefaultTestBundleControl.log("#testAclConstraints010");
            tbc.cleanAcl(TestExecPluginActivator.INEXISTENT_NODE);

            session = tbc.getDmtAdmin().getSession(".",
                    DmtSession.LOCK_TYPE_EXCLUSIVE);
            Acl aclParent = new Acl(new String[] { DmtConstants.PRINCIPAL },new int[] { Acl.REPLACE });
            session.setNodeAcl(TestExecPluginActivator.ROOT,
                    aclParent);

            session.setNodeAcl(TestExecPluginActivator.INTERIOR_NODE,
                    new Acl(new String[] { DmtConstants.PRINCIPAL },
                            new int[] { Acl.EXEC }));
            TestExecPlugin.setAllUriIsExistent(false);
            session.copy(TestExecPluginActivator.INTERIOR_NODE,
                    TestExecPluginActivator.INEXISTENT_NODE, true);
            TestExecPlugin.setAllUriIsExistent(true);
            TestCase.assertTrue("Asserts that the copied nodes inherit the access rights from the parent of the destination node.",
                aclParent.equals(session.getEffectiveNodeAcl(TestExecPluginActivator.INEXISTENT_NODE)));

        } catch (Exception e) {
        	tbc.failUnexpectedException(e);
        } finally {
            tbc.cleanUp(session, TestExecPluginActivator.INTERIOR_NODE);
            tbc.cleanAcl(TestExecPluginActivator.ROOT);
            TestExecPlugin.setAllUriIsExistent(false);
        }
    }

    /**
     * This method asserts that when copy method is called if the calling principal does not
     * have Replace rights for the parent, the destiny node must be set with an Acl having
     * Add, Delete and Replace permissions
     *
     * @spec 117.4.10 Copying Nodes
     */
    private void testAclConstraints011() {
        DmtSession session = null;
        try {
			DefaultTestBundleControl.log("#testAclConstraints011");

            tbc.openSessionAndSetNodeAcl(TestExecPluginActivator.INTERIOR_NODE, DmtConstants.PRINCIPAL, Acl.GET | Acl.ADD );
            tbc.openSessionAndSetNodeAcl(TestExecPluginActivator.ROOT, DmtConstants.PRINCIPAL, Acl.ADD );

            Acl aclExpected = new Acl(new String[] { DmtConstants.PRINCIPAL },new int[] { Acl.ADD | Acl.DELETE | Acl.REPLACE });

            tbc.setPermissions(new PermissionInfo(DmtPrincipalPermission.class
					.getName(), DmtConstants.PRINCIPAL, "*"));

            session = tbc.getDmtAdmin().getSession(DmtConstants.PRINCIPAL, ".",
                    DmtSession.LOCK_TYPE_EXCLUSIVE);

            session.copy(TestExecPluginActivator.INTERIOR_NODE,
                    TestExecPluginActivator.INEXISTENT_NODE, true);
            TestExecPlugin.setAllUriIsExistent(true);

            session.close();
            session = tbc.getDmtAdmin().getSession(".",DmtSession.LOCK_TYPE_EXCLUSIVE);

            TestCase.assertTrue("Asserts that if the calling principal does not have Replace rights for the parent, " +
            		"the destiny node must be set with an Acl having Add, Delete and Replace permissions.",
            		aclExpected.equals(session.getNodeAcl(TestExecPluginActivator.INEXISTENT_NODE)));

        } catch (Exception e) {
        	tbc.failUnexpectedException(e);
        } finally {
            tbc.cleanUp(session, TestExecPluginActivator.INTERIOR_NODE);
            tbc.cleanAcl(TestExecPluginActivator.ROOT);
            tbc.cleanAcl(TestExecPluginActivator.INEXISTENT_NODE);
            TestExecPlugin.setAllUriIsExistent(false);
        }
    }

    /**
     * Asserts that Acl is a public final class
     *
     * @spec 117.12.2 Acl
     */
    private void testAclConstraints012() {
        try {
            int aclModifiers = Acl.class.getModifiers();
            TestCase.assertTrue("Asserts that Acl is a public final class", aclModifiers == (Modifier.FINAL | Modifier.PUBLIC));

        } catch (Exception e) {
        	tbc.failUnexpectedException(e);
        }
    }
}


text:
/**
   @Author:
      Date:
   Teacher:
    Period:
  */

import kareltherobot.*;
import java.awt.Color;

public class MainDriver1 implements Directions
{
    public static void main(String args[])  {
       PathFinder karel = new PathFinder(1, 1, West, 1);
       karel.followPath();
       karel.demoFinished();
   }

    static {
        World.reset();
        World.readWorld("path.kwld");
//        World.setBeeperColor(Color.magenta);
//        World.setStreetColor(Color.blue);
//        World.setNeutroniumColor(Color.green.darker().darker());
        World.setDelay(1);
        World.setVisible(true);
    }
}


text:
/**
 * @fileoverview This file is a plugin for maptune.jsapi top import cross domain feeds
 *
 * @author Guenter Richter guenter.richter@ixmaps.com
 * @version 0.9
 */

/**
 * define namespace maptune
 */

window.maptune = window.maptune || {};
maptune.jsapi = maptune.jsapi || {};
maptune.feed = maptune.feed || {};
maptune.feed.parse = maptune.feed.parse || {};
(function() {

var debug = false;

/**
 * add a cross domain feed to the map
 * @param szSource the URL of the feed
 * @param opt optional parameter object
 * @type void
 */
	maptune.feed.crossDomain = function(szSource,opt,callback){

		_TRACE("maptune.feed.crossDomain: "+szSource);

		// check origin and get around cross domain restrictions by using a proxy
		// ----------------------------------------------------------------------
		var rootA = szSource.split('?')[0].split('#')[0].split('/');
		if ( rootA[0] == "http:" || rootA[0] == "https:" ){
			rootA.length = 3;
			szDomain = rootA.join('/');
			if ( szDomain != document.location.host ){

				// check type
				// ----------
				switch (opt.type){
					case "kml":
					case "Google_Maps_My_Map_KML_YQL":
					case "Google_Maps_My_Map_KML":
						opt.format = "xml";
						opt.type = "kml_json";
					break;
				}

				var outputFormat = opt.type.match(/GeoRSS/)?"xml":"json";

				// cross domain !!
				// at the moment we use yahoo query api as a proxy
				// -----------------------------------------------
				var szUrl  = "http:\/\/query.yahooapis.com\/v1\/public\/yql?q=select%20*%20from%20"+opt.format+"%20where%20url%3D";
					szUrl += "'"+encodeURIComponent(szSource)+"'";
					szUrl += opt.type.match(/GeoRSS/)?"&format=rss&diagnostics=true":"&format="+outputFormat+"&diagnostics=true";
				szSource = szUrl;

				// YQL has been told to respond with json, so change type
				opt.format = outputFormat;

				// flag that we have a proxy
				opt.proxy = "yql";

				maptune.message("loading",true);

				_TRACE("maptune.feed.crossDomain: "+szSource);

				$.ajax({
					 type: "GET",
					 url: szSource,
					 dataType: opt.format,
					 success: function(data) {

						if ( (opt.format == "json") && !data.query.results ){
							if ( data.query.diagnostics.url.error ){
								maptune.errorMessage(data.query.diagnostics.url.error);
							}
							callback(false);
						}

						// undo proxy (YQL) wrapping
						// -------------------------
						if ( (opt.proxy == "yql") && data.query && data.query.results ){
							if ( opt.format == "json" && data.query.results ){
								data = 	maptune.feed.unwrapYQLjson(data.query.results);
							}
							if ( opt.format == "xml" ){
							}
							opt.proxy = false;
						}
						callback(maptune.feed.processFeed(data,opt));
					 },
					 error: function(data) {
						maptune.message("loading",false,"x5");
						callback(false);
					}
				});

				return true;
			}
		}
		return false;
	};

/**
 * YQL adds a json object for nested arrays
 * here we try to unwrap this
 * @param node the original node
 * @type object
 * @return stripped node
 */
	maptune.feed.unwrapYQLjson = function(node){
		if ( node.json ){
			node = node.json;
		}
		if ( typeof(node) == 'object' ){
			for ( a in node ){
				if ( node[a] ){
					node[a] = maptune.feed.unwrapYQLjson(node[a]);
				}
			}
		}else
		if ( typeof(node) == 'array' ){
			for ( var a=0; a<node.length; a++ ){
				if ( node[a] ){
					node[a] = maptune.feed.unwrapYQLjson(node[a]);
				}
			}
		}
		return node;
	};

/**
 * end of namespace
 */

})();

// -----------------------------
// EOF
// -----------------------------


text:
<?php

declare(strict_types=1);

namespace sad_spirit\pg_wrapper\converters\datetime;

use sad_spirit\pg_wrapper\exceptions\TypeConversionException;

/**
 * Converter for TIME WITH TIME ZONE type
 *
 * Not recommended to use even in the official PostgreSQL manual.
 */
class TimeTzConverter extends BaseDateTimeConverter
{
    protected function getFormats(string $style): array
    {
        return ['H:i:s.uO', 'H:i:sO'];
    }

    protected function inputNotNull(string $native)
    {
        foreach ($this->getFormats(self::DEFAULT_STYLE) as $format) {
            if ($value = \DateTimeImmutable::createFromFormat('!' . $format, $native)) {
                return $value;
            }
        }
        throw TypeConversionException::unexpectedValue(
            $this,
            'input',
            'time string with time zone info',
            $native
        );
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Test_Model2Form.Models;

namespace Test_Model2Form
{
    public partial class ContactUs4 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            Model2Form1.DataSource = new ContactUsInfo4();
            Model2Form1.DataBind();
        }

        protected void Model2Form1_LookupControlCreated(object sender, EasyWebControls.FieldEventArgs e)
        {
            if (e.FieldName == "Type")
            {
                DropDownList list = (DropDownList)sender;
                list.Items.Add(new ListItem("Suggestion","1"));
                list.Items.Add(new ListItem("Complaint","2"));

            }
        }
    }
}


text:
package org.pentaho.hadoop.mapreduce;

import org.pentaho.di.core.row.RowMetaInterface;

public class InKeyValueOrdinals extends BaseKeyValueOrdinals {
  public InKeyValueOrdinals(RowMetaInterface rowMeta) {
    super(rowMeta);
  }

  @Override
  protected final String getKeyName() {
    return "key"; //$NON-NLS-1$
  }

  @Override
  protected final String getValueName() {
    return "value"; //$NON-NLS-1$
  }
}


text:
diff -prub --exclude '*~' --exclude '.git' --exclude '*.elc' --exclude 'state' emacs.d ~/.emacs.d
diff -u ~/.gitconfig gitconfig

for d in config/*
do
    diff -prub $d ~/.$d
done


text:
class AddOptimizationPolicyToApplianceSets < ActiveRecord::Migration
  def change
    add_column :atmosphere_appliance_sets, :optimization_policy, :string
  end
end


text:
package com.smp.rxplayround.sample.operator.transform;

import com.smp.rxplayround.BasePlayground;
import com.smp.rxplayround.support.Utils;

import org.junit.Test;

import lombok.extern.slf4j.Slf4j;
import rx.Observable;
import rx.Observer;
import rx.Subscriber;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * Created by myungpyo.shim on 2016. 4. 25..
 */
@Slf4j
public class FlatMapOnWorker extends BasePlayground {

    @Test
    public void play() throws Exception {

        Observable.from(new String[]{"1-3","5-8", "10-15"})
            .flatMap(new Func1<String, Observable<Integer>>() {
                @Override
                public Observable<Integer> call(final String range) {
                    return Observable.create(new Observable.OnSubscribe<Integer>() {
                        @Override
                        public void call(Subscriber<? super Integer> subscriber) {
                            if (subscriber.isUnsubscribed()) {
                                return;
                            }

                            String[] split = range.split("-");
                            if (split.length != 2) {
                                throw new IllegalArgumentException("Check range format. ex> lowNum-HighNum");
                            }

                            int minNum = Integer.parseInt(split[0]);
                            int maxNum = Integer.parseInt(split[1]);

                            for (int num = minNum; num <= maxNum; num++) {
                                Utils.sleep(500);
                                subscriber.onNext(num);
                            }
                            subscriber.onCompleted();
                        }
                    }).subscribeOn(Schedulers.io());
                }
            })
            .subscribe(new Observer<Integer>() {
                @Override
                public void onCompleted() {
                    log.debug("onCompleted");
                    stopWaitingForObservable();
                }

                @Override
                public void onError(Throwable e) {
                    log.debug("onError : {}", e.getMessage());
                    stopWaitingForObservable();
                }

                @Override
                public void onNext(Integer value) {
                    log.debug("onNext : {}", value);
                }
            });

        waitForObservable();

    }
}


text:
import webpack from 'webpack'
import _debug from 'debug'
import WebpackIsomorphicToolsPlugin from 'webpack-isomorphic-tools/plugin'

import isomorphicToolsConfig from './isomorphic.tools.config'
import projectConfig, { paths } from '../config'

const webpackIsomorphicToolsPlugin = new WebpackIsomorphicToolsPlugin(isomorphicToolsConfig)
const debug = _debug('app:webpack:config:dev')
const srcDir = paths('src')
const cssLoaderOptions = {
  modules: true,
  sourceMap: true,
  localIdentName: '[name]__[local]___[hash:base64:5]',
}
const scssLoaderOptions = {
  outputStyle: 'expanded',
  sourceMap: true,
}
const {
  SERVER_HOST,
  VENDOR_DEPENDENCIES,
  WEBPACK_DEV_SERVER_PORT,
  __CLIENT__,
  __SERVER__,
  __DEV__,
  __PROD__
} = projectConfig

debug('Create configuration.')
const config = {
  cache: true,
  context: paths('base'),
  devtool: 'source-map',
  entry: {
    app: [
      'react-hot-loader/patch',
      `webpack-hot-middleware/client?reload=true&path=http://${SERVER_HOST}:${WEBPACK_DEV_SERVER_PORT}/__webpack_hmr`,
      paths('entryApp')
    ],
    vendor: VENDOR_DEPENDENCIES
  },
  output: {
    path: paths('build'),
    filename: '[name].js',
    chunkFilename: '[name].chunk.js',
    publicPath: `http://${SERVER_HOST}:${WEBPACK_DEV_SERVER_PORT}/build/`
  },
  resolve: {
    extensions: ['.js', '.jsx', '.json'],
    modules: [
      'src',
      'node_modules',
    ],
  },
  module: {
    rules: [
      {
        test: /\.js[x]?$/,
        enforce: 'pre',
        loader: 'eslint-loader',
        include: [srcDir],
        options: {
          rules: {
            'no-unused-vars': 'warn'
          }
        }
      },
      {
        test: /\.js[x]?$/,
        loader: 'babel-loader',
        include: [srcDir],
        options: {
          cacheDirectory: true,
          babelrc: false,
          presets: [
            ['latest', { es2015: { modules: false } }],
            'react',
            'stage-0'
          ],
          plugins: ['transform-runtime', 'react-hot-loader/babel', 'transform-react-jsx-source'],
        }
      },
      { test: /\.json$/, loader: 'json-loader' },
      {
        test: /\.css$/,
        include: [srcDir],
        use: [
          'style-loader',
          {
            loader: 'css-loader',
            options: { ...cssLoaderOptions, importLoaders: 1 }
          },
          'postcss-loader'
        ]
      },
      {
        test: /\.scss$/,
        include: [srcDir],
        loaders: [
          'style-loader',
          {
            loader: 'css-loader',
            options: { ...cssLoaderOptions, importLoaders: 2 }
          },
          'postcss-loader',
          { loader: 'sass-loader', options: scssLoaderOptions },
        ]
      },
      { test: /\.woff(\?v=\d+\.\d+\.\d+)?$/, loader: 'url-loader?prefix=fonts/&name=[path][name].[ext]&limit=10000&mimetype=application/font-woff' },
      { test: /\.woff2(\?v=\d+\.\d+\.\d+)?$/, loader: 'url-loader?prefix=fonts/&name=[path][name].[ext]&limit=10000&mimetype=application/font-woff2' },
      { test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/, loader: 'url-loader?prefix=fonts/&name=[path][name].[ext]&limit=10000&mimetype=application/octet-stream' },
      { test: /\.eot(\?v=\d+\.\d+\.\d+)?$/, loader: 'file-loader?prefix=fonts/&name=[path][name].[ext]' },
      { test: /\.svg(\?v=\d+\.\d+\.\d+)?$/, loader: 'url-loader?prefix=fonts/&name=[path][name].[ext]&limit=10000&mimetype=image/svg+xml' },
      {
        test: webpackIsomorphicToolsPlugin.regular_expression('images'),
        loader: 'url-loader',
        options: {
          limit: 10240
        }
      }
    ],
  },
  plugins: [
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoEmitOnErrorsPlugin(),
    new webpack.optimize.CommonsChunkPlugin({
      name: 'vendor',
      minChunks: Infinity,
    }),
    new webpack.DefinePlugin({
      __CLIENT__,
      __SERVER__,
      __DEV__,
      __PROD__
    }),
    webpackIsomorphicToolsPlugin.development()
  ]
}

export default config


text:
namespace {

const uint64_t kReadingBufferSize = sizeof(device::SensorReadingSharedBuffer);
const uint64_t kSharedBufferSizeInBytes =
    kReadingBufferSize *
    (static_cast<uint64_t>(device::mojom::SensorType::kMaxValue) + 1);

}  // namespace

namespace device {

FakeSensor::FakeSensor(mojom::SensorType sensor_type,
                       SensorReadingSharedBuffer* buffer)
    : sensor_type_(sensor_type), buffer_(buffer) {}

FakeSensor::~FakeSensor() = default;

void FakeSensor::AddConfiguration(
    const PlatformSensorConfiguration& configuration,
    AddConfigurationCallback callback) {
  std::move(callback).Run(true);
  SensorReadingChanged();
}

void FakeSensor::GetDefaultConfiguration(
    GetDefaultConfigurationCallback callback) {
  std::move(callback).Run(GetDefaultConfiguration());
}

void FakeSensor::RemoveConfiguration(
    const PlatformSensorConfiguration& configuration) {}

void FakeSensor::Suspend() {}

void FakeSensor::Resume() {}

void FakeSensor::ConfigureReadingChangeNotifications(bool enabled) {
  reading_notification_enabled_ = enabled;
}

PlatformSensorConfiguration FakeSensor::GetDefaultConfiguration() {
  return PlatformSensorConfiguration(GetSensorDefaultFrequency(sensor_type_));
}

mojom::ReportingMode FakeSensor::GetReportingMode() {
  return mojom::ReportingMode::ON_CHANGE;
}

double FakeSensor::GetMaximumSupportedFrequency() {
  return GetSensorMaxAllowedFrequency(sensor_type_);
}

double FakeSensor::GetMinimumSupportedFrequency() {
  return 1.0;
}

mojo::PendingReceiver<mojom::SensorClient> FakeSensor::GetClient() {
  return client_.BindNewPipeAndPassReceiver();
}

uint64_t FakeSensor::GetBufferOffset() {
  return SensorReadingSharedBuffer::GetOffset(sensor_type_);
}

void FakeSensor::SetReading(SensorReading reading) {
  reading_ = reading;
  SensorReadingChanged();
}

void FakeSensor::SensorReadingChanged() {
  auto& seqlock = buffer_->seqlock.value();
  seqlock.WriteBegin();
  buffer_->reading = reading_;
  seqlock.WriteEnd();

  if (client_ && reading_notification_enabled_)
    client_->SensorReadingChanged();
}

FakeSensorProvider::FakeSensorProvider() = default;

FakeSensorProvider::~FakeSensorProvider() = default;

void FakeSensorProvider::GetSensor(mojom::SensorType type,
                                   GetSensorCallback callback) {
  if (!CreateSharedBufferIfNeeded()) {
    std::move(callback).Run(mojom::SensorCreationResult::ERROR_NOT_AVAILABLE,
                            nullptr);
    return;
  }

  SensorReadingSharedBuffer* buffer = GetSensorReadingSharedBufferForType(type);

  std::unique_ptr<FakeSensor> sensor;

  switch (type) {
    case mojom::SensorType::AMBIENT_LIGHT:
      if (ambient_light_sensor_is_available_) {
        sensor = std::make_unique<FakeSensor>(mojom::SensorType::AMBIENT_LIGHT,
                                              buffer);
        ambient_light_sensor_ = sensor.get();
        ambient_light_sensor_->SetReading(ambient_light_sensor_reading_);
      }
      break;
    case mojom::SensorType::ACCELEROMETER:
      if (accelerometer_is_available_) {
        sensor = std::make_unique<FakeSensor>(mojom::SensorType::ACCELEROMETER,
                                              buffer);
        accelerometer_ = sensor.get();
        accelerometer_->SetReading(accelerometer_reading_);
      }
      break;
    case mojom::SensorType::LINEAR_ACCELERATION:
      if (linear_acceleration_sensor_is_available_) {
        sensor = std::make_unique<FakeSensor>(
            mojom::SensorType::LINEAR_ACCELERATION, buffer);
        linear_acceleration_sensor_ = sensor.get();
        linear_acceleration_sensor_->SetReading(
            linear_acceleration_sensor_reading_);
      }
      break;
    case mojom::SensorType::GYROSCOPE:
      if (gyroscope_is_available_) {
        sensor =
            std::make_unique<FakeSensor>(mojom::SensorType::GYROSCOPE, buffer);
        gyroscope_ = sensor.get();
        gyroscope_->SetReading(gyroscope_reading_);
      }
      break;
    case mojom::SensorType::RELATIVE_ORIENTATION_EULER_ANGLES:
      if (relative_orientation_sensor_is_available_) {
        sensor = std::make_unique<FakeSensor>(
            mojom::SensorType::RELATIVE_ORIENTATION_EULER_ANGLES, buffer);
        relative_orientation_sensor_ = sensor.get();
        relative_orientation_sensor_->SetReading(
            relative_orientation_sensor_reading_);
      }
      break;
    case mojom::SensorType::ABSOLUTE_ORIENTATION_EULER_ANGLES:
      if (absolute_orientation_sensor_is_available_) {
        sensor = std::make_unique<FakeSensor>(
            mojom::SensorType::ABSOLUTE_ORIENTATION_EULER_ANGLES, buffer);
        absolute_orientation_sensor_ = sensor.get();
        absolute_orientation_sensor_->SetReading(
            absolute_orientation_sensor_reading_);
      }
      break;
    default:
      NOTIMPLEMENTED();
  }

  if (sensor) {
    auto init_params = mojom::SensorInitParams::New();
    init_params->client_receiver = sensor->GetClient();
    init_params->memory = shared_buffer_handle_->Clone(
        mojo::SharedBufferHandle::AccessMode::READ_ONLY);
    init_params->buffer_offset = sensor->GetBufferOffset();
    init_params->default_configuration = sensor->GetDefaultConfiguration();
    init_params->maximum_frequency = sensor->GetMaximumSupportedFrequency();
    init_params->minimum_frequency = sensor->GetMinimumSupportedFrequency();

    mojo::MakeSelfOwnedReceiver(
        std::move(sensor),
        init_params->sensor.InitWithNewPipeAndPassReceiver());
    std::move(callback).Run(mojom::SensorCreationResult::SUCCESS,
                            std::move(init_params));
  } else {
    std::move(callback).Run(mojom::SensorCreationResult::ERROR_NOT_AVAILABLE,
                            nullptr);
  }
}

void FakeSensorProvider::Bind(
    mojo::PendingReceiver<mojom::SensorProvider> receiver) {
  receivers_.Add(this, std::move(receiver));
}

void FakeSensorProvider::SetAmbientLightSensorData(double value) {
  ambient_light_sensor_reading_.als.timestamp =
      (base::TimeTicks::Now() - base::TimeTicks()).InSecondsF();
  ambient_light_sensor_reading_.als.value = value;
}

void FakeSensorProvider::SetAccelerometerData(double x, double y, double z) {
  accelerometer_reading_.raw.timestamp =
      (base::TimeTicks::Now() - base::TimeTicks()).InSecondsF();
  accelerometer_reading_.accel.x = x;
  accelerometer_reading_.accel.y = y;
  accelerometer_reading_.accel.z = z;
}

void FakeSensorProvider::SetLinearAccelerationSensorData(double x,
                                                         double y,
                                                         double z) {
  linear_acceleration_sensor_reading_.raw.timestamp =
      (base::TimeTicks::Now() - base::TimeTicks()).InSecondsF();
  linear_acceleration_sensor_reading_.accel.x = x;
  linear_acceleration_sensor_reading_.accel.y = y;
  linear_acceleration_sensor_reading_.accel.z = z;
}

void FakeSensorProvider::SetGyroscopeData(double x, double y, double z) {
  gyroscope_reading_.raw.timestamp =
      (base::TimeTicks::Now() - base::TimeTicks()).InSecondsF();
  gyroscope_reading_.gyro.x = x;
  gyroscope_reading_.gyro.y = y;
  gyroscope_reading_.gyro.z = z;
}

void FakeSensorProvider::SetRelativeOrientationSensorData(double alpha,
                                                          double beta,
                                                          double gamma) {
  relative_orientation_sensor_reading_.raw.timestamp =
      (base::TimeTicks::Now() - base::TimeTicks()).InSecondsF();
  relative_orientation_sensor_reading_.orientation_euler.x = beta;
  relative_orientation_sensor_reading_.orientation_euler.y = gamma;
  relative_orientation_sensor_reading_.orientation_euler.z = alpha;
}

void FakeSensorProvider::SetAbsoluteOrientationSensorData(double alpha,
                                                          double beta,
                                                          double gamma) {
  absolute_orientation_sensor_reading_.raw.timestamp =
      (base::TimeTicks::Now() - base::TimeTicks()).InSecondsF();
  absolute_orientation_sensor_reading_.orientation_euler.x = beta;
  absolute_orientation_sensor_reading_.orientation_euler.y = gamma;
  absolute_orientation_sensor_reading_.orientation_euler.z = alpha;
}

void FakeSensorProvider::UpdateAmbientLightSensorData(double value) {
  SetAmbientLightSensorData(value);
  EXPECT_TRUE(ambient_light_sensor_);
  ambient_light_sensor_->SetReading(ambient_light_sensor_reading_);
}

void FakeSensorProvider::UpdateAccelerometerData(double x, double y, double z) {
  SetAccelerometerData(x, y, z);
  EXPECT_TRUE(accelerometer_);
  accelerometer_->SetReading(accelerometer_reading_);
}

void FakeSensorProvider::UpdateLinearAccelerationSensorData(double x,
                                                            double y,
                                                            double z) {
  SetLinearAccelerationSensorData(x, y, z);
  EXPECT_TRUE(linear_acceleration_sensor_);
  linear_acceleration_sensor_->SetReading(linear_acceleration_sensor_reading_);
}

void FakeSensorProvider::UpdateGyroscopeData(double x, double y, double z) {
  SetGyroscopeData(x, y, z);
  EXPECT_TRUE(gyroscope_);
  gyroscope_->SetReading(gyroscope_reading_);
}

void FakeSensorProvider::UpdateRelativeOrientationSensorData(double alpha,
                                                             double beta,
                                                             double gamma) {
  SetRelativeOrientationSensorData(alpha, beta, gamma);
  EXPECT_TRUE(relative_orientation_sensor_);
  relative_orientation_sensor_->SetReading(
      relative_orientation_sensor_reading_);
}

void FakeSensorProvider::UpdateAbsoluteOrientationSensorData(double alpha,
                                                             double beta,
                                                             double gamma) {
  SetAbsoluteOrientationSensorData(alpha, beta, gamma);
  EXPECT_TRUE(absolute_orientation_sensor_);
  absolute_orientation_sensor_->SetReading(
      absolute_orientation_sensor_reading_);
}

bool FakeSensorProvider::CreateSharedBufferIfNeeded() {
  if (shared_buffer_mapping_.get())
    return true;

  if (!shared_buffer_handle_.is_valid()) {
    shared_buffer_handle_ =
        mojo::SharedBufferHandle::Create(kSharedBufferSizeInBytes);
    if (!shared_buffer_handle_.is_valid())
      return false;
  }

  // Create read/write mapping now, to ensure it is kept writable
  // after the region is sealed read-only on Android.
  shared_buffer_mapping_ = shared_buffer_handle_->Map(kSharedBufferSizeInBytes);
  return shared_buffer_mapping_.get() != nullptr;
}

SensorReadingSharedBuffer*
FakeSensorProvider::GetSensorReadingSharedBufferForType(
    mojom::SensorType type) {
  auto* ptr = static_cast<char*>(shared_buffer_mapping_.get());
  if (!ptr)
    return nullptr;

  ptr += SensorReadingSharedBuffer::GetOffset(type);
  memset(ptr, 0, kReadingBufferSize);
  return reinterpret_cast<SensorReadingSharedBuffer*>(ptr);
}

}  // namespace device


text:
<?php
/*
Section: forgot-password
Language: French Français
*/

$translations = array(
    'h1' => 'Mot de passe oublié ?',

    'username' => 'Nom d\'utilisateur',

    'request-new-password' => 'Demander un nouveau mot de passe',

    'ph1' => 'Saisissez votre nom d\'utilisateur',

    'error1' => 'Les données que vous avez saisies sont incorrectes !',

    'success' => 'Vous avez reçu un email contenant votre nouveau mot de passe !',
);
?>


text:
import { Record } from 'immutable';

export const properties = {
  id: 0,
  username: 'Username',
  description: '',
  points: 0,
  imageUrl: '',
  linkedInUrl: '',
  location: '',
};
export default class User extends Record(properties) {}


text:
DROP TABLE IF EXISTS `{{store_id}}_tasks_summary`;

CREATE TABLE `{{store_id}}_tasks_summary` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `shift_id` BIGINT NOT NULL,
  `employee_id` varchar(30) NOT NULL,
  `shift_count` INT NOT NULL,
  `total_duration` INT NOT NULL,
  PRIMARY KEY (`id`)
);

INSERT INTO `{{store_id}}_tasks_summary` (shift_id, employee_id, shift_count, total_duration)
SELECT shift_id, employee_id, count(shift_id) as shift_count, SUM(duration) as total_duration FROM `{{store_id}}_tasks` group by shift_id,employee_id;

########################
# Timesheets
########################
DROP TABLE IF EXISTS `{{store_id}}_timesheets_summary`;

CREATE TABLE `{{store_id}}_timesheets_summary` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `employee_id` int(100) NOT NULL,
  `day` date NULL,
  `min` BIGINT NULL,
  `max` BIGINT NULL,
  `list` varchar(200) DEFAULT NULL,
  `count` DOUBLE NULL,
  PRIMARY KEY (`id`)
);

INSERT INTO `{{store_id}}_timesheets_summary` (employee_id, day, min, max, list, count)
SELECT MIN(employee_id) employee_id, DATE(CONVERT_TZ(FROM_UNIXTIME(MIN(event_time)/1000),'+00:00','-04:00')) as day, MIN(event_time) as min, MAX(event_time) as max, GROUP_CONCAT(event_time) as list, COUNT(event_time) as count from `{{store_id}}_timesheets` GROUP BY DATE(CONVERT_TZ(FROM_UNIXTIME(event_time/1000),'+00:00','-04:00')), employee_id;


text:
import numpy as np
import math

"""
 ==================================
 Problem 3: Neural Network Basics
 ==================================
    Generates a neural network with the following architecture:
        Fully connected neural network.
        Input vector takes in two features.
        One hidden layer with three neurons whose activation function is ReLU.
        One output neuron whose activation function is the identity function.
"""

def rectified_linear_unit(x):
    """ Returns the ReLU of x, or the maximum between 0 and x."""
    # TODO

def rectified_linear_unit_derivative(x):
    """ Returns the derivative of ReLU."""
    # TODO

def output_layer_activation(x):
    """ Linear function, returns input as is. """
    return x

def output_layer_activation_derivative(x):
    """ Returns the derivative of a linear function: 1. """
    return 1

class NeuralNetwork():
    """
        Contains the following functions:
            -train: tunes parameters of the neural network based on error obtained from forward propagation.
            -predict: predicts the label of a feature vector based on the class's parameters.
            -train_neural_network: trains a neural network over all the data points for the specified number of epochs during initialization of the class.
            -test_neural_network: uses the parameters specified at the time in order to test that the neural network classifies the points given in testing_points within a margin of error.
    """

    def __init__(self):

        # DO NOT CHANGE PARAMETERS
        self.input_to_hidden_weights = np.matrix('1 1; 1 1; 1 1')
        self.hidden_to_output_weights = np.matrix('1 1 1')
        self.biases = np.matrix('0; 0; 0')
        self.learning_rate = .001
        self.epochs_to_train = 10
        self.training_points = [((2,1), 10), ((3,3), 21), ((4,5), 32), ((6, 6), 42)]
        self.testing_points = [(1,1), (2,2), (3,3), (5,5), (10,10)]

    def train(self, x1, x2, y):

        ### Forward propagation ###
        input_values = np.matrix([[x1],[x2]]) # 2 by 1

        # Calculate the input and activation of the hidden layer
        hidden_layer_weighted_input = # TODO (3 by 1 matrix)
        hidden_layer_activation = # TODO (3 by 1 matrix)

        output =  # TODO
        activated_output = # TODO

        ### Backpropagation ###

        # Compute gradients
        output_layer_error = # TODO
        hidden_layer_error = # TODO (3 by 1 matrix)

        bias_gradients = # TODO
        hidden_to_output_weight_gradients = # TODO
        input_to_hidden_weight_gradients = # TODO

        # Use gradients to adjust weights and biases using gradient descent
        self.biases = # TODO
        self.input_to_hidden_weights = # TODO
        self.hidden_to_output_weights = # TODO

    def predict(self, x1, x2):

        input_values = np.matrix([[x1],[x2]])

        # Compute output for a single input(should be same as the forward propagation in training)
        hidden_layer_weighted_input = # TODO
        hidden_layer_activation = # TODO
        output = # TODO
        activated_output = # TODO

        return activated_output.item()

    # Run this to train your neural network once you complete the train method
    def train_neural_network(self):

        for epoch in range(self.epochs_to_train):
            for x,y in self.training_points:
                self.train(x[0], x[1], y)

    # Run this to test your neural network implementation for correctness after it is trained
    def test_neural_network(self):

        for point in self.testing_points:
            print("Point,", point, "Prediction,", self.predict(point[0], point[1]))
            if abs(self.predict(point[0], point[1]) - 7*point[0]) < 0.1:
                print("Test Passed")
            else:
                print("Point ", point[0], point[1], " failed to be predicted correctly.")
                return

x = NeuralNetwork()

x.train_neural_network()

# UNCOMMENT THE LINE BELOW TO TEST YOUR NEURAL NETWORK
# x.test_neural_network()


text:
<?php

namespace ByTIC\Payments\Models\Purchase\Traits;

use ByTIC\Payments\Models\BillingRecord\Traits\RecordTrait as BillingRecord;
use ByTIC\Payments\Models\BillingRecord\Traits\RecordTrait as BillingRecordTrait;
use ByTIC\Payments\Models\Methods\Traits\RecordTrait;
use ByTIC\Payments\Models\PurchaseSessions\PurchaseSessionTrait;
use ByTIC\Payments\Subscriptions\SubscriptionBuilder;
use Exception;
use Nip\Records\AbstractModels\RecordManager;
use Nip\Records\Collections\Associated;
use Omnipay\Common\Message\RequestInterface;

/**
 * Trait IsPurchasableModelTrait
 * @package ByTIC\Payments\Models\Purchase\Traits
 *
 * @property int $id
 * @property string $status
 * @property string $status_notes
 * @property string $received
 * @property string $created
 *
 * @method string getConfirmURL()
 * @method string getIpnURL()
 * @method update()
 * @method string getClassName()
 * @method string getStatus()
 *
 * @method RecordManager getManager()
 * @method PurchaseSessionTrait[]|Associated getPurchasesSessions()
 */
trait IsPurchasableModelTrait
{
    use IsPurchasableTrait;

    /**
     * @return RequestInterface
     */
    public function getPurchaseRequest()
    {
        return $this->getPaymentGateway()->purchaseFromModel($this);
    }

    /**
     * @return bool|\ByTIC\Payments\Gateways\Providers\AbstractGateway\Traits\GatewayTrait|null
     */
    public function getPaymentGateway()
    {
        return $this->getPaymentMethod()->getGateway();
    }

    /**
     * @return RecordTrait
     */
    abstract public function getPaymentMethod();

    /**
     * @param $note
     */
    public function saveGatewayNote($note)
    {
        $this->setGatewayNotes($note);
        $this->update();
    }

    /**
     * @param $note
     */
    public function setGatewayNotes($note)
    {
        $this->status_notes = $note;
    }

    /**
     * @return array
     * @throws Exception
     */
    public function getPurchaseParametersCard()
    {
        $params = null;
        $billing = $this->getPurchaseBillingRecord();
        if (!is_object($billing)) {
            throw new Exception(
                sprintf(
                    'PurchaseBillingRecord is not an object in [%s]',
                    $this->getClassName()
                )
            );
        }
        if (!in_array(BillingRecordTrait::class, class_uses($billing))) {
            throw new Exception(
                sprintf(
                    'Billing record in %s must use BillingRecordTrait %s',
                    $this->getClassName(),
                    BillingRecordTrait::class
                )
            );
        }
        $params = [];
        $params['firstName'] = $billing->getFirstName();
        $params['lastName'] = $billing->getLastName();
        $params['email'] = $billing->getEmail();
        $params['phone'] = $billing->getPurchasePhone();
        $params['city'] = $billing->getPurchaseCity();
        $params['country'] = $billing->getPurchaseCountry();

        return $params;
    }

    /**
     * @return BillingRecord|null
     */
    public function getPurchaseBillingRecord()
    {
        return null;
    }

    /**
     * @return SubscriptionBuilder
     */
    public function newSubscription()
    {
        return SubscriptionBuilder::fromPurchase($this);
    }

    /**
     * @return mixed
     */
    public function getConfirmStatusTitle()
    {
        return $this->getManager()->getMessage('confirm.' . $this->getStatus()->getName());
    }
}


text:
<?php
$pagetitle='Linkwalla Login';
$pagetype='form';
require_once 'lwFunctions.php';
if($_GET["action"] == "logout") {
    lw_logout(); // Kills the login cooie
    header("Location: index.php"); // retrns to the home page
}
if($_POST["action"] == "login") {
    $password = $_POST["password"];
    $l_username = $_POST["lwusername"];
    lw_login($password, $l_username);
}
include 'head.php';
?>

Log in

<?php
  if($_GET["error"] == "yes") {
    echo '
Error: That was the wrong username/password.
';
  }
?>

Please fill in the missing fields.

<form class="checkSubmit" action="login.php" method="post">

	Username
	<input type="text" name="lwusername" id="lwusername" class="required" size="20" maxlength="20" />

	Password
	<input type="password" name="password" id="password" class="required" size="20" maxlength="20" />

	<input name="action" type="hidden" value="login" />

	<input type="submit" value="submit" />

</form>
<?php include 'foot.php'; ?>


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:clickable="true"
        android:background="#FFFFFF"
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        android:orientation="vertical">

    <TextView xmlns:android="http://schemas.android.com/apk/res/android"
              android:padding="@dimen/default_padding"
              android:id="@+id/fairy_text"
              android:textSize="18sp"
              android:layout_width="match_parent"
              android:layout_height="wrap_content"
              android:drawablePadding="@dimen/default_padding"
              android:gravity="center_vertical|left"
              android:textStyle="bold"
              android:text="@string/first_scan_successful"
              android:layout_marginTop="@dimen/default_padding_half"
              android:textAppearance="@style/FairySpeechbubble">

    </TextView>
    <View
            android:layout_marginTop="@dimen/default_padding_half"
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:id="@+id/divider1"
            android:background="@color/grey6"/>

    <TextView android:text="@string/feedback_description"
              android:textSize="16sp"
              android:id="@+id/explanation_text"
              android:padding="@dimen/default_padding"
              android:background="@android:color/white"
              android:layout_width="match_parent"
              android:layout_height="wrap_content"/>

    <View
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:id="@+id/divider2"
            android:background="@color/grey6"/>

    <LinearLayout android:layout_width="match_parent"
                  android:orientation="horizontal"
                  android:layout_height="@dimen/button_height">
        <Button android:layout_weight="1"
                android:textSize="14sp"
                android:id="@+id/could_be_better"
                style="?android:attr/borderlessButtonStyle"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:text="@string/could_be_better"/>
        <View android:layout_width="1dp"
              android:id="@+id/button_divider"
              android:layout_marginLeft="@dimen/default_padding_half"
              android:layout_marginRight="@dimen/default_padding_half"
              android:layout_height="@dimen/button_height"
              android:background="@color/grey6"/>
        <Button android:layout_weight="1"
                android:textSize="14sp"
                android:id="@+id/love_it"
                style="?android:attr/borderlessButtonStyle"
                android:drawableLeft="@drawable/ic_heart"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:text="@string/love_it"/>

    </LinearLayout>

</LinearLayout><!-- From: file:/C:/Users/12125/Desktop/OCR/textfairy/app/src/main/res/layout/dialog_feedback.xml -->


text:
//
//  GBUtility_iOS.h
//  GBToolbox
//
//  Created by Luka Mirosevic on 05/02/2013.
//  Copyright (c) 2013 Luka Mirosevic. All rights reserved.
//

#import "GBTypes_Common.h"
#import "GBTypes_iOS.h"

#import "GBUtility_Common.h"
#import "UIControl+GBToolbox.h"

#import <QuartzCore/QuartzCore.h>
#import <CoreLocation/CoreLocation.h>
#import <MessageUI/MessageUI.h>
#import <MessageUI/MFMailComposeViewController.h>

@class GBAddress;

@interface GBToolbox (iOS)

#pragma mark - UIView

NSUInteger tagFromUIViewSubclass(_Nullable id sender);

#pragma mark - View Hierarchy

UIViewController * _Nullable TopmostViewController();
UIViewController * _Nullable TopmostViewControllerWithRootViewController(UIViewController * _Nullable rootViewController);

#pragma mark - Screen Locking

+(BOOL)isAutoScreenLockingEnabled;
+(void)enableAutoScreenLocking:(BOOL)enable;

#pragma mark - Torch

/**
 Enables or disables the device's flash/torch if the device has one
 */
void EnableTorch(BOOL enable);

#pragma mark - App Store redirect

void RedirectToAppStore(NSString * _Nonnull appID);

#pragma mark - Images

UIImage * _Nullable Image(NSString * _Nonnull name);
UIImage * _Nullable ImageResizableWithCapInsets(NSString * _Nonnull name, CGFloat topCap, CGFloat leftCap, CGFloat bottomCap, CGFloat rightCap);

#pragma mark - Clipping

CAShapeLayer * _Nonnull RoundClippingMaskInRectWithMargin(CGRect rect, UIEdgeInsets margin);
UIBezierPath * _Nonnull RoundBezierPathForRectWithMargin(CGRect rect, UIEdgeInsets margin);

#pragma mark - Push Notifications

BOOL IsPushDisabled();

#pragma mark - UITableView

BOOL IsCellAtIndexPathFullyVisible(NSIndexPath * _Nullable indexPath, UITableView * _Nullable tableView);

#pragma mark - Keyboard hiding

void DismissKeyboard();

#pragma mark - Twitter

BOOL IsTwitterAccountAvailable();

#pragma mark - Localisation

NSString * _Nullable UIKitLocalizedString(NSString * _Nullable string);

#pragma mark - Vibration

void VibrateDevice();

#pragma mark - Colors

//Returns a random color with a bias towards the more saturated and brighter colors
UIColor * _Nonnull RandomColor();

#pragma mark - Auto Layout

void AutoLayoutDebugOn(BOOL crashOnTrigger);
NSString * _Nonnull AutoLayoutViewPointer(NSObject * _Nonnull object);
NSDictionary * _Nonnull AutoLayoutPointerViewsDictionaryForViews(NSArray * _Nonnull views);

#pragma mark - Debugging

void DebugCode(VoidBlock _Nonnull code);

UIButton * _Nonnull RegisterDebugButton(NSString * _Nonnull title, GBActionBlock _Nonnull action);

#pragma mark - Geocoding

void ReverseGeocodeLocation(CLLocation * _Nullable location, void(^_Nullable block)(GBAddress * _Nullable address));

#pragma mark - UIViewController containment

void AddChildViewController(UIViewController * _Nonnull hostViewController, UIViewController * _Nonnull childViewController);
void AddChildViewControllerToView(UIViewController * _Nonnull hostViewController, UIView * _Nonnull hostView, UIViewController * _Nonnull childViewController);
void RemoveChildViewController(UIViewController * _Nonnull childViewController);

#pragma mark - Actions

void OpenLinkInSafari(NSString * _Nullable link);
void OpenMap(CLLocation * _Nonnull location, NSString * _Nullable name);
void CallPhone(NSString * _Nonnull number);
void SendSMS(NSString * _Nonnull number);

#pragma mark - Fonts

void ListAvailableFonts();

#pragma mark - Disk utils

NSString * _Nonnull DocumentsDirectoryPath();
NSURL * _Nonnull DocumentsDirectoryURL();

#pragma mark - Cookies

void ClearCookies();

#pragma mark - Email

void ShowContactEmailOnViewController(UIViewController * _Nonnull viewController,  NSArray<NSString *> * _Nullable toAdresses,  NSString * _Nullable subject,  NSString * _Nullable body);

#pragma mark - Alerts

void ShowAlert(NSString * _Nullable title, NSString * _Nullable message, NSString * _Nullable dismissButtonTitle);

#pragma mark - Network

NSString * _Nullable CurrentWifiNetworkName();

@end