text:
"""
mbed SDK
Copyright (c) 2011-2013 ARM Limited

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

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

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

def create_headers(args):
    return { 'X-Api-Key':  args.api_key }

def finish_command(command, response):
    print(command, response.status_code, response.reason)
    print(response.text)

    if response.status_code < 400:
        sys.exit(0)
    else:
        sys.exit(2)

def create_build(args):
    build = {}
    build['buildType'] = args.build_type
    build['number'] = args.build_number
    build['source'] = args.build_source
    build['status'] = 'running'

    if build['buildType'] == 'Pull_Request':
        build['buildType'] = 'Pull Request'

    r = requests.post(urlparse.urljoin(args.url, "api/builds"), headers=create_headers(args), json=build)

    if r.status_code < 400:
        if args.property_file_format:
            print("MBED_BUILD_ID=" + r.text)
        else:
            print(r.text)

        sys.exit(0)
    else:
        sys.exit(2)

def finish_build(args):
    data = {}
    data['status'] = 'completed'

    r = requests.put(urlparse.urljoin(args.url, "api/builds/" + args.build_id), headers=create_headers(args), json=data)
    finish_command('finish-build', r)

def abort_build(args):
    data = {}
    data['status'] = 'aborted'

    r = requests.put(urlparse.urljoin(args.url, "api/builds/" + args.build_id), headers=create_headers(args), json=data)
    finish_command('abort-build', r)

def add_project_runs(args):
    '''
    -------------------------------------
    Notes on 'project_run_data' structure:
    --------------------------------------
        'projectRuns' - Tree structure used to keep track of what projects have
            been logged in different report files. The tree is organized as follows:

            'projectRuns': {                - Root element of tree

                'hostOs': {                 - Host OS on which project was built/tested
                                                - ex. windows, linux, or mac

                    'platform': {           - Platform for which project was built/tested
                                              (Corresponds to platform names in targets.py)
                                                - ex. K64F, LPC1768, NRF51822, etc.

                        'toolchain': {      - Toolchain with which project was built/tested
                                              (Corresponds to TOOLCHAIN_CLASSES names in toolchains/__init__.py)
                                                - ex. ARM, uARM, GCC_ARM, etc.

                            'project': {    - Project that was build/tested
                                              (Corresponds to test id in tests.py or library id in libraries.py)
                                                - For tests, ex. MBED_A1, MBED_11, DTCT_1 etc.
                                                - For libraries, ex. MBED, RTX, RTOS, etc.

                            },
                            ...
                        },
                        ...
                    },
                    ...
                }
            }

        'platforms_set' - Set of all the platform names mentioned in the given report files

        'toolchains_set' - Set of all the toolchain names mentioned in the given report files

        'names_set' - Set of all the project names mentioned in the given report files

        'hostOses_set' - Set of all the host names given (only given by the command line arguments)
    '''

    project_run_data = {}
    project_run_data['projectRuns'] = {}
    project_run_data['platforms_set'] = set()
    project_run_data['vendors_set'] = set()
    project_run_data['toolchains_set'] = set()
    project_run_data['names_set'] = set()
    project_run_data['hostOses_set'] = set()
    project_run_data['hostOses_set'].add(args.host_os)

    add_report(project_run_data, args.build_report, True, args.build_id, args.host_os)

    if (args.test_report):
        add_report(project_run_data, args.test_report, False, args.build_id, args.host_os)

    ts_data = format_project_run_data(project_run_data)
    r = requests.post(urlparse.urljoin(args.url, "api/projectRuns"), headers=create_headers(args), json=ts_data)
    finish_command('add-project-runs', r)

def format_project_run_data(project_run_data):
    ts_data = {}
    ts_data['projectRuns'] = []

    for hostOs in project_run_data['projectRuns'].values():
        for platform in hostOs.values():
            for toolchain in platform.values():
                for project in toolchain.values():
                    ts_data['projectRuns'].append(project)

    ts_data['platforms'] = list(project_run_data['platforms_set'])
    ts_data['vendors'] = list(project_run_data['vendors_set'])
    ts_data['toolchains'] = list(project_run_data['toolchains_set'])
    ts_data['names'] = list(project_run_data['names_set'])
    ts_data['hostOses'] = list(project_run_data['hostOses_set'])

    return ts_data

def find_project_run(projectRuns, project):
    keys = ['hostOs', 'platform', 'toolchain', 'project']

    elem = projectRuns

    for key in keys:
        if not project[key] in elem:
            return None

        elem = elem[project[key]]

    return elem

def add_project_run(projectRuns, project):
    keys = ['hostOs', 'platform', 'toolchain']

    elem = projectRuns

    for key in keys:
        if not project[key] in elem:
            elem[project[key]] = {}

        elem = elem[project[key]]

    elem[project['project']] = project

def update_project_run_results(project_to_update, project, is_build):
    if is_build:
        project_to_update['buildPass'] = project['buildPass']
        project_to_update['buildResult'] = project['buildResult']
        project_to_update['buildOutput'] = project['buildOutput']
    else:
        project_to_update['testPass'] = project['testPass']
        project_to_update['testResult'] = project['testResult']
        project_to_update['testOutput'] = project['testOutput']

def update_project_run(projectRuns, project, is_build):
    found_project = find_project_run(projectRuns, project)
    if found_project:
        update_project_run_results(found_project, project, is_build)
    else:
        add_project_run(projectRuns, project)

def add_report(project_run_data, report_file, is_build, build_id, host_os):
    tree = None

    try:
        tree = ET.parse(report_file)
    except:
        print(sys.exc_info()[0])
        print('Invalid path to report: %s', report_file)
        sys.exit(1)

    test_suites = tree.getroot()

    for test_suite in test_suites:
        platform = ""
        toolchain = ""
        vendor = ""
        for properties in test_suite.findall('properties'):
            for property in properties.findall('property'):
                if property.attrib['name'] == 'target':
                    platform = property.attrib['value']
                    project_run_data['platforms_set'].add(platform)
                elif property.attrib['name'] == 'toolchain':
                    toolchain = property.attrib['value']
                    project_run_data['toolchains_set'].add(toolchain)
                elif property.attrib['name'] == 'vendor':
                    vendor = property.attrib['value']
                    project_run_data['vendors_set'].add(vendor)

        for test_case in test_suite.findall('testcase'):
            projectRun = {}
            projectRun['build'] = build_id
            projectRun['hostOs'] = host_os
            projectRun['platform'] = platform
            projectRun['toolchain'] = toolchain
            projectRun['project'] = test_case.attrib['classname'].split('.')[-1]
            projectRun['vendor'] = vendor

            project_run_data['names_set'].add(projectRun['project'])

            skipped = test_case.findall('skipped')

            if not skipped:
                system_outs = test_case.findall('system-out')

                output = ""
                if system_outs:
                    output = system_outs[0].text

                if is_build:
                    projectRun['buildOutput'] = output
                else:
                    projectRun['testOutput'] = output

                errors = test_case.findall('error')
                failures = test_case.findall('failure')
                projectRunPass = None
                result = None

                if errors:
                    projectRunPass = False
                    result = errors[0].attrib['message']
                elif failures:
                    projectRunPass = False
                    result = failures[0].attrib['message']
                else:
                    projectRunPass = True
                    result = 'OK'

                if is_build:
                    projectRun['buildPass'] = projectRunPass
                    projectRun['buildResult'] = result
                else:
                    projectRun['testPass'] = projectRunPass
                    projectRun['testResult'] = result

                update_project_run(project_run_data['projectRuns'], projectRun, is_build)

def main(arguments):
    # Register and parse command line arguments
    parser = argparse.ArgumentParser()
    parser.add_argument('-u', '--url', required=True, help='url to ci site')
    parser.add_argument('-k', '--api-key', required=True, help='api-key for posting data')

    subparsers = parser.add_subparsers(help='subcommand help')

    create_build_parser = subparsers.add_parser('create-build', help='create a new build')
    create_build_parser.add_argument('-b', '--build-number', required=True, help='build number')
    create_build_parser.add_argument('-T', '--build-type', choices=['Nightly', 'Limited', 'Pull_Request'], required=True, help='type of build')
    create_build_parser.add_argument('-s', '--build-source', required=True, help='url to source of build')
    create_build_parser.add_argument('-p', '--property-file-format', action='store_true', help='print result in the property file format')
    create_build_parser.set_defaults(func=create_build)

    finish_build_parser = subparsers.add_parser('finish-build', help='finish a running build')
    finish_build_parser.add_argument('-b', '--build-id', required=True, help='build id')
    finish_build_parser.set_defaults(func=finish_build)

    abort_build_parser = subparsers.add_parser('abort-build', help='abort a running build')
    abort_build_parser.add_argument('-b', '--build-id', required=True, help='build id')
    abort_build_parser.set_defaults(func=abort_build)

    add_project_runs_parser = subparsers.add_parser('add-project-runs', help='add project runs to a build')
    add_project_runs_parser.add_argument('-b', '--build-id', required=True, help='build id')
    add_project_runs_parser.add_argument('-r', '--build-report', required=True, help='path to junit xml build report')
    add_project_runs_parser.add_argument('-t', '--test-report', required=False, help='path to junit xml test report')
    add_project_runs_parser.add_argument('-o', '--host-os', required=True, help='host os on which test was run')
    add_project_runs_parser.set_defaults(func=add_project_runs)

    args = parser.parse_args(arguments)
    args.func(args)

if __name__ == '__main__':
    main(sys.argv[1:])


text:
// ASM: a very small and fast Java bytecode manipulation framework
// Copyright (c) 2000-2011 INRIA, France Telecom
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// 1. Redistributions of source code must retain the above copyright
//    notice, this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright
//    notice, this list of conditions and the following disclaimer in the
//    documentation and/or other materials provided with the distribution.
// 3. Neither the name of the copyright holders nor the names of its
//    contributors may be used to endorse or promote products derived from
//    this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
package org.apache.tapestry5.internal.plastic.asm;

/**
 * A visitor to visit a Java module. The methods of this class must be called in the following
 * order: ( {@code visitMainClass} | ( {@code visitPackage} | {@code visitRequire} | {@code
 * visitExport} | {@code visitOpen} | {@code visitUse} | {@code visitProvide} )* ) {@code visitEnd}.
 *
 * @author Remi Forax
 * @author Eric Bruneton
 */
public abstract class ModuleVisitor {
  /**
   * The ASM API version implemented by this visitor. The value of this field must be one of {@link
   * Opcodes#ASM6} or {@link Opcodes#ASM7}.
   */
  protected final int api;

  /**
   * The module visitor to which this visitor must delegate method calls. May be {@literal null}.
   */
  protected ModuleVisitor mv;

  /**
   * Constructs a new {@link ModuleVisitor}.
   *
   * @param api the ASM API version implemented by this visitor. Must be one of {@link Opcodes#ASM6}
   *     or {@link Opcodes#ASM7}.
   */
  public ModuleVisitor(final int api) {
    this(api, null);
  }

  /**
   * Constructs a new {@link ModuleVisitor}.
   *
   * @param api the ASM API version implemented by this visitor. Must be one of {@link Opcodes#ASM6}
   *     or {@link Opcodes#ASM7}.
   * @param moduleVisitor the module visitor to which this visitor must delegate method calls. May
   *     be null.
   */
  public ModuleVisitor(final int api, final ModuleVisitor moduleVisitor) {
    if (api != Opcodes.ASM9
        && api != Opcodes.ASM8
        && api != Opcodes.ASM7
        && api != Opcodes.ASM6
        && api != Opcodes.ASM5
        && api != Opcodes.ASM4
        && api != Opcodes.ASM10_EXPERIMENTAL) {
      throw new IllegalArgumentException("Unsupported api " + api);
    }
    if (api == Opcodes.ASM10_EXPERIMENTAL) {
      Constants.checkAsmExperimental(this);
    }
    this.api = api;
    this.mv = moduleVisitor;
  }

  /**
   * Visit the main class of the current module.
   *
   * @param mainClass the internal name of the main class of the current module.
   */
  public void visitMainClass(final String mainClass) {
    if (mv != null) {
      mv.visitMainClass(mainClass);
    }
  }

  /**
   * Visit a package of the current module.
   *
   * @param packaze the internal name of a package.
   */
  public void visitPackage(final String packaze) {
    if (mv != null) {
      mv.visitPackage(packaze);
    }
  }

  /**
   * Visits a dependence of the current module.
   *
   * @param module the fully qualified name (using dots) of the dependence.
   * @param access the access flag of the dependence among {@code ACC_TRANSITIVE}, {@code
   *     ACC_STATIC_PHASE}, {@code ACC_SYNTHETIC} and {@code ACC_MANDATED}.
   * @param version the module version at compile time, or {@literal null}.
   */
  public void visitRequire(final String module, final int access, final String version) {
    if (mv != null) {
      mv.visitRequire(module, access, version);
    }
  }

  /**
   * Visit an exported package of the current module.
   *
   * @param packaze the internal name of the exported package.
   * @param access the access flag of the exported package, valid values are among {@code
   *     ACC_SYNTHETIC} and {@code ACC_MANDATED}.
   * @param modules the fully qualified names (using dots) of the modules that can access the public
   *     classes of the exported package, or {@literal null}.
   */
  public void visitExport(final String packaze, final int access, final String... modules) {
    if (mv != null) {
      mv.visitExport(packaze, access, modules);
    }
  }

  /**
   * Visit an open package of the current module.
   *
   * @param packaze the internal name of the opened package.
   * @param access the access flag of the opened package, valid values are among {@code
   *     ACC_SYNTHETIC} and {@code ACC_MANDATED}.
   * @param modules the fully qualified names (using dots) of the modules that can use deep
   *     reflection to the classes of the open package, or {@literal null}.
   */
  public void visitOpen(final String packaze, final int access, final String... modules) {
    if (mv != null) {
      mv.visitOpen(packaze, access, modules);
    }
  }

  /**
   * Visit a service used by the current module. The name must be the internal name of an interface
   * or a class.
   *
   * @param service the internal name of the service.
   */
  public void visitUse(final String service) {
    if (mv != null) {
      mv.visitUse(service);
    }
  }

  /**
   * Visit an implementation of a service.
   *
   * @param service the internal name of the service.
   * @param providers the internal names of the implementations of the service (there is at least
   *     one provider).
   */
  public void visitProvide(final String service, final String... providers) {
    if (mv != null) {
      mv.visitProvide(service, providers);
    }
  }

  /**
   * Visits the end of the module. This method, which is the last one to be called, is used to
   * inform the visitor that everything have been visited.
   */
  public void visitEnd() {
    if (mv != null) {
      mv.visitEnd();
    }
  }
}

redpajama_set_name: RedPajamaGithub


text:
package javax.el;

import java.beans.FeatureDescriptor;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.ListResourceBundle;
import java.util.ResourceBundle;

import org.junit.Assert;
import org.junit.Test;

import org.apache.jasper.el.ELContextImpl;

public class TestResourceBundleELResolver {

    @Test
    public void bug53001() {
        ExpressionFactory factory = ExpressionFactory.newInstance();
        ELContext context = new ELContextImpl();

        ResourceBundle rb = new TesterResourceBundle();

        ValueExpression var = factory.createValueExpression(rb,
                ResourceBundle.class);
        context.getVariableMapper().setVariable("rb", var);

        ValueExpression ve = factory.createValueExpression(context,
                "${rb.keys}", String.class);

        MethodExpression me = factory.createMethodExpression(context,
                "${rb.getKeys()}", Enumeration.class, null);

        // Ensure we are specification compliant
        String result1 = (String) ve.getValue(context);
        Assert.assertEquals("???keys???", result1);

        // Check that the method expression does return the keys
        Object result2 = me.invoke(context, null);
        Assert.assertTrue(result2 instanceof Enumeration);
        @SuppressWarnings("unchecked")
        Enumeration<String> e = (Enumeration<String>) result2;

        Assert.assertTrue(e.hasMoreElements());
        Assert.assertEquals("key2", e.nextElement());
        Assert.assertTrue(e.hasMoreElements());
        Assert.assertEquals("key1", e.nextElement());
        Assert.assertFalse(e.hasMoreElements());
    }

    /**
     * Tests that a null context results in an NPE as per EL Javadoc.
     */
    @Test(expected = NullPointerException.class)
    public void testGetValue01() {
        ResourceBundleELResolver resolver = new ResourceBundleELResolver();
        resolver.getValue(null, new Object(), new Object());
    }

    /**
     * Tests that a valid property is not resolved if base is not
     * ResourceBundle.
     */
    @Test
    public void testGetValue02() {
        doNegativeTest(new Object(), new Object(), MethodUnderTest.GET_VALUE,
                true);
    }

    /**
     * Tests that a valid property is resolved.
     */
    @Test
    public void testGetValue03() {
        ResourceBundleELResolver resolver = new ResourceBundleELResolver();
        ELContext context = new ELContextImpl();

        ResourceBundle resourceBundle = new TesterResourceBundle();
        Object result = resolver.getValue(context, resourceBundle, "key1");

        Assert.assertEquals("value1", result);
        Assert.assertTrue(context.isPropertyResolved());

        result = resolver.getValue(context, resourceBundle, "unknown-key");

        Assert.assertEquals("???unknown-key???", result);
        Assert.assertTrue(context.isPropertyResolved());

        result = resolver.getValue(context, resourceBundle, null);

        Assert.assertNull(result);
        Assert.assertTrue(context.isPropertyResolved());
    }

    /**
     * Tests that a null context results in an NPE as per EL Javadoc.
     */
    @Test(expected = NullPointerException.class)
    public void testGetType01() {
        ResourceBundleELResolver resolver = new ResourceBundleELResolver();
        resolver.getType(null, new Object(), new Object());
    }

    /**
     * Tests that a valid property is not resolved if base is not
     * ResourceBundle.
     */
    @Test
    public void testGetType02() {
        doNegativeTest(new Object(), new Object(), MethodUnderTest.GET_TYPE,
                true);
    }

    /**
     * Tests that null will be returned when base is ResourceBundle. Checks that
     * the propertyResolved is true.
     */
    @Test
    public void testGetType03() {
        ResourceBundleELResolver resolver = new ResourceBundleELResolver();
        ELContext context = new ELContextImpl();

        ResourceBundle resourceBundle = new TesterResourceBundle();
        Class<?> result = resolver.getType(context, resourceBundle, "key1");

        Assert.assertNull(result);
        Assert.assertTrue(context.isPropertyResolved());
    }

    /**
     * Tests that a null context results in an NPE as per EL Javadoc.
     */
    @Test(expected = NullPointerException.class)
    public void testSetValue01() {
        ResourceBundleELResolver resolver = new ResourceBundleELResolver();
        resolver.setValue(null, new Object(), new Object(), new Object());
    }

    /**
     * Tests that a valid property is not set if base is not ResourceBundle.
     */
    @Test
    public void testSetValue02() {
        doNegativeTest(new Object(), new Object(), MethodUnderTest.SET_VALUE,
                false);
    }

    /**
     * Tests that an exception is thrown because the resolver is read only.
     */
    @Test(expected = PropertyNotWritableException.class)
    public void testSetValue03() {
        ResourceBundleELResolver resolver = new ResourceBundleELResolver();
        ELContext context = new ELContextImpl();

        ResourceBundle resourceBundle = new TesterResourceBundle();
        resolver.setValue(context, resourceBundle, new Object(), new Object());
    }

    /**
     * Tests that a null context results in an NPE as per EL Javadoc.
     */
    @Test(expected = NullPointerException.class)
    public void testIsReadOnly01() {
        ResourceBundleELResolver resolver = new ResourceBundleELResolver();
        resolver.isReadOnly(null, new Object(), new Object());
    }

    /**
     * Tests that the propertyResolved is false and readOnly is false if base is
     * not ResourceBundle.
     */
    @Test
    public void testIsReadOnly02() {
        ResourceBundleELResolver resolver = new ResourceBundleELResolver();
        ELContext context = new ELContextImpl();

        boolean result = resolver.isReadOnly(context, new Object(),
                new Object());

        Assert.assertFalse(result);
        Assert.assertFalse(context.isPropertyResolved());
    }

    /**
     * Tests that the readOnly is true always when the base is ResourceBundle.
     */
    @Test
    public void testIsReadOnly03() {
        ResourceBundleELResolver resolver = new ResourceBundleELResolver();
        ELContext context = new ELContextImpl();

        ResourceBundle resourceBundle = new TesterResourceBundle();
        boolean result = resolver.isReadOnly(context, resourceBundle,
                new Object());

        Assert.assertTrue(result);
        Assert.assertTrue(context.isPropertyResolved());
    }

    /**
     * Tests that a valid FeatureDescriptors are not returned if base is not
     * ResourceBundle.
     */
    @Test
    public void testGetFeatureDescriptors01() {
        ResourceBundleELResolver resolver = new ResourceBundleELResolver();
        ELContext context = new ELContextImpl();

        @SuppressWarnings("unchecked")
        Iterator<FeatureDescriptor> result = resolver.getFeatureDescriptors(
                context, new Object());

        Assert.assertNull(result);
    }

    /**
     * Tests that a valid FeatureDescriptors are returned.
     */
    @Test
    public void testGetFeatureDescriptors02() {
        ResourceBundleELResolver resolver = new ResourceBundleELResolver();
        ELContext context = new ELContextImpl();

        ResourceBundle resourceBundle = new TesterResourceBundle(
                new Object[][] { { "key", "value" } });
        @SuppressWarnings("unchecked")
        Iterator<FeatureDescriptor> result = resolver.getFeatureDescriptors(
                context, resourceBundle);

        while (result.hasNext()) {
            FeatureDescriptor featureDescriptor = result.next();
            Assert.assertEquals("key", featureDescriptor.getDisplayName());
            Assert.assertEquals("key", featureDescriptor.getName());
            Assert.assertEquals("", featureDescriptor.getShortDescription());
            Assert.assertFalse(featureDescriptor.isExpert());
            Assert.assertFalse(featureDescriptor.isHidden());
            Assert.assertTrue(featureDescriptor.isPreferred());
            Assert.assertEquals(String.class,
                    featureDescriptor.getValue(ELResolver.TYPE));
            Assert.assertEquals(Boolean.TRUE, featureDescriptor
                    .getValue(ELResolver.RESOLVABLE_AT_DESIGN_TIME));
        }
    }

    private static class TesterResourceBundle extends ListResourceBundle {

        public TesterResourceBundle() {
            this(new Object[][] { { "key1", "value1" }, { "key2", "value2" } });
        }

        public TesterResourceBundle(Object[][] contents) {
            this.contents = contents;
        }

        @Override
        protected Object[][] getContents() {
            return contents;
        }

        private Object[][] contents;
    }

    private void doNegativeTest(Object base, Object trigger,
            MethodUnderTest method, boolean checkResult) {
        ResourceBundleELResolver resolver = new ResourceBundleELResolver();
        ELContext context = new ELContextImpl();

        Object result = null;
        switch (method) {
        case GET_VALUE: {
            result = resolver.getValue(context, base, trigger);
            break;
        }
        case SET_VALUE: {
            resolver.setValue(context, base, trigger, new Object());
            break;
        }
        case GET_TYPE: {
            result = resolver.getType(context, base, trigger);
            break;
        }
        default: {
            // Should never happen
            Assert.fail("Missing case for method");
        }
        }

        if (checkResult) {
            Assert.assertNull(result);
        }
        Assert.assertFalse(context.isPropertyResolved());
    }

    private static enum MethodUnderTest {
        GET_VALUE, SET_VALUE, GET_TYPE
    }
}


text:
import os

import yaml

from .. import app

__all__ = ('data',)

# Data loaded on import time so file system is not read and YAML parsed
# on every request.
with open(os.path.join(app.static_folder, 'data', 'beginners.yml')) as f:
    data = yaml.safe_load(f.read())


text: Photos


text:
import { Meteor } from 'meteor/meteor';
import { Random } from 'meteor/random';
import { Tracker } from 'meteor/tracker';
import visitor from '../../imports/client/visitor';

Meteor.startup(() => {
	if (!localStorage.getItem('rocketChatLivechat')) {
		localStorage.setItem('rocketChatLivechat', Random.id());
	} else {
		Tracker.autorun((c) => {
			if (!visitor.getId() && visitor.getToken()) {
				Meteor.call('livechat:loginByToken', visitor.getToken(), (err, result) => {
					if (result && result._id) {
						visitor.setId(result._id);
						c.stop();
					}
				});
			}
		});
	}
});

Meteor.startup(() => {
	let connected = false;
	Tracker.autorun(function() {
		const connectionStatus = Meteor.status();
		if (visitor.getRoom() && visitor.getToken() && connectionStatus.connected && !connected) {
			connected = connectionStatus.connected;
			document.cookie = `rc_rid=${ visitor.getRoom() }; path=/`;
			document.cookie = `rc_token=${ visitor.getToken() }; path=/`;
			document.cookie = 'rc_room_type=l; path=/';
			visitor.setConnected();
		}
	});
});


text:
'''
The MIT License (MIT)

Copyright (c) 2017 Wolfgang Almeida <wolfgang.almeida@yahoo.com>

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

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

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

# Imports gerais
# ==============
from __future__ import print_function
from PyQt4 import QtCore, QtGui

import os
import sys
import ctypes
import platform
import subprocess

# Imports do programa
# ===================
from GlobalVars import GlobalVars
from DownloaderClass import Downloader
from MessageBoxClass import ShowMessageBox
from UpdaterClass import Updater

# Definindo a codificação padrão para UTF-8.
# ==========================================
reload(sys)
sys.setdefaultencoding('utf-8')

# Determinando a pasta 'home' do usuário.
# =======================================
if platform.system() == "Windows":
	buf = ctypes.create_unicode_buffer(1024)
	ctypes.windll.kernel32.GetEnvironmentVariableW(u"USERPROFILE", buf, 1024)
	home_dir = buf.value
else:
	home_dir = expanduser("~")

# Classe do gerenciador da janela principal
# =========================================
class WindowHandler(object):
	# Inicializando objetos da classe
	# ===============================
	def __init__(self, ui, MainWindow):
		self.ui = ui
		self.MainWindow = MainWindow
		self.messageBox = ShowMessageBox()

		# Propriedades da classe
		# ----------------------
		if platform.system() == "Windows":
			self.div = "\\"
		else:
			self.div = "/"
		self.isFFmpegPresent = False

		self.videoURL = ""
		self.selectedDir = ""
		self.saveOption = ""
		self.keepOriginal = None
		self.openChosenDirAfterDownload = None

		# Declarações da classe
		# ---------------------
		self.checkBinaries()

	# Verificando se os binários do youtube-dl e ffmpeg estão na pasta /bin
	# =====================================================================
	def checkBinaries(self):
		programLocation = os.getcwdu()
		GlobalVars.BinFolder = "%s%s%s" % (programLocation, self.div, "bin")

		GlobalVars.Youtube_dl = "%s%s%s" % (GlobalVars.BinFolder, self.div, GlobalVars.ExecutableName1)
		ffmpegBin = "%s%s%s" % (GlobalVars.BinFolder, self.div, GlobalVars.ExecutableName2)

		if not os.path.isfile(GlobalVars.Youtube_dl):
			self.messageBox.show(u"Erro!",
				QtGui.QMessageBox.Critical,
				u"Binário '%s' não está presente na pasta /bin!" % (GlobalVars.ExecutableName1),
				u"É necessário que o binário '%s' esteja presente na pasta /bin para" % (GlobalVars.ExecutableName1) +
				" realizar o download dos vídeos!",
				QtGui.QMessageBox.Ok,
				1)

		if not os.path.isfile(ffmpegBin):
			self.messageBox.show(u"Aviso!",
				QtGui.QMessageBox.Warning,
				u"Binário '%s' não está presente na pasta /bin!" % (GlobalVars.ExecutableName2),
				u"O programa não poderá fazer conversões de formatos sem o ffmpeg!",
				QtGui.QMessageBox.Ok,
				0)
			self.isFFmpegPresent = False
		else:
			self.isFFmpegPresent = True

	# Mostrando informações do programa no terminal auxiliar
	# ======================================================
	def displayInfo(self):
		print(u"====================================")
		print(u"SVD - Simple Video Downloader - v%s" % (GlobalVars.Version))
		print(u"====================================\n")

		print(u"Este prompt de comando serve de apoio para o programa.")
		print(u"Mantenha este prompt aberto enquanto o programa estiver sendo executado!")

	# Mostrando informações do programa em uma MessageBox
	# ===================================================
	def displayAbout(self):
		self.messageBox.show(u"Simple Video Downloader",
			QtGui.QMessageBox.Information,
			u"SVD - Simple Video Downloader - Versão %s" % (GlobalVars.Version),
			u"Criado por: Wolfgang Almeida - © 2017\n\n*** Este programa é licenciado sob a licença MIT ***" +
			u"\nVisite o repositório no GitHub: https://github.com/Wolfterro/SVD",
			QtGui.QMessageBox.Ok,
			0)

	# Inserindo a pasta de destino padrão
	# ===================================
	def setDefaultDir(self):
		self.ui.lineEdit_2.setText("%s%s%s" % (home_dir, self.div, GlobalVars.SaveFolder))

	# Saindo do programa
	# ==================
	def exitProgram(self):
		sys.exit(0)

	# Verificando a pasta de destino
	# ==============================
	def checkSelectedDir(self):
		if os.path.exists(unicode(self.selectedDir)):
			os.chdir(unicode(self.selectedDir))
		else:
			os.makedirs(unicode(self.selectedDir))
			os.chdir(unicode(self.selectedDir))

	# Método para selecionar pasta de destino.
	# ========================================
	def selectOutputDir(self):
		self.selectedDir = QtGui.QFileDialog.getExistingDirectory(self.MainWindow,
			'Selecione a pasta de destino:', home_dir, QtGui.QFileDialog.ShowDirsOnly)

		if self.selectedDir != "":
			if platform.system() == "Windows":
				self.ui.lineEdit_2.setText(self.selectedDir.replace("/", "\\"))
			else:
				self.ui.lineEdit_2.setText(self.selectedDir)

	# Congelando os botões da janela principal
	# ========================================
	def freezeProgramFields(self, freeze):
		if freeze:
			self.ui.pushButton.setEnabled(False)
			self.ui.toolButton.setEnabled(False)
			QtGui.QApplication.processEvents()
		else:
			self.ui.pushButton.setEnabled(True)
			self.ui.toolButton.setEnabled(True)
			QtGui.QApplication.processEvents()

	# Resgatando informações do usuário
	# =================================
	def gatherUserInformation(self):
		self.videoURL = str(self.ui.lineEdit.text())
		self.selectedDir = str(self.ui.lineEdit_2.text())
		self.checkSelectedDir()

		self.saveOption = str(self.ui.comboBox.currentText())
		self.keepOriginal = self.ui.checkBox_2.isChecked()
		self.openChosenDirAfterDownload = self.ui.checkBox.isChecked()

		if self.videoURL != "":
			self.beginDownloadProcess()
		else:
			self.messageBox.show(u"Erro!",
				QtGui.QMessageBox.Critical,
				u"URL do Vídeo ou Playlist vazia!",
				u"Insira a URL do Vídeo ou Playlist desejada e tente novamente!",
				QtGui.QMessageBox.Ok,
				0)

	# Iniciando o processo de download
	# ================================
	def beginDownloadProcess(self):
		self.freezeProgramFields(True)
		# ------------------------------------------------------------------------
		downloader = Downloader(self.videoURL, self.saveOption, self.keepOriginal)
		downloader.download()
		# ------------------------------------------------------------------------
		self.freezeProgramFields(False)

		if self.openChosenDirAfterDownload:
			if platform.system() == "Windows":
				os.startfile(unicode(self.selectedDir))
			else:
				try:
					subprocess.Popen(["xdg-open", "%s" % unicode(self.selectedDir)])
				except Exception as e:
					pass

	# Atualizando o binário do youtube-dl
	# ===================================
	def updateYoutube_dl(self):
		try:
			print(u"\n[SVD] Atualizando youtube-dl...")
			print(u"-------------------------------")

			self.freezeProgramFields(True)
			# -----------------------------------------------
			update = Updater()
			updateStatus = update.Youtube_DL()
			# -----------------------------------------------
			self.freezeProgramFields(False)

			if updateStatus:
				print(u"Versão atual: ", end="")
				subprocess.call("%s %s" % (GlobalVars.ExecutableName1, "--version"))
				print(u"\n[SVD] Atualização do youtube-dl concluída!")
				print(u"------------------------------------------")
			else:
				print(u"\n[SVD] Não foi possível atualizar o youtube-dl!")
				print(u"----------------------------------------------")
		except Exception as e:
			print(u"\n[SVD] Erro ao tentar atualizar o youtube-dl!")
			print(u"[SVD] Erro: %s" % (e))


text:
update sql_queries set query = '
DECLARE @user varchar(15)
DECLARE @block int
DECLARE @rppYear varchar(15)
SET @user = ?;
SET @block= ?;
SELECT rppWeekOrder as id, rppWeek, ''newVisit'' as form, [Sunday] AS Sun, [Monday] as Mon, [Tuesday] AS Tue,
[Wednesday] as Wed, [Thursday] as Thu,   [Friday] as Fri, [Saturday] as Sat     FROM
(SELECT     lkup_block.blockLabel as Block,lkup_date.rppWeek as rppWeek, lkup_date.rppWeekOrder as
rppWeekOrder, lkup_block.blockKey as BlockKey,         LKUP_date.dayName as ValDayName, FACT_visits.addedBy as addedBy     FROM
lkup_block   full outer join  LKUP_date ON lkup_block.blockKey = LKUP_date.block
RIGHT OUTER JOIN  FACT_visits ON LKUP_date.fullDate = FACT_visits.date
%WHERECLAUSE% AND addedBy=@user and blockKey=@block and deleteflag<>1) ps
PIVOT
(COUNT (BlockKey)  FOR ValDayName IN
([Sunday], [Monday], [Tuesday], [Wednesday], [Thursday], [Friday], [Saturday])) AS pv
UNION
(SELECT rppWeekOrder as id, rppWeek, ''newVisit'' as form, ''0'' as Sun,''0'' as Mon, ''0'' as Tue, ''0'' as Wed, ''0'' as Thu, ''0'' as Fri,
''0'' as Sat   FROM LKUP_date WHERE block = @block and (NOT (rppWeek IS NULL))
EXCEPT
SELECT DISTINCT  LKUP_date.rppWeekOrder, LKUP_date.rppWeek, ''newVisit'' as form, ''0'' as Sun,''0'' as Mon, ''0'' as Tue,
''0'' as Wed, ''0'' as Thu, ''0'' as Fri, ''0'' as Sat       FROM    FACT_visits
INNER JOIN  LKUP_date ON FACT_visits.date = LKUP_date.fullDate
INNER JOIN   lkup_block ON LKUP_date.block = lkup_block.blockKey
%WHERECLAUSE% AND       (FACT_visits.addedBy = @user) AND (LKUP_date.block = @block)and (FACT_visits.deleteflag=0))
order by id'
where queryLabel = 'calendar'


text:
Vim
===
__[Vim]__ is a modal text editor and my text editor of choice. __[NeoVim]__ is
an alternative to watch.

Structure
---------
The configuration directory for __Vim__ has a specific structure. In general,
any file with extension `.vim` may be dropped into [`config.d`][config.d] and it
will be automatically sourced, but I've developed a structure to keep things
organized and help ensure order sensitivity is respected.

    vim/
    ├── README.md
    ├── config.d
    │   ├── 00-core.vim
    │   ├── 10-functions.vim
    │   ├── 30-behavior.vim
    │   ├── 40-appearance.vim
    │   ├── 50-plugin.d
    │   │   └── plugin-name.vim
    │   ├── 80-keybindings.vim
    │   └── 90-miscellaneous.vim
    ├── vimfiles
    │   └── ftplugin
    │       └── filetype.vim
    └── vimrc

### vimrc ###
[`vimrc`][vimrc] is kept very simple, containing only a block used to source
everything in `config.d`.

### config.d ###
[`config.d`][config.d] is a directory where almost all user specified settings
are stored. The structure is quite specific and order sensitive. Each file or
directory directly under `config.d` is prefixed with a two digit number; this
allows for the prioritization of sourcing files and directories. Each block of
10 numbers is allocated to a specific function, described in the key below.

    00-09  Core           Important bootstrapping scripts
    10-19  Functions      User written functions required elsewhere
    30-39  Behavior       Vim settings that affect its behaviour
    40-39  Appearance     Vim settings that affect its appearance
    50-59  Plugins        Plugin settings
    80-89  Keybindings    Keybindings
    90-99  Miscellaneous  Anything that doesn't fit elsewhere

[`50-plugin.d`][50-plugin.d] lives inside `config.d` and is where plugin
specific settings are stored. The files in `50-plugin.d` follow the filename
format `plugin-name.vim`, where `plugin-name` is the name of the plugin whose
settings the file contains. Plugins should be orthogonal; the settings in these
files shouldn't have external dependencies, therefore it shouldn't become
necessary to prefix them with numbers.

### vimfiles/ftplugin ###
[`vimfiles`][vimfiles] currently serves only as the parent directory to
[`ftplugin`][ftplugin], where filetype specific settings can be found. The files
in `ftplugin` follow the filename format `filetype.vim`, where `filetype` is the
the name of the language whose settings the file contains. For example,
`python.vim` would be the name of the file used for `python` specific settings.
This avoids cluttering `vimrc`, or files it sources, with lines like `autocmd
FileType python set sw=4`. Placing those settings in their respective
`filetype.vim` files instead allows writing settings like `set sw=4` and lets
__Vim__ take care of enabling those settings on files of the specific type.

Further reading
---------------
- [Vim]     - The homepage
- [usevim]  - Useful resource
- [NeoVim]  - Alternative modal text editor

[Vim]: http://www.vim.org/ "Vim"
[NeoVim]: https://neovim.org/ "NeoVim"
[usevim]: http://usevim.com/ "usevim"

[vimrc]: vimrc "vimrc"
[config.d]: config.d/ "config.d"
[50-plugin.d]: config.d/50-plugin.d/ "50-plugin.d"
[vimfiles]: vimfiles/ "vimfiles"
[ftplugin]: vimfiles/ftplugin/ "ftplugin"


text:
namespace MassTransit.Context
{
    using System;

    public class BusObjectPublisherImpl<TMessage> :
        BusObjectPublisher
        where TMessage : class
    {
        public void Publish(IServiceBus bus, object message)
        {
            var msg = message as TMessage;
            bus.Publish(msg);
        }

        public void Publish(IServiceBus bus, object message, Action<IPublishContext> contextCallback)
        {
            var msg = message as TMessage;
            bus.Publish(msg, context => contextCallback(context));
        }
    }
}


text:
                            campo
                            valor

id	{{bean.id}}

titulo	{{bean.titulo}}

descripcion	{{bean.descripcion| clipString}}

fecha_subida	{{bean.fecha_subida}}

fecha_modificacion	{{bean.fecha_modificacion}}

visitas	{{bean.visitas}}

valoracion	{{bean.valoracion}}

destacado	{{bean.destacado}}

                            usuario

                                {{bean.obj_usuario.login}}

¿Está seguro de que desea borrar el registro?

                    Si
                    No

No se ha podido eliminar el registro

Se ha eliminado el registro

                Volver

Error al eliminar el registro


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.compute.models;

import com.azure.core.util.ExpandableStringEnum;
import com.fasterxml.jackson.annotation.JsonCreator;
import java.util.Collection;

/** Defines values for ExpandTypesForGetVMScaleSets. */
public final class ExpandTypesForGetVMScaleSets extends ExpandableStringEnum<ExpandTypesForGetVMScaleSets> {
    /** Static value userData for ExpandTypesForGetVMScaleSets. */
    public static final ExpandTypesForGetVMScaleSets USER_DATA = fromString("userData");

    /**
     * Creates or finds a ExpandTypesForGetVMScaleSets from its string representation.
     *
     * @param name a name to look for.
     * @return the corresponding ExpandTypesForGetVMScaleSets.
     */
    @JsonCreator
    public static ExpandTypesForGetVMScaleSets fromString(String name) {
        return fromString(name, ExpandTypesForGetVMScaleSets.class);
    }

    /**
     * Gets known ExpandTypesForGetVMScaleSets values.
     *
     * @return known ExpandTypesForGetVMScaleSets values.
     */
    public static Collection<ExpandTypesForGetVMScaleSets> values() {
        return values(ExpandTypesForGetVMScaleSets.class);
    }
}


text:
package com.github.proglottis.ladders;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;

import java.util.UUID;

import butterknife.Bind;
import butterknife.ButterKnife;

public class LoginActivity extends AppCompatActivity implements View.OnClickListener {
    @Bind(R.id.google_btn) Button googleBtn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);

        googleBtn.setOnClickListener(this);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_login, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onClick(View view) {
        switch(view.getId()){
        case R.id.google_btn:
            startGoogleAuth();
            break;
        }
    }

    private void startGoogleAuth() {
        String state = UUID.randomUUID().toString();
        String url = getString(R.string.google_base_uri)
                + "?access_type=offline"
                + "&client_id="
                + getString(R.string.google_client_id)
                + "&redirect_uri="
                + getString(R.string.google_redirect_uri)
                + "&response_type=code"
                + "&scope="
                + getString(R.string.google_scope)
                + "&state="
                + state;

        Intent intent = new Intent(this, AuthActivity.class);
        intent.putExtra(AuthActivity.AUTH_URL, url);
        intent.putExtra(AuthActivity.AUTH_STATE, state);
        startActivity(intent);
    }
}


text:
 /*-----------*\
/*    RESET   	\___________________________________________________ */

html, body, div, span, applet, object, iframe,h1, h2, h3, h4, h5, h6, p, blockquote, pre,a, abbr, acronym, address, big, cite, code,del, dfn, em, img, ins, kbd, q, s, samp,small, strike, strong, sub, sup, tt, var,b, u, i, center,dl, dt, dd, ol, ul, li,fieldset, form, label, legend,table, caption, tbody, tfoot, thead, tr, th, td,article, aside, canvas, details, embed, figure, figcaption, footer, header, hgroup, menu, nav, output, ruby, section, summary,time, mark, audio, video {margin: 0;padding: 0;border: 0;font-size: 100%;font: inherit;vertical-align: baseline;}
article, aside, details, figcaption, figure, footer, header, hgroup, menu, nav, section {display: block;}
body {line-height: 1;}
ol, ul {list-style: none;}
blockquote, q {quotes: none;}
blockquote:before, blockquote:after,q:before, q:after {content: '';content: none;}
table {border-collapse: collapse;border-spacing: 0;}

* 										{ -webkit-tap-highlight-color: rgba(0,0,0,0); box-sizing: border-box; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; -o-box-sizing: border-box; -ms-box-sizing: border-box; }

.input-box 								{ background: #7F8C8D; padding: 18px; }
.output 				{ text-align:center; width: 50%; margin: 0 auto; height: 48px; border: none; padding: 0 15px; font: 400 16px/48px 'Open Sans',sans-serif; color: #ffffff; background: rgba(0,0,0,.45);  }

 /*-----------*\
/*    SLIDER   	\___________________________________________________ */

span.slider-tut 						{ width: 100%; display: block; text-align: center; font: 400 10px/16px 'Open Sans',sans-serif; color: #ffffff; margin-bottom: -10px; margin-top: 14px; }

.slider,
.grip,
.grip-ridges,
.grip-ridges li,
.track,
.track-division 						{ -moz-user-select: none; -webkit-user-select: none; -ms-user-select: none; -o-user-select: none; user-select: none; }

.slider 								{ background: #95A5A6; width: 100%; height: 52px; position: relative; overflow: hidden; }
.grip 									{ z-index: 9; height: 52px; background: #c0392b; background: -moz-linear-gradient(left, #c0392b 0%, #c0392b 50%, #e74c3c 51%, #e74c3c 100%); background: -webkit-gradient(linear, left top, right top, color-stop(0%,#c0392b), color-stop(50%,#c0392b), color-stop(51%,#e74c3c), color-stop(100%,#e74c3c)); background: -webkit-linear-gradient(left, #c0392b 0%,#c0392b 50%,#e74c3c 51%,#e74c3c 100%); background: -o-linear-gradient(left, #c0392b 0%,#c0392b 50%,#e74c3c 51%,#e74c3c 100%); background: -ms-linear-gradient(left, #c0392b 0%,#c0392b 50%,#e74c3c 51%,#e74c3c 100%); background: linear-gradient(to right, #c0392b 0%,#c0392b 50%,#e74c3c 51%,#e74c3c 100%); filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#c0392b', endColorstr='#e74c3c',GradientType=1 ); position: absolute; cursor: pointer; left: 0; }

.grip:before 							{ z-index: 3; content: ''; height: 0; position: absolute; width: 0; border: 10px solid transparent; border-left-color: #e74c3c; right: -20px; top: 50%; margin-top: -10px; }
.grip:after 							{ z-index: 3; content: ''; height: 0; position: absolute; width: 0; border: 10px solid transparent; border-right-color: #c0392b; left: -20px; top: 50%; margin-top: -10px; }

.grip-ridges 							{ width: 30px; height: 60%; position: relative; top: 20%; left: 50%; margin-left: -15px; overflow: hidden; }
.grip-ridges li 						{ width: 4px; height: 100%; margin: 0 3px; background: #A11F13; float: left; }

.track 									{ overflow: hidden; height: 100%; }
.track-division 						{ float: left; height: 100%;  border-right: 1px solid #7F8C8D; }
.track-division:first-child 			{ border-left: none; }


text:
```
src/
    Main.elm   # main
    Mockup.elm # another main
    ViewingGame.elm # the third main (static game views)

    Util.elm

    Game.elm        # bloaty game view: refactor to smaller modules.
    Lounge.elm      # Lounge view
    MsgDialog       # a component
    View.elm        # some general shit that should be in different, better-named modules

    # communication with hajong-server
    GameTypes.elm
    Events.elm
    JSON.elm

    # communication with hajong-site
    PlayerInfo.elm

```


text:
#ifndef _Subsys_Explode_h
#define _Subsys_Explode_h

// Subsys_Explode.h
//------------------------------------------
// synopsis:
// ...
//
// description:
// ...
//------------------------------------------
// Restrictions:
// ...
//------------------------------------------

#ifndef prototypes_h
#include "prototypes.h"
#endif

#include <gtDlgTemplate.h>
#include <gtToggleBox.h>
#include "oodt_ui_decls.h"

BEGIN_C_DECL
void popup_Subsys_explode PROTO((void *, void *));
END_C_DECL

class Subsys_Explode {
    gtToggleBox		*group1;
    void		*popnode, *viewp;

  public:
    gtDialogTemplate	*shell;
    Subsys_Explode();
    void init_fields(void *, void *);
    void do_it();
    static void OK_CB(gtPushButton *, gtEvent *, void *cd, gtReason);
    static void Apply_CB(gtPushButton *, gtEvent *, void *cd, gtReason);
    static void Cancel_CB(gtPushButton *, gtEvent *, void *cd, gtReason);
};

typedef Subsys_Explode* Subsys_Explode_Ptr;

#endif // _Browser_Explode_h

/*
    START-LOG-------------------------------

    $Log: Subsys_Explode.h  $
    Revision 1.2 1995/07/27 20:35:34EDT rajan
    Port
 * Revision 1.2.1.2  1992/10/09  19:56:21  kws
 * Fix comments
 *

    END-LOG---------------------------------
*/


text:
<?php
/**
 * Created by PhpStorm.
 * User: leelam
 * Date: 13/5/16
 * Time: 8:43 PM
 */

namespace Leelam\PaymentGateway;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class CashTransaction extends Model
{
    use SoftDeletes;

    public $table = 'leelam_cash';

    protected $dates = ['deleted_at'];

    protected $fillable = [
        'transaction_id',
        'cashable_id',
        'cashable_type',
        'amount',
        'response_data',
        'status',
        'service_provider',
        'ip',
        'user_id'
    ];

    /**
     *
     * @return mixed
     *
     */
    public function cashable()
    {
        return $this->morphTo();
    }

    /**
     *  The persion who has made the transaction
     *
     * @return mixed
     */
    public function user ()
    {
        return $this->hasOne ( User::class, 'id', 'user_id' );
    }

}


text:
layout: post
title: "Circle of Power"
date: 2015-07-14
tags: [paladin, level5, abjuration]
---

**5th-level abjuration**

**Casting Time**: 1 action

**Range**: Self (30-foot radius)

**Components**: V

**Duration**: Concentration, up to 10 minutes

Divine energy radiates from you, distorting and diffusing magical energy within 30 feet of you. Until the spell ends, the sphere moves with you, centered on you. For the duration, each friendly creature in the area (including you) has advantage on saving throws against spells and other magical effects. Additionally, when an affected creature succeeds on a saving throw made against a spell or magical effect that allows it to make a saving throw to take only half damage, it instead takes no damage if it succeeds on the saving throw.


text:
"""Unittest for block_disk.py module."""

__pychecker__ = 'no-local'  # for unittest

from contextlib import closing
import json
import logging
import os
import random
import subprocess
import tarfile
import tempfile
import unittest
import urllib2

from gcimagebundlelib import block_disk
from gcimagebundlelib import exclude_spec
from gcimagebundlelib.tests import image_bundle_test_base
from gcimagebundlelib import utils

class FsRawDiskTest(image_bundle_test_base.ImageBundleTest):
  """FsRawDisk Unit Test."""

  _MEGABYTE = 1024*1024
  _GIGABYTE = 1024*_MEGABYTE

  def setUp(self):
    super(FsRawDiskTest, self).setUp()
    self._fs_size = 10* FsRawDiskTest._MEGABYTE
    self._bundle = block_disk.FsRawDisk(self._fs_size, 'ext4')
    self._tar_path = self.tmp_path + '/image.tar.gz'
    self._bundle.SetTarfile(self._tar_path)
    self._bundle.AppendExcludes([exclude_spec.ExcludeSpec(self._tar_path)])
    self._bundle.SetKey('key')
    self._bundle._SetManifest(self._manifest)

  def _SetupMbrDisk(self, partition_start, partition_end, fs_uuid):
    """Creates a disk with a fake MBR.

    Args:
      partition_start: The byte offset where the partition starts.
      partition_end: The byte offset where the partition ends.
      fs_uuid: The UUID of the filesystem to create on the partition.

    Returns:
      The path where the disk is located.
    """
    # Create the disk file with the size specified.
    disk_path = os.path.join(self.tmp_root, 'mbrdisk.raw')
    disk_size = partition_end + FsRawDiskTest._MEGABYTE
    with open(disk_path, 'wb') as disk_file:
      disk_file.truncate(disk_size)

    # Create a partition table
    utils.MakePartitionTable(disk_path)

    # Create the partition
    utils.MakePartition(disk_path, 'primary', 'ext2',
                        partition_start, partition_end)

    # Create the file system
    with utils.LoadDiskImage(disk_path) as devices:
      utils.MakeFileSystem(devices[0], 'ext4', fs_uuid)

    # Write some data after the MBR but before the first partition
    with open(disk_path, 'r+b') as disk_file:
      # Seek to last two bytes of first sector
      disk_file.seek(510)
      # Write MBR signature
      disk_file.write(chr(0x55))
      disk_file.write(chr(0xAA))
      # Write random data on the disk till the point first partition starts
      for _ in range(partition_start - 512):
        # Write a byte
        disk_file.write(chr(random.randint(0, 127)))

    return disk_path

  def tearDown(self):
    super(FsRawDiskTest, self).tearDown()

  def testDiskBundle(self):
    """Tests bundle command when a disk is specified.

    Creates a 20Gb source disk to start with and verifies that creating
    a 10MB file off it works.
    """
    # Create a 20GB disk with first partition starting at 1MB
    self._TestDiskBundleHelper(FsRawDiskTest._MEGABYTE,
                               FsRawDiskTest._GIGABYTE*20,
                               utils.RunCommand(['uuidgen']).strip())

  def testDiskBundlePartitionAt2MB(self):
    """Tests bundle command when a disk is specified.

    Creates the first partition at 2MB and verifies all data prior to that is
    copied.
    """
    # Create a 20GB disk with first partition starting at 2MB
    self._TestDiskBundleHelper(FsRawDiskTest._MEGABYTE*2,
                               FsRawDiskTest._GIGABYTE*20,
                               utils.RunCommand(['uuidgen']).strip())

  def _TestDiskBundleHelper(self, partition_start, partition_end, fs_uuid):
    disk_path = self._SetupMbrDisk(partition_start, partition_end, fs_uuid)

    with utils.LoadDiskImage(disk_path) as devices:
      # Get the path to do the disk.
      # devices will have something which is like /dev/mapper/loop0p1
      # We need to get loop0 out of it.
      disk_loop_back_path = '/dev/' + devices[0].split('/')[3][:-2]

      # Create a symlinks to the disk and loopback paths
      # This is required because of the code where we assume first
      # partition is device path appended by 1. Will remove it once we
      # update that part of the code.
      symlink_disk = os.path.join(self.tmp_root, 'disk')
      symlink_partition = self.tmp_root + '/disk1'
      utils.RunCommand(['ln', '-s', disk_loop_back_path, symlink_disk])
      utils.RunCommand(['ln', '-s', devices[0], symlink_partition])

      # Bundle up
      self._bundle.AddDisk(symlink_disk)
      self._bundle.AddSource(self.tmp_path)
      self._bundle.Verify()
      (_, _) = self._bundle.Bundleup()
    self._VerifyImageHas(self._tar_path,
                         ['lost+found', 'test1', 'test2', 'dir1/',
                          '/dir1/dir11/', '/dir1/sl1', '/dir1/hl2', 'dir2/',
                          '/dir2/dir1', '/dir2/sl2', '/dir2/hl1'])
    self._VerifyNumberOfHardLinksInRawDisk(self._tar_path, 'test1', 2)
    self._VerifyNumberOfHardLinksInRawDisk(self._tar_path, 'test2', 2)
    self._VerifyDiskSize(self._tar_path, self._fs_size)
    self._VerifyNonPartitionContents(self._tar_path,
                                     disk_path,
                                     partition_start)
    self._VerifyFilesystemUUID(self._tar_path, fs_uuid)

  def testRawDisk(self):
    """Tests the regular operation. No expected error."""
    self._bundle.AddSource(self.tmp_path)
    self._bundle.Verify()
    (_, digest) = self._bundle.Bundleup()
    if not digest:
      self.fail('raw disk failed')
    self._VerifyTarHas(self._tar_path, ['disk.raw'])
    self._VerifyImageHas(self._tar_path,
                         ['lost+found', 'test1', 'test2', 'dir1/',
                          '/dir1/dir11/', '/dir1/sl1', '/dir1/hl2', 'dir2/',
                          '/dir2/dir1', '/dir2/sl2', '/dir2/hl1'])
    self._VerifyNumberOfHardLinksInRawDisk(self._tar_path, 'test1', 2)
    self._VerifyNumberOfHardLinksInRawDisk(self._tar_path, 'test2', 2)

  def testRawDiskIgnoresHardlinks(self):
    """Tests if the raw disk ignores hard links if asked."""
    self._bundle.AddSource(self.tmp_path)
    self._bundle.IgnoreHardLinks()
    self._bundle.Verify()
    (_, digest) = self._bundle.Bundleup()
    if not digest:
      self.fail('raw disk failed')
    self._VerifyTarHas(self._tar_path, ['disk.raw'])
    self._VerifyImageHas(self._tar_path,
                         ['lost+found', 'test1', 'test2', 'dir1/',
                          '/dir1/dir11/', '/dir1/sl1', '/dir1/hl2', 'dir2/',
                          '/dir2/dir1', '/dir2/sl2', '/dir2/hl1'])
    self._VerifyNumberOfHardLinksInRawDisk(self._tar_path, 'test1', 1)
    self._VerifyNumberOfHardLinksInRawDisk(self._tar_path, 'test2', 1)

  def testRawDiskIgnoresExcludes(self):
    """Tests if the raw disk ignores specified excludes files."""
    self._bundle.AddSource(self.tmp_path)
    self._bundle.AppendExcludes(
        [exclude_spec.ExcludeSpec(self.tmp_path + '/dir1')])
    self._bundle.Verify()
    (_, digest) = self._bundle.Bundleup()
    if not digest:
      self.fail('raw disk failed')
    self._VerifyTarHas(self._tar_path, ['disk.raw'])
    self._VerifyImageHas(self._tar_path,
                         ['lost+found', 'test1', 'test2', 'dir2/', '/dir2/dir1',
                          '/dir2/sl2', '/dir2/hl1'])

  def testRawDiskExcludePreservesSubdirs(self):
    """Tests if excludes preserves subdirs underneath if asked."""
    self._bundle.AddSource(self.tmp_path)
    self._bundle.AppendExcludes(
        [exclude_spec.ExcludeSpec(self.tmp_path + '/dir1',
                                  preserve_dir=True,
                                  preserve_subdir=True)])
    self._bundle.Verify()
    (_, digest) = self._bundle.Bundleup()
    if not digest:
      self.fail('raw disk failed')
    self._VerifyTarHas(self._tar_path, ['disk.raw'])
    self._VerifyImageHas(self._tar_path,
                         ['lost+found', 'test1', 'test2', 'dir1/',
                          '/dir1/dir11', 'dir2/', '/dir2/dir1',
                          '/dir2/sl2', '/dir2/hl1'])

  def testRawDiskExcludePreservesFiles(self):
    """Tests if excludes preserves the files underneath if asked."""
    self._bundle.AddSource(self.tmp_path)
    self._bundle.AppendExcludes(
        [exclude_spec.ExcludeSpec(self.tmp_path + '/dir1',
                                  preserve_dir=True,
                                  preserve_file=True)])
    self._bundle.Verify()
    (_, digest) = self._bundle.Bundleup()
    if not digest:
      self.fail('raw disk failed')
    self._VerifyTarHas(self._tar_path, ['disk.raw'])
    self._VerifyImageHas(self._tar_path,
                         ['lost+found', 'test1', 'test2', 'dir1/', '/dir1/hl2',
                          '/dir1/sl1', 'dir2/', '/dir2/dir1', '/dir2/sl2',
                          '/dir2/hl1'])

  def testRawDiskUsesModifiedFiles(self):
    """Tests if the raw disk uses modified files."""
    self._bundle.AddSource(self.tmp_path)
    self._bundle.AppendExcludes(
        [exclude_spec.ExcludeSpec(self.tmp_path + '/dir1')])
    self._bundle.SetPlatform(image_bundle_test_base.MockPlatform(self.tmp_root))
    self._bundle.Verify()
    (_, digest) = self._bundle.Bundleup()
    if not digest:
      self.fail('raw disk failed')
    self._VerifyTarHas(self._tar_path, ['disk.raw'])
    self._VerifyImageHas(self._tar_path,
                         ['lost+found', 'test1', 'test2', 'dir2/',
                          '/dir2/dir1', '/dir2/sl2', '/dir2/hl1'])
    self._VerifyFileInRawDiskEndsWith(self._tar_path, 'test1',
                                      'something extra.')

  def testRawDiskGeneratesCorrectDigest(self):
    """Tests if the SHA1 digest generated is accurate."""
    self._bundle.AddSource(self.tmp_path)
    self._bundle.Verify()
    (_, digest) = self._bundle.Bundleup()
    if not digest:
      self.fail('raw disk failed')
    p = subprocess.Popen(['/usr/bin/openssl dgst -sha1 ' + self._tar_path],
                         stdout=subprocess.PIPE, shell=True)
    file_digest = p.communicate()[0].split('=')[1].strip()
    self.assertEqual(digest, file_digest)

  def testRawDiskHonorsRecursiveOff(self):
    """Tests if raw disk handles recursive off."""
    self._bundle.AppendExcludes([exclude_spec.ExcludeSpec(self._tar_path)])
    self._bundle.AddSource(self.tmp_path + '/dir1',
                           arcname='dir1', recursive=False)
    self._bundle.AddSource(self.tmp_path + '/dir2', arcname='dir2')
    self._bundle.Verify()
    (_, digest) = self._bundle.Bundleup()
    if not digest:
      self.fail('raw disk failed')
    self._VerifyTarHas(self._tar_path, ['disk.raw'])
    self._VerifyImageHas(self._tar_path,
                         ['lost+found', 'dir1/', 'dir2/', '/dir2/dir1',
                          '/dir2/sl2', '/dir2/hl1'])

  def testSkipLicenseCheckIfNotOnGCE(self):
    """Tests that no licenses are loaded if gcimagebundle is not run on GCE."""
    class MockHttp(utils.Http):
      def Get(self, request, timeout=None):
        # if gcimagebundle is not run on GCE the metadata server will be unreachable
        raise urllib2.URLError("urlopen error timed out")

    self._http = MockHttp()
    self._manifest._http = self._http
    self._manifest._is_gce_instance = False

    self._bundle.AddSource(self.tmp_path)
    self._bundle.Verify()
    _ = self._bundle.Bundleup()
    self.assertFalse(self._bundle._manifest._IsManifestNeeded())
    self._VerifyTarHas(self._tar_path, ['disk.raw'])

  def testNoManifestCreatedWithZeroLicenses(self):
    """Tests that no manifest is created when there are 0 licenses."""
    self._bundle.AddSource(self.tmp_path)
    self._bundle.Verify()
    _ = self._bundle.Bundleup()
    self.assertFalse(self._bundle._manifest._IsManifestNeeded())
    self._VerifyTarHas(self._tar_path, ['disk.raw'])

  def testManifestWithOneLicense(self):
    """Tests manifest is populated with 1 license."""
    self._http._instance_response = ('{"hostname":"test",'
                                     '"licenses":[{"id":"TEST-LICENSE"}]}')
    self._bundle.AddSource(self.tmp_path)
    self._bundle.Verify()
    _ = self._bundle.Bundleup()
    manifest_json = self._bundle._manifest._ToJson()
    manifest_obj = json.loads(manifest_json)
    self.assertTrue(self._bundle._manifest._IsManifestNeeded())
    self.assertEqual(1, len(manifest_obj['licenses']))
    self.assertEqual('TEST-LICENSE', manifest_obj['licenses'][0])
    self._VerifyTarHas(self._tar_path, ['manifest.json', 'disk.raw'])
    self._VerifyFileContentsInTarball(self._tar_path,
                                      'manifest.json',
                                      '{"licenses": ["TEST-LICENSE"]}')

  def testManifestWithTwoLicenses(self):
    """Tests manifest is populated with 2 licenses."""
    self._http._instance_response = ('{"hostname":"test",'
                                     '"licenses":[{"id":"TEST-1"},'
                                     '{"id":"TEST-2"}]}')
    self._bundle.AddSource(self.tmp_path)
    self._bundle.Verify()
    _ = self._bundle.Bundleup()
    manifest_json = self._bundle._manifest._ToJson()
    manifest_obj = json.loads(manifest_json)
    self.assertTrue(self._bundle._manifest._IsManifestNeeded())
    self.assertEqual(2, len(manifest_obj['licenses']))
    self.assertEqual('TEST-1', manifest_obj['licenses'][0])
    self.assertEqual('TEST-2', manifest_obj['licenses'][1])
    self._VerifyTarHas(self._tar_path, ['manifest.json', 'disk.raw'])
    self._VerifyFileContentsInTarball(self._tar_path,
                                      'manifest.json',
                                      '{"licenses": ["TEST-1", "TEST-2"]}')

  def _VerifyFilesystemUUID(self, tar, expected_uuid):
    """Verifies UUID of the first partition on disk matches the value."""
    tmp_dir = tempfile.mkdtemp(dir=self.tmp_root)
    tar_cmd = ['tar', '-xzf', tar, '-C', tmp_dir]
    self.assertEqual(subprocess.call(tar_cmd), 0)

    created_disk_path = os.path.join(tmp_dir, 'disk.raw')
    with utils.LoadDiskImage(created_disk_path) as devices:
      self.assertEqual(1, len(devices))
      self.assertEqual(expected_uuid, utils.GetUUID(devices[0]))

  def _VerifyNonPartitionContents(self, tar, disk_path, partition_start):
    """Verifies that bytes outside the partition are preserved."""
    tmp_dir = tempfile.mkdtemp(dir=self.tmp_root)
    tar_cmd = ['tar', '-xzf', tar, '-C', tmp_dir]
    self.assertEqual(subprocess.call(tar_cmd), 0)
    created_disk_path = os.path.join(tmp_dir, 'disk.raw')

    # Verify first parition in both disks starts at the same offset
    self.assertEqual(partition_start,
                     utils.GetPartitionStart(disk_path, 1))
    self.assertEqual(partition_start,
                     utils.GetPartitionStart(created_disk_path, 1))
    with open(disk_path, 'r') as source_file:
      with open(created_disk_path, 'r') as created_file:
        # Seek to 510'th byte in both streams and verify rest of the
        # bytes until the partition start are the same
        source_file.seek(510)
        created_file.seek(510)
        for i in range(partition_start - 510):
          self.assertEqual(source_file.read(1),
                           created_file.read(1),
                           'byte at position %s not equal' % (i + 510))

  def _VerifyDiskSize(self, tar, expected_size):
    """Verifies that the disk file has the same size as expected."""
    tmp_dir = tempfile.mkdtemp(dir=self.tmp_root)
    tar_cmd = ['tar', '-xzf', tar, '-C', tmp_dir]
    self.assertEqual(subprocess.call(tar_cmd), 0)
    disk_path = os.path.join(tmp_dir, 'disk.raw')
    statinfo = os.stat(disk_path)
    self.assertEqual(expected_size, statinfo.st_size)

  def _VerifyImageHas(self, tar, expected):
    """Tests if raw disk contains an expected list of files/directories."""
    tmp_dir = tempfile.mkdtemp(dir=self.tmp_root)
    tar_cmd = ['tar', '-xzf', tar, '-C', tmp_dir]
    self.assertEqual(subprocess.call(tar_cmd), 0)
    disk_path = os.path.join(tmp_dir, 'disk.raw')
    with utils.LoadDiskImage(disk_path) as devices:
      self.assertEqual(len(devices), 1)
      mnt_dir = tempfile.mkdtemp(dir=self.tmp_root)
      with utils.MountFileSystem(devices[0], mnt_dir, 'ext4'):
        found = []
        for root, dirs, files in os.walk(mnt_dir):
          root = root.replace(mnt_dir, '')
          for f in files:
            found.append(os.path.join(root, f))
          for d in dirs:
            found.append(os.path.join(root, d))
    self._AssertListEqual(expected, found)

  def _VerifyFileContentsInTarball(self, tar, file_name, expected_content):
    """Reads the file from the tar file and turns it."""
    with closing(tarfile.open(tar)) as tar_file:
      content = tar_file.extractfile(file_name).read()
      self.assertEqual(content, expected_content)

  def _VerifyFileInRawDiskEndsWith(self, tar, filename, text):
    """Tests if a file on raw disk contains ends with a specified text."""
    tmp_dir = tempfile.mkdtemp(dir=self.tmp_root)
    tar_cmd = ['tar', '-xzf', tar, '-C', tmp_dir]
    self.assertEqual(subprocess.call(tar_cmd), 0)
    disk_path = os.path.join(tmp_dir, 'disk.raw')
    with utils.LoadDiskImage(disk_path) as devices:
      self.assertEqual(len(devices), 1)
      mnt_dir = tempfile.mkdtemp(dir=self.tmp_root)
      with utils.MountFileSystem(devices[0], mnt_dir, 'ext4'):
        f = open(os.path.join(mnt_dir, filename), 'r')
        file_content = f.read()
        f.close()
        self.assertTrue(file_content.endswith(text))

  def _VerifyNumberOfHardLinksInRawDisk(self, tar, filename, count):
    """Tests if a file on raw disk has a specified number of hard links."""
    tmp_dir = tempfile.mkdtemp(dir=self.tmp_root)
    tar_cmd = ['tar', '-xzf', tar, '-C', tmp_dir]
    self.assertEqual(subprocess.call(tar_cmd), 0)
    disk_path = os.path.join(tmp_dir, 'disk.raw')
    with utils.LoadDiskImage(disk_path) as devices:
      self.assertEqual(len(devices), 1)
      mnt_dir = tempfile.mkdtemp(dir=self.tmp_root)
      with utils.MountFileSystem(devices[0], mnt_dir, 'ext4'):
        self.assertEqual(os.stat(os.path.join(mnt_dir, filename)).st_nlink,
                         count)

class RootFsRawTest(image_bundle_test_base.ImageBundleTest):
  """RootFsRaw Unit Test."""

  def setUp(self):
    super(RootFsRawTest, self).setUp()
    self._bundle = block_disk.RootFsRaw(
        10*1024*1024, 'ext4', False, self._MockStatvfs)
    self._tar_path = self.tmp_path + '/image.tar.gz'
    self._bundle.SetTarfile(self._tar_path)
    self._bundle.AppendExcludes([exclude_spec.ExcludeSpec(self._tar_path)])
    self._bundle._SetManifest(self._manifest)

  def tearDown(self):
    super(RootFsRawTest, self).tearDown()

  def testRootRawDiskVerifiesOneSource(self):
    """Tests that only one root directory is allowed."""
    self._bundle.AddSource(self.tmp_path)
    self._bundle.AddSource(self.tmp_path + '/dir1')
    self._bundle.SetKey('key')
    try:
      self._bundle.Verify()
    except block_disk.InvalidRawDiskError:
      return
    self.fail()

  def testRootRawDiskVerifiesRootDestination(self):
    """Tests that destination directory must be /."""
    self._bundle.AddSource(self.tmp_path, arcname='/tmp')
    self._bundle.SetKey('key')
    try:
      self._bundle.Verify()
    except block_disk.InvalidRawDiskError:
      return
    self.fail()

  def testRootRawDiskNotEnoughFreeSpace(self):
    """Tests that there is not enough disk space to complete the operation."""
    self._statvfs_map = {
      "/" : image_bundle_test_base.StatvfsResult(1024, 500, 100),
      "/tmp" : image_bundle_test_base.StatvfsResult(1024, 500, 100)
      }
    self._bundle.AddSource("/")
    self._bundle.SetKey('key')
    try:
      self._bundle.Verify()
    except block_disk.InvalidRawDiskError as e:
      print str(e)
      return
    self.fail()

  def testRootFilesExceedDiskSize(self):
    """Tests that source files may exceed the raw disk file size limit."""
    self._statvfs_map = {
      "/" : image_bundle_test_base.StatvfsResult(1024, 50000, 20000),
      "/tmp" : image_bundle_test_base.StatvfsResult(1024, 100000, 90000)
      }
    self._bundle.AddSource("/")
    self._bundle.SetKey('key')
    try:
      self._bundle.Verify()
    except block_disk.InvalidRawDiskError as e:
      print str(e)
      return
    self.fail()

  def _MockStatvfs(self, file_path):
      return self._statvfs_map[file_path]

def main():
  logging.basicConfig(level=logging.DEBUG)
  unittest.main()

if __name__ == '__main__':
  main()


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>Uses of Package com.googlecode.concurrenttrees.radixreversed (Concurrent-Trees 2.4.0 API)</title>
<meta name="date" content="2013-12-03">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Package
com.googlecode.concurrenttrees.radixreversed

Packages that use com.googlecode.concurrenttrees.radixreversed

Package
Description

com.googlecode.concurrenttrees.radixreversed

Classes in com.googlecode.concurrenttrees.radixreversed used by com.googlecode.concurrenttrees.radixreversed

Class and Description

ReversedRadixTree

API of a reversed radix tree, that is a tree which allows values to be looked up based on suffixes of the keys
 with which they were associated, as well as based on exact matches for keys.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Copyright © 2013. All Rights Reserved.


text:
"""Defines the toggleable explainable type"""
import hug

from hug_explainable.directive import Explainable

class ExplainableToggle(hug.types.SmartBoolean):
    """If set to True this endpoint will return explainations as well as profiling information."""

    def __call__(self, enabled):
        if isinstance(enabled, Explainable):
            return enabled
        return Explainable(enabled=super().__call__(enabled))

explainable_toggle = ExplainableToggle()


text:
/*
 Portions borrowed from the rusoto project. See README.md
*/

use aws::common::xmlutil::{XmlParseError, Peek, Next};
use aws::common::xmlutil::{characters, start_element, end_element, string_field, peek_at_name};
use aws::common::params::{Params, ServiceParams};

#[derive(Default, Debug)]
pub struct XmlError {
	pub error_type: String,
	pub code: String,
	pub message: String,
	pub detail: Option<String>
}

pub struct XmlErrorDeserializer;
impl XmlErrorDeserializer {
	pub fn deserialize<'a, T: Peek + Next>(tag_name: &str, stack: &mut T) -> Result<XmlError, XmlParseError> {
		try!(start_element(tag_name, stack));

		let mut obj = XmlError::default();

		loop {
			match &try!(peek_at_name(stack))[..] {
				"Type" => {
					obj.error_type = try!(string_field("Type", stack));
					continue;
				},
				"Code" => {
					obj.code = try!(string_field("Code", stack));
					continue;
				},
				"Message" => {
					obj.message = try!(string_field("Message", stack));
					continue;
				},
				"Detail" => {
					try!(start_element("Detail", stack));
					if let Ok(characters) = characters(stack){
						obj.detail = Some(characters.to_string());
						try!(end_element("Detail", stack));
					}
					continue;
				},
				_ => break
			}
		}

		try!(end_element(tag_name, stack));

		Ok(obj)
	}
}

pub type Errors = Vec<String>;

/// Parse `Errors` from XML
#[allow(dead_code)]
struct ErrorsParser;

impl ErrorsParser {
	#[allow(dead_code)]
	#[allow(unused_variables)]
    fn parse_xml<T: Peek + Next>(tag_name: &str, stack: &mut T) -> Result<Errors, XmlParseError> {
        let mut obj : Vec<String> = Vec::new();
        while try!(peek_at_name(stack)) == "Error" {
            obj.push(try!(ErrorsParser::parse_single_error(stack)));
        }
        Ok(obj)
    }

    fn parse_single_error<T: Peek + Next>(stack: &mut T) -> Result<String, XmlParseError> {
        // TODO: go back to try!

        match characters(stack) {
            Err(why) => Err(why),
            Ok(val) => Ok(val),
        }
    }
}

/// Write `Errors` contents to a `SignedRequest`
#[allow(dead_code)]
struct ErrorsWriter;

impl ErrorsWriter {
	#[allow(dead_code)]
    fn write_params(params: &mut Params, name: &str, obj: &Errors) {
        let mut index = 1;
        for element in obj.iter() {
            let key = &format!("{}.{}", name, index);
            ErrorsWriter::write_param(params, key, element);
            index += 1;
        }
    }

	#[allow(dead_code)]
    fn write_param(params: &mut Params, key: &str, value: &str) {
        params.put(key, value);
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
        <PreferenceCategory android:title="Settings">
                <CheckBoxPreference
                		android:title="Show notification bar"
                		android:defaultValue="true"
                		android:key="notificationBarCheckbox" />
                <CheckBoxPreference
                		android:title="Enable compass"
                		android:defaultValue="false"
                		android:summary="Experimental"
                		android:key="compassBox" />
        </PreferenceCategory>
</PreferenceScreen>


text:
/* tweet-bot.spec.js */

var TweetBot = require('../lib/tweet-bot.js');
var config = require('../config.json');

var tweetBot;

describe('tweetBot', function() {

    beforeEach(function () {
        tweetBot = new TweetBot(config);
    });

    it('should exists', function() {
        expect(tweetBot).toBeDefined();
    });

    it('should have OAuth credentials', function() {
        expect(tweetBot.config).toBeDefined();
    });

    it('should have consumer KEY', function() {
        expect(tweetBot.config.CONSUMER_KEY).toBeDefined();
    });

    it('should have consumer SECRET', function() {
        expect(tweetBot.config.CONSUMER_SECRET).toBeDefined();
    });

    it('should have access TOKEN', function() {
        expect(tweetBot.config.ACCESS_TOKEN).toBeDefined();
    });

    it('should have access TOKEN SECRET', function() {
        expect(tweetBot.config.ACCESS_TOKEN_SECRET).toBeDefined();
    });
});


text:
using System;
using NUnit.Framework.Interfaces;
using NUnit.Framework.Internal;

namespace NUnit.Framework
{
    /// <summary>
    /// Sets the current Culture for the duration of a test.
    /// <para>
    /// It may be specified at the level of a test or a fixture.
    /// The culture remains set until the test or fixture completes and is then reset to its original value.
    /// </para>
    /// </summary>
    /// <seealso cref="SetUICultureAttribute"/>
    [AttributeUsage(AttributeTargets.Class|AttributeTargets.Method|AttributeTargets.Assembly, AllowMultiple=false, Inherited=true)]
    public class SetCultureAttribute : PropertyAttribute, IApplyToContext
    {
        private string _culture;

        /// <summary>
        /// Construct given the name of a culture
        /// </summary>
        /// <param name="culture"></param>
        public SetCultureAttribute( string culture ) : base( PropertyNames.SetCulture, culture )
        {
            _culture = culture;
        }

        #region IApplyToContext Members

        void IApplyToContext.ApplyToContext(TestExecutionContext context)
        {
            context.CurrentCulture = new System.Globalization.CultureInfo(_culture, false);
        }

        #endregion
    }
}
#endif


text:
package com.javatoscala;

import static org.junit.Assert.assertEquals;

import org.junit.Test;

public class MultipleInheritanceTest {

	@Test
	public void testShoutingHai() {
		SayHiClass sayHiInstance = new SayHiClass();
		assertEquals("hi er i mean hai!", sayHiInstance.shout(sayHiInstance.sayHi("er i mean hai")));
	}

	public static class SayHiClass implements Shout, SayHi {}

	public static interface Shout {
		default public String shout(String something) {
			return something + "!";
		}
	}

	public static interface SayHi {
		default public String sayHi(String something) {
			return "hi " + something;
		}
	}

}


text:
class IpPoolName(object):
    """The IP Pool that you would like to send this email from."""

    def __init__(self, ip_pool_name=None):
        """Create a IpPoolName object

        :param ip_pool_name: The IP Pool that you would like to send this
                             email from.
        :type ip_pool_name: string, optional
        """
        self._ip_pool_name = None

        if ip_pool_name is not None:
            self.ip_pool_name = ip_pool_name

    @property
    def ip_pool_name(self):
        """The IP Pool that you would like to send this email from.

        :rtype: string
        """
        return self._ip_pool_name

    @ip_pool_name.setter
    def ip_pool_name(self, value):
        """The IP Pool that you would like to send this email from.

        :param value: The IP Pool that you would like to send this email from.
        :type value: string
        """
        self._ip_pool_name = value

    def get(self):
        """
        Get a JSON-ready representation of this IpPoolName.

        :returns: This IpPoolName, ready for use in a request body.
        :rtype: string
        """
        return self.ip_pool_name


text:
@interface AppDelegate()
- (void) launchPreferences:(id) sender ;
@end

SpecBegin(AppDelegateStatusMenuSpec)

describe(@"AppDelegate", ^{
  __block AppDelegate *delegate ;
  __block NSApplication *application;

  beforeEach(^{
    application = [NSApplication sharedApplication];
    [NSBundle loadNibNamed:@"MainMenu" owner:application];
    delegate = [application delegate] ;
  }) ;

  afterEach(^{
    [[NSStatusBar systemStatusBar] removeStatusItem:delegate.statusItem] ;
  }) ;

  describe(@"statusMenu", ^{
    __block NSMenu *statusMenu ;

    beforeEach(^{
      [delegate applicationDidFinishLaunching: nil] ;
      statusMenu = delegate.statusItem.menu ;
    }) ;
  }) ;

  describe(@"launchPreferences", ^{
    beforeEach(^{
      [delegate launchPreferences:nil] ;
    }) ;

    it(@"launches a preferences window", ^{
      expect(delegate.preferencesController).toNot.beNil() ;
    }) ;

    // can't get why I've got errors
    // expected: a kind of MASPreferencesWindowController,
    // got: an instance of MASPreferencesWindowController, which is not a kind of MASPreferencesWindowController
    pending(@"creates a MASPreferencesWindowController", ^{
      expect(delegate.preferencesController).to.beKindOf([MASPreferencesWindowController class]) ;
    }) ;

    // Same thing here
    pending(@"creates a preference window with e configuration view controller", ^{
      id viewController = ((MASPreferencesWindowController *) delegate.preferencesController).viewControllers ;

      expect(viewController[0]).to.beKindOf([ConfigurationPreferencesViewController class]) ;
    }) ;

    // Same thing here
    pending(@"creates a preference window with e configuration view controller", ^{
      id viewController = ((MASPreferencesWindowController *) delegate.preferencesController).viewControllers ;

      expect(viewController[1]).to.beKindOf([ProjectsPreferencesViewController class]) ;
    }) ;

    // Same thing here
    pending(@"creates a preference window with e configuration view controller", ^{
      id viewController = ((MASPreferencesWindowController *) delegate.preferencesController).viewControllers ;

      expect(viewController[2]).to.beKindOf([AdvancedPreferencesViewController class]) ;
    }) ;

    it(@"does not re-create the controller, it memoizes it", ^{
      id viewController = delegate.preferencesController ;

      [delegate launchPreferences:nil] ;

      expect(delegate.preferencesController).to.beIdenticalTo(viewController) ;
    }) ;
  }) ;
});
SpecEnd


text:
<?php
namespace IHorse\BackendBundle\Form;

use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class VeterinaryType extends AdminUserType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        parent::buildForm($builder, $options);
        $builder->add('clinic', 'json_clinic', array('required'=>true));
    }

    public function getName()
    {
        return 'veterinary';
    }

}


text:
cask "babeledit" do
  version "4.0.0"
  sha256 "884fff64931ab21956e4c24675c67005e2081a7bc9afea996a51fbd1d2967045"

  url "https://www.codeandweb.com/download/babeledit/#{version}/BabelEdit-#{version}.dmg"
  name "BabelEdit"
  desc "Translation editor"
  homepage "https://www.codeandweb.com/babeledit"

  livecheck do
    url "https://www.codeandweb.com/babeledit/download"
    regex(%r{babeledit/download/v?(\d+(?:\.\d+)+)/mac-64}i)
  end

  auto_updates true

  app "BabelEdit.app"

  zap trash: "~/Library/Preferences/de.code-and-web.BabelEdit.plist"
end


text:
/**
* Remove Linked List Elements.
* https://leetcode.com/problems/remove-linked-list-elements/
*
* Remove all elements from a linked list of integers that have value val.
*
* Example
* Given: 1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6, val = 6
* Return: 1 --> 2 --> 3 --> 4 --> 5
*/

#ifndef SOLUTIONS_LIST_REMOVE_LINKED_LIST_ELEMENTS_H_
#define SOLUTIONS_LIST_REMOVE_LINKED_LIST_ELEMENTS_H_

#include <utility>

#include "../util/util_common.h"

class RemoveLinkedListElements {
public:
  ListNode* removeElements(ListNode* head, int val);
};

#endif  // SOLUTIONS_LIST_REMOVE_LINKED_LIST_ELEMENTS_H_


text:
using BulletSharp;

namespace BulletSharpTest
{
    class DebugDrawTest2 : DebugDraw
    {
        DebugDrawModes _debugMode;

        public override DebugDrawModes DebugMode
        {
            get
            {
                return _debugMode;
            }
            set
            {
                _debugMode = value;
            }
        }

        public override void Draw3dText(ref Vector3 location, string textString)
        {
            throw new System.NotImplementedException();
        }

        public override void DrawContactPoint(ref Vector3 pointOnB, ref Vector3 normalOnB, float distance, int lifeTime, System.Drawing.Color color)
        {
            throw new System.NotImplementedException();
        }

        public override void DrawLine(ref Vector3 from, ref Vector3 to, System.Drawing.Color color)
        {
            throw new System.NotImplementedException();
        }

        public override void ReportErrorWarning(string warningString)
        {
            throw new System.NotImplementedException();
        }
    }
}


text:
/*
 * Authors:     Nithya Ramanathan
 *
 */

// Possible actions handled by the power-tracker
enum {
  RT_SEND_DATA  = 1,
  RT_RECV_DATA,
  RT_SEND_NACK,
  RT_RECV_NACK,
  MOTE_OFF,
  MOTE_ON,
  RADIO_ON,  // includes idle mode and Receive mode
  RADIO_OFF,

  // MUST call RADIO_STOP_SEND after RADIO_START_SEND!
  RADIO_START_SEND,
  RADIO_STOP_SEND,
  RADIO_START_RECV,
  RADIO_STOP_RECV,
  SENSOR_ON,
  SENSOR_OFF,
  ANALOG_SENSOR_ON ,
  ANALOG_SENSOR_OFF ,
  DSDV_MSG_SEND ,
  DSDV_MSG_RECV ,
  CONTROL_POWERSAVE_PACKETS_SEND,
  CONTROL_POWERSAVE_PACKETS_RECV ,
  CONTROL_DATASCHEDULER_PACKETS_SEND,
  CONTROL_DATASCHEDULER_PACKETS_RECV,
  MISC_PACKET_TX,
  MISC_PACKET_RX,
};

// Struct used to transfer statistics between components
typedef struct Statistics {
  // Power Tracker
  // Naming convention <type>_<module>_<action>_<units>
  // type = num or time
  uint32_t time_mote_on_msec;
  uint32_t time_radio_on_msec;
  uint32_t time_radio_tx_msec;
  uint32_t time_radio_rx_msec;
  uint32_t time_sensor_on_msec;
  uint32_t time_analog_sensor_on_msec;
  uint32_t time_total_sec; // Total time these counters were running
  uint32_t num_times_radio_switched_on;

  // Packet Counters
  // Naming convention <type>_<protocol>_<action>_<pkt_type>
  // type = num or time
  // protocol => rt = reliability, dsdv = routing, ps => power-save,
  // 	ds => data-scheduler
  uint16_t num_rt_send_data;
  uint16_t num_rt_recv_data;
  uint16_t num_rt_send_nack;
  uint16_t num_rt_recv_nack;
  uint16_t num_dsdv_sent;
  uint16_t num_dsdv_recv;
  uint16_t num_packets_send_total;
  uint16_t num_packets_recv_total;
  uint16_t num_ps_send_ctrl;
  uint16_t num_ps_recv_ctrl;
  uint32_t num_ds_send_ctrl;
  uint32_t num_ds_recv_ctrl;
} Statistics_t;


text:
from cmsplugin_form_handler.cms_plugins import FormPluginBase
from cms.plugin_pool import plugin_pool

from .forms import SampleForm, SampleModelForm, SampleCrispyModelForm
from .models import Sample, SamplePluginModel

class SampleFormPlugin(FormPluginBase):
    """
    This is a normal (non-Crispy) non-model form plugin..
    """
    form_class = SampleForm
    model = SamplePluginModel
    name = 'Sample Form Plugin'
    render_template = 'sample/plugins/sample_plugin.html'
    success_url = '/'

    def render(self, context, instance, placeholder):
        context = super(SampleFormPlugin, self).render(
            context, instance, placeholder)
        context['plugin_name'] = self.name
        return context

    def form_valid(self, request, instance, form):
        """'Manually' create a sample object from the form data."""
        cleaned_data = form.cleaned_data
        return Sample.objects.create(
            name=cleaned_data['name'],
            message=cleaned_data['message'],
        )

plugin_pool.register_plugin(SampleFormPlugin)

class SampleModelFormPlugin(FormPluginBase):
    """
    This is a normal (non-Crispy) model form plugin.
    """
    form_class = SampleModelForm
    model = SamplePluginModel
    name = 'Sample Model Form Plugin'
    render_template = 'sample/plugins/sample_plugin.html'
    success_url = '/'

    def render(self, context, instance, placeholder):
        context = super(SampleModelFormPlugin, self).render(
            context, instance, placeholder)
        context['plugin_name'] = self.name
        return context

    # So we can ensure that the defaults work, we're intentionally not
    # overriding the following for the tests here:
    #   get_form_class()
    #   get_form_kwargs()
    #   get_success_url()
    #   form_valid()
    #
    # This is actually the typical usage pattern anyway.

plugin_pool.register_plugin(SampleModelFormPlugin)

class SampleCrispyModelFormPlugin(FormPluginBase):
    """
    This is the same form plugin as above, but uses Django Crispy Forms.
    """
    form_class = SampleCrispyModelForm
    model = SamplePluginModel
    name = 'Sample Crispy Model Form Plugin'
    render_template = 'sample/plugins/sample_crispy_plugin.html'
    success_url = '/'  # Or, see: get_success_url()

    def render(self, context, instance, placeholder):
        context = super(SampleCrispyModelFormPlugin, self).render(
            context, instance, placeholder)
        context['plugin_name'] = self.name
        return context

    # We're 'overriding' the default implementations for the these methods.

    def get_form_class(self, request, instance):
        # Use this method to programmatically determine the form_class.
        # This is what this method does by default:
        return self.form_class

    def get_form_kwargs(self, request, instance):
        # Use this method to programmatically add additional parameters to
        # your form. By default, this should return an empty dict.
        return {}

    def get_success_url(self, request, instance):
        # Use this method to programmatically determine the success_url.
        # This is what this method does by default:
        return self.success_url

    def form_valid(self, request, instance, form):
        # Optionally do something with the rendered form here
        # This is what this method does by default:
        form.save()

plugin_pool.register_plugin(SampleCrispyModelFormPlugin)


text:
class BadSessionError < StandardError; end
class RequestFailedError < StandardError; end

module Scrobbler
  class Scrobble
    # you need to read last.fm/api/submissions#subs first!

    attr_accessor :session_id, :submission_url, :artist, :track, :time,
                  :source, :length, :album, :track_number, :mb_track_id
    attr_reader :status

    def initialize(args = {})
      @session_id = args[:session_id] # from Scrobbler::SimpleAuth
      @submission_url = args[:submission_url] # from Scrobbler::SimpleAuth (can change)
      @artist = args[:artist] # track artist
      @track = args[:track] # track name
      @time = args[:time] # a Time object set to the time the track started playing
      @source = args[:source] || 'P' # track source, see last.fm/api/submissions#subs
      @length = args[:length].to_s || '' # track length in seconds
      @album = args[:album] || '' # track album name (optional)
      @track_number = args[:track_number] || '' # track number (optional)
      @mb_track_id = args[:mb_track_id] || '' # MusicBrainz track ID (optional)

      if [@session_id, @submission_url, @artist, @track].any?(&:blank?)
        raise ArgumentError, 'Missing required argument'
      elsif @time.class.to_s != 'Time'
        raise ArgumentError, ":time must be a Time object"
      elsif !['P','R','E','U'].include?(@source) # see last.fm/api/submissions#subs
        raise ArgumentError, "Invalid source"
      elsif @source == 'P' && @length.blank? # length is not optional if source is P
        raise ArgumentError, 'Length must be set'
      elsif !@length.blank? && @length.to_i <= 30 # see last.fm/api/submissions#subs
        raise ArgumentError, 'Length must be greater than 30 seconds'
      end

      @connection = REST::Connection.new(@submission_url)
    end

    def submit!
      query = { :s => @session_id,
                'a[0]' => @artist,
                't[0]' => @track,
                'i[0]' => @time.utc.to_i,
                'o[0]' => @source,
                'r[0]' => '',
                'l[0]' => @length,
                'b[0]' => @album,
                'n[0]' => @track_number,
                'm[0]' => @mb_track_id }

      @status = @connection.post('', query)

      case @status
      when /OK/

      when /BADSESSION/
        raise BadSessionError # rerun Scrobbler::SimpleAuth#handshake!
      when /FAILED/
        raise RequestFailedError, @status
      else
        raise RequestFailedError
      end
    end
  end
end


text:
package net.safedata.springboot.training.d01.s03.config;

import net.safedata.springboot.training.d01.s03.repository.ProductRepository;
import net.safedata.springboot.training.d01.s03.service.ProductService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * A simple Spring configuration, which wires two simple {@link Bean}s and configures their init and destroy methods
 *
 * @author bogdan.solga
 */
@Configuration
public class BeanParametersConfig {

    @Bean(initMethod = "initialize")
    public ProductRepository productRepository() {
        return new ProductRepository();
    }

    @Bean(destroyMethod = "onClose")
    public ProductService productService() {
        return new ProductService(productRepository());
    }
}