text:
package com.facebook.buck.android.dalvik.firstorder;

import org.objectweb.asm.AnnotationVisitor;
import org.objectweb.asm.FieldVisitor;
import org.objectweb.asm.Opcodes;

class FirstOrderFieldVisitor extends FieldVisitor {

  private final FirstOrderVisitorContext mContext;
  // Unused by dexopt: private final FirstOrderTypeInfo.Builder mBuilder;

  public FirstOrderFieldVisitor(FirstOrderVisitorContext context) {
    super(Opcodes.ASM7);
    mContext = context;
    // Unused by dexopt: mBuilder = context.builder;
  }

  @Override
  public AnnotationVisitor visitAnnotation(String desc, boolean visible) {
    // Unused by dexopt: mBuilder.addDependencyDesc(desc);
    return mContext.annotationVisitor;
  }
}


text:
package org.efaps.eql;

import java.util.Arrays;

import org.efaps.admin.datamodel.Type;
import org.efaps.ci.CIType;
import org.efaps.db.Instance;
import org.efaps.db.stmt.AbstractStmt;
import org.efaps.db.stmt.DeleteStmt;
import org.efaps.db.stmt.InsertStmt;
import org.efaps.db.stmt.PrintStmt;
import org.efaps.db.stmt.UpdateStmt;
import org.efaps.eql.builder.Delete;
import org.efaps.eql.builder.Insert;
import org.efaps.eql.builder.Print;
import org.efaps.eql.builder.Query;
import org.efaps.eql.builder.Selectables;
import org.efaps.eql.builder.Update;
import org.efaps.eql.builder.Where;
import org.efaps.eql2.EQL2;
import org.efaps.eql2.IDeleteStatement;
import org.efaps.eql2.IInsertStatement;
import org.efaps.eql2.IPrintStatement;
import org.efaps.eql2.IStatement;
import org.efaps.eql2.IUpdateStatement;
import org.efaps.eql2.bldr.AbstractDeleteEQLBuilder;
import org.efaps.eql2.bldr.AbstractInsertEQLBuilder;
import org.efaps.eql2.bldr.AbstractPrintEQLBuilder;
import org.efaps.eql2.bldr.AbstractQueryEQLBuilder;
import org.efaps.eql2.bldr.AbstractSelectables;
import org.efaps.eql2.bldr.AbstractUpdateEQLBuilder;
import org.efaps.eql2.bldr.AbstractWhereBuilder;

/**
 * EQL main util classes.
 *
 * @author The eFaps Team
 */
public final class EQL
    extends EQL2
{
    @Override
    protected AbstractPrintEQLBuilder<?> getPrint()
    {
        return new Print();
    }

    @Override
    protected AbstractUpdateEQLBuilder<?> getUpdate()
    {
        return new Update();
    }

    @Override
    protected AbstractInsertEQLBuilder<?> getInsert()
    {
        return new Insert();
    }

    @Override
    protected AbstractDeleteEQLBuilder<?> getDelete()
    {
        return new Delete();
    }

    @Override
    protected AbstractQueryEQLBuilder<?> getQuery()
    {
        return new Query();
    }

    @Override
    protected AbstractWhereBuilder<?> getWhere()
    {
        return new Where();
    }

    @Override
    protected AbstractSelectables getSelectables()
    {
        return new Selectables();
    }

    /**
     * Parses the stmt.
     *
     * @param _stmt the stmt
     * @return the abstract stmt
     */
    public static AbstractStmt getStatement(final CharSequence _stmt)
    {
        AbstractStmt ret = null;
        final IStatement<?> stmt = parse(_stmt);
        if (stmt instanceof IPrintStatement) {
            ret = PrintStmt.get((IPrintStatement<?>) stmt, null);
        } else if (stmt instanceof IDeleteStatement) {
            ret = DeleteStmt.get((IDeleteStatement<?>) stmt);
        } else if (stmt instanceof IInsertStatement) {
            ret = InsertStmt.get((IInsertStatement) stmt);
        } else if (stmt instanceof IUpdateStatement) {
            ret = UpdateStmt.get((IUpdateStatement<?>) stmt);
        }
        return ret;
    }

    public static EQLBuilder builder() {
        return new EQLBuilder(EQL2.eql());
    }

    public static class EQLBuilder extends EQL2Builder<EQLBuilder> {
        public EQLBuilder(final EQL2 _eql2) {
            super(_eql2);
        }

        @Override
        public Delete delete(final String... _oids) {
            return (Delete) super.delete(_oids);
        }

        public Delete delete(final Instance... _instances)
        {
            return delete(Arrays.stream(_instances)
                            .map(instance -> instance.getOid())
                            .toArray(String[]::new));
        }

        @Override
        public Insert insert(final String _typeName)
        {
            return (Insert) super.insert(_typeName);
        }

        public Insert insert(final CIType _ciType)
        {
            return insert(_ciType.getType().getName());
        }

        public Insert insert(final Type _type)
        {
            return insert(_type.getName());
        }

        @Override
        public Update update(final String... _oid)
        {
            return (Update) super.update(_oid);
        }

        public Update update(final Instance... _instances)
        {
            return update(Arrays.stream(_instances)
                            .map(instance -> instance.getOid())
                            .toArray(String[]::new));
        }

        public Print print()
        {
            return print(new String[0]);
        }

        @Override
        public Print print(final String... _oids)
        {
            return (Print) super.print(_oids);
        }

        public Print print(final Instance... _instances)
        {
            return print(Arrays.stream(_instances)
                            .map(instance -> instance.getOid())
                            .toArray(String[]::new));
        }

        @Override
        public Query query(final String... _types)
        {
            return (Query) super.query(_types);
        }

        public Query query(final CIType... _ciTypes)
        {
            return query(Arrays.stream(_ciTypes)
                            .map(ciType -> ciType.getType().getName())
                            .toArray(String[]::new));
        }

        public Query nestedQuery(final CIType... _ciTypes)
        {
            return (Query) nestedQuery(Arrays.stream(_ciTypes)
                            .map(ciType -> ciType.getType().getName())
                            .toArray(String[]::new));
        }

        @Override
        public Where where()
        {
            return (Where) super.where();
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
<!doctype html>

	<meta charset="UTF-8">
	<title>index</title>
	<link rel="stylesheet" type="text/css" href="style/reset.css">
	<link rel="stylesheet" type="text/css" href="style/style2.css">


text: -- Test migration 01


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Observ. mycol. (Havniae) 1: 209 (1815)

#### Original name
Mucor albovirens Fr.

### Remarks
null


text:
<?php

namespace PhalconTest\Flash;

use \Phalcon\Flash\Direct as PhDirect;

class Direct extends PhDirect
{
    public function setImplicitFlush($implicitFlush)
    {
        return parent::setImplicitFlush($implicitFlush);
    }

    public function setAutomaticHtml($automaticHtml)
    {
        parent::setAutomaticHtml($automaticHtml);
    }

    public function setCssClasses($cssClasses)
    {
        return parent::setCssClasses($cssClasses);
    }

    public function error($message)
    {
        return parent::error($message);
    }

    public function notice($message)
    {
        return parent::notice($message);
    }

    public function success($message)
    {
        return parent::success($message);
    }

    public function warning($message)
    {
        return parent::warning($message);
    }

    public function outputMessage($type, $message)
    {
        return parent::outputMessage($type, $message);
    }

    public function message($type, $message)
    {
        return parent::message($type, $message);
    }
}


text:
package org.activiti.bpmn.model;

public class ExtensionAttribute {

  protected String name;
  protected String value;
  protected String namespacePrefix;
  protected String namespace;

  public String getName() {
    return name;
  }
  public void setName(String name) {
    this.name = name;
  }
  public String getValue() {
    return value;
  }
  public void setValue(String value) {
    this.value = value;
  }
  public String getNamespacePrefix() {
    return namespacePrefix;
  }
  public void setNamespacePrefix(String namespacePrefix) {
    this.namespacePrefix = namespacePrefix;
  }
  public String getNamespace() {
    return namespace;
  }
  public void setNamespace(String namespace) {
    this.namespace = namespace;
  }
}


text:
<!DOCTYPE html>

        <meta charset="utf-8">
        <title>XF Tests</title>
        <link rel="stylesheet" href="./lib/qunit-1.12.0.css">


text:
package com.github.dkorotych.gradle.maven;

import org.apache.commons.lang3.ObjectUtils;
import org.gradle.api.GradleException;

import java.io.File;

/**
 * Exception with information about Maven installation or finding issue.
 *
 * @author Dmitry Korotych (dkorotych at gmail dot com)
 */
public class IncorrectMavenInstallationDirectoryException extends GradleException {
    /**
     * Create a Maven installation exception.
     *
     * @param directory Maven installation directory
     */
    public IncorrectMavenInstallationDirectoryException(final File directory) {
        super("Maven home is set to: '"
                + ObjectUtils.defaultIfNull(directory, "blank")
                + "' which is not a correct Maven installation directory");
    }
}


text:
import mock
from oslo_config import fixture as fixture_config

from ceilometer.agent import manager
from ceilometer.compute.pollsters import instance as pollsters_instance
from ceilometer.tests.unit.compute.pollsters import base

class TestInstancePollster(base.TestPollsterBase):

    def setUp(self):
        super(TestInstancePollster, self).setUp()

    @mock.patch('ceilometer.pipeline.setup_pipeline', mock.MagicMock())
    def test_get_samples_instance(self):
        mgr = manager.AgentManager()
        pollster = pollsters_instance.InstancePollster()
        samples = list(pollster.get_samples(mgr, {}, [self.instance]))
        self.assertEqual(1, len(samples))
        self.assertEqual('instance', samples[0].name)
        self.assertEqual(1, samples[0].resource_metadata['vcpus'])
        self.assertEqual(512, samples[0].resource_metadata['memory_mb'])
        self.assertEqual(20, samples[0].resource_metadata['disk_gb'])
        self.assertEqual(20, samples[0].resource_metadata['root_gb'])
        self.assertEqual(0, samples[0].resource_metadata['ephemeral_gb'])
        self.assertEqual('active', samples[0].resource_metadata['status'])

    @mock.patch('ceilometer.pipeline.setup_pipeline', mock.MagicMock())
    def test_get_reserved_metadata_with_keys(self):
        self.CONF = self.useFixture(fixture_config.Config()).conf
        self.CONF.set_override('reserved_metadata_keys', ['fqdn'])

        mgr = manager.AgentManager()
        pollster = pollsters_instance.InstancePollster()
        samples = list(pollster.get_samples(mgr, {}, [self.instance]))
        self.assertEqual({'fqdn': 'vm_fqdn',
                          'stack': '2cadc4b4-8789-123c-b4eg-edd2f0a9c128'},
                         samples[0].resource_metadata['user_metadata'])

    @mock.patch('ceilometer.pipeline.setup_pipeline', mock.MagicMock())
    def test_get_reserved_metadata_with_namespace(self):
        mgr = manager.AgentManager()
        pollster = pollsters_instance.InstancePollster()
        samples = list(pollster.get_samples(mgr, {}, [self.instance]))
        self.assertEqual({'stack': '2cadc4b4-8789-123c-b4eg-edd2f0a9c128'},
                         samples[0].resource_metadata['user_metadata'])

        self.CONF = self.useFixture(fixture_config.Config()).conf
        self.CONF.set_override('reserved_metadata_namespace', [])
        mgr = manager.AgentManager()
        pollster = pollsters_instance.InstancePollster()
        samples = list(pollster.get_samples(mgr, {}, [self.instance]))
        self.assertNotIn('user_metadata', samples[0].resource_metadata)


text:
<?xml version="1.0" encoding="UTF-8"?>
<!-- Generated by org.testng.reporters.JUnitReportReporter -->
<testsuite hostname="alex-pc" name="com.example.tests.ContactModificationTests" tests="1" failures="0" timestamp="16 Nov 2014 23:52:20 GMT" time="3.158" errors="0">
  <testcase name="modificationSomeContact" time="3.158" classname="com.example.tests.ContactModificationTests"/>
</testsuite> <!-- com.example.tests.ContactModificationTests -->


text:
Change log
====

This gem follows [Semantic Versioning 2.0.0](http://semver.org/spec/v2.0.0.html).
All classes and public methods are part of the public API, unless explicitly
noted otherwise in their documentation.

0.4.0
----
Release on 2014-09-18

This release maintains API compatibility with version 0.3.0, except for the two
constants that were removed.

Signatures produced with prior versions may be incompatible with signatures from
this version.

- Change the `Hasher#hash_string` method so that it can handle ECDSA groups
  that have a much smaller order than the number of bits they have (such as
  Curve25519).
- `Hasher` now validates that its group's byte-length is equal to its hash
  algorithm's byte-length.
- Remove support for ECDSA groups that have an order larger than the number of
  bits they have. Secp160k1 and Secp160r1 fall into this category because their
  order is larger than 2^160.
- Remove the `Secp160k1_Ripemd160` and `Secp160r1_Ripemd160` constants, since
  their groups are no longer supported.

0.3.0
----
Released on 2014-09-15

This release breaks API compatibility with version 0.2.0.

- Change `PrivateKey`, `PublicKey`, and `Signature` constructors such that they
  accept a required `Hasher` argument rather than an optional `ECDSA::Group` and
  `hash_algorithm`. The `Hasher` encapsulates these properties.
- Change `Hasher` constructor so that `group` and `hash_algorithm` attributes
  are passed in as explicit arguments rather than options.
- Remove `RingSig.default_group` and `RingSig.defaut_hash_algorithm` attributes.
  There are now no default algorithms.
- Update gem dependency for `ecdsa` gem to 1.2.

This will hopefully be the last major API change for a while, but it still may
change until 1.0 is released.

0.2.0
----
Released on 2014-09-12

This release breaks API compatibility with version 0.1.0.

- Add support for ruby 1.9, including jruby-19mode.
- Add `RingSig.default_group` and `RingSig.defaut_hash_algorithm` attributes.
- Change `Hasher` constructor so that `group` and `hash_algorithm` attributes
  are passed in as options rather than explicit arguments.

0.1.0
----
Released on 2014-09-11

This release breaks API compatibility with version 0.0.1.

- Split the `Key` class into `PrivateKey` and `PublicKey`, which better
  encapsulate the functionality of each.
- The `sign` and `key_image` methods are placed in the `PrivateKey` class.
- Remove the `drop_private_key` method from `Key`. Instead, a new method simply
  called `public_key` is included in both `PrivateKey` and `PublicKey`.
- Add methods `to_hex`, `to_octet`, `from_hex`, and `from_octet` to both
  `PrivateKey` and `PublicKey` classes.
- Add `==` methods to `PrivateKey` and `PublicKey`
- Add `point` attribute to `PublicKey` which stores the actual public key.
- Add `point` method to `PrivateKey` which references the public key's point.
- Add `value` attribute to `PrivateKey` which stores the actual private key.

0.0.1
----
Released on 2014-09-09

All core functionality is implemented:

- `Key` class
  - `sign` method
  - `key_image` method
  - `drop_private_key` method
  - `public_key` and `private_key` attributes
  - `group` and `hash_algorithm` attributes
- `Signature` class
  - `verify` method
  - `components` method
  - `to_hex`, `to_der`, `from_hex`, and `from_der` methods
  - `key_image`, `c_array`, and `r_array` attributes
  - `group` and `hash_algorithm` attributes
- `Hasher` class
  - `hash_string` method
  - `hash_array` method
  - `hash_point` method
  - `shuffle` method
  - `group` and `algorithm` attributes


text:
<?php

namespace Nwidart\Modules\Commands;

use Illuminate\Support\Str;
use Nwidart\Modules\Support\Config\GenerateConfigReader;
use Nwidart\Modules\Support\Stub;
use Nwidart\Modules\Traits\ModuleCommandTrait;
use Symfony\Component\Console\Input\InputArgument;

class RuleMakeCommand extends GeneratorCommand
{
    use ModuleCommandTrait;

    /**
     * The name of argument name.
     *
     * @var string
     */
    protected $argumentName = 'name';

    /**
     * The console command name.
     *
     * @var string
     */
    protected $name = 'module:make-rule';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Create a new validation rule for the specified module.';

    public function getDefaultNamespace(): string
    {
        $module = $this->laravel['modules'];

        return $module->config('paths.generator.rules.namespace') ?: $module->config('paths.generator.rules.path', 'Rules');
    }

    /**
     * Get the console command arguments.
     *
     * @return array
     */
    protected function getArguments()
    {
        return [
            ['name', InputArgument::REQUIRED, 'The name of the rule class.'],
            ['module', InputArgument::OPTIONAL, 'The name of module will be used.'],
        ];
    }

    /**
     * @return mixed
     */
    protected function getTemplateContents()
    {
        $module = $this->laravel['modules']->findOrFail($this->getModuleName());

        return (new Stub('/rule.stub', [
            'NAMESPACE' => $this->getClassNamespace($module),
            'CLASS'     => $this->getFileName(),
        ]))->render();
    }

    /**
     * @return mixed
     */
    protected function getDestinationFilePath()
    {
        $path = $this->laravel['modules']->getModulePath($this->getModuleName());

        $rulePath = GenerateConfigReader::read('rules');

        return $path . $rulePath->getPath() . '/' . $this->getFileName() . '.php';
    }

    /**
     * @return string
     */
    private function getFileName()
    {
        return Str::studly($this->argument('name'));
    }
}


text:
package com.basecamp.turbolinks;

import android.util.Log;

class TurbolinksLog {
    private static final String DEFAULT_TAG = "TurbolinksLog";
    private static boolean debugLoggingEnabled = false;

    /**
     *
Enables/disables debug logging.

     *
     * @param enabled True, to enable.
     */
    static void setDebugLoggingEnabled(boolean enabled) {
        debugLoggingEnabled = enabled;
    }

    /**
     *
Send a DEBUG level log statement with the default tag

     *
     * @param msg Debug message.
     */
    static void d(String msg) {
        log(Log.DEBUG, DEFAULT_TAG, msg);
    }

    /**
     *
Send a ERROR level log statement with the default tag

     *
     * @param msg Error message.
     */
    static void e(String msg) {
        log(Log.ERROR, DEFAULT_TAG, msg);
    }

    /**
     *
Default log statement called by other convenience methods.

     *
     * @param logLevel Log level of the statement.
     * @param tag Tag to identify the logging statement.
     * @param msg Message to log.
     */
    private static void log(int logLevel, String tag, String msg) {
        switch (logLevel) {
            case Log.DEBUG:
                if (debugLoggingEnabled) {
                    Log.d(tag, msg);
                }
                break;
            case Log.ERROR:
                Log.e(tag, msg);
                break;
            default:
                break;
        }
    }
}


text:
'use strict';

const assert = require('assert');
const Quoter = require('../../src/Quoter');

describe('Quoter', () => {
	describe('unquote()', () => {
		for (const quoteCharacter of ["'", '"', '`']) {
			it('quote character = [' + quoteCharacter + ']', () => {
				const q = (string) => {
					return quoteCharacter + string + quoteCharacter;
				};

				assert.strictEqual(Quoter.unquote(q('')), '');
				assert.strictEqual(Quoter.unquote(q('hello')), 'hello');
				assert.strictEqual(Quoter.unquote(q('hello\\tworld')), 'hello\tworld');
			});
		}
	});

	describe('unquoteOptionalQuotes', () => {
		it('quoted string', () => {
			assert.strictEqual(Quoter.unquoteOptionalQuotes('""', '"'), '');
			assert.strictEqual(Quoter.unquoteOptionalQuotes('"hello"', '"'), 'hello');
			assert.strictEqual(Quoter.unquoteOptionalQuotes('\'hello\'', '\''), 'hello');
			assert.strictEqual(Quoter.unquoteOptionalQuotes('`hello`', '`'), 'hello');
		});

		it('unquoted string', () => {
			assert.strictEqual(Quoter.unquoteOptionalQuotes('', '"'), '');
			assert.strictEqual(Quoter.unquoteOptionalQuotes('hello', '"'), 'hello');
			assert.strictEqual(Quoter.unquoteOptionalQuotes('hello', '\''), 'hello');
		});

		it('quoted by wrong quotes', () => {
			assert.strictEqual(Quoter.unquoteOptionalQuotes('\'hello\'', '"'), '\'hello\'');
			assert.strictEqual(Quoter.unquoteOptionalQuotes('"hello"', '\''), '"hello"');
		});
	});

	describe('unescape()', () => {
		it('quotes', () => {
			assert.strictEqual(Quoter.unescape('\\"'), '"');
			assert.strictEqual(Quoter.unescape('\\\''), '\'');
			assert.strictEqual(Quoter.unescape('\\`'), '`');
		});

		it('special characters', () => {
			assert.strictEqual(Quoter.unescape('line1\\nline2'), 'line1\nline2');
			assert.strictEqual(Quoter.unescape('col\\tcol'), 'col\tcol');
		});

		it('quote character at last position', () => {
			assert.throws(() => {
				Quoter.unescape('hello\\');
			}, Error, 'Unexpected end of string after');
		});

		// http://dev.mysql.com/doc/refman/5.7/en/string-literals.html Table 10.1
		it('MySQL compatibility', () => {
			assert.strictEqual(
				Quoter.unescape('\\0\\b\\n\\r\\t\\Z\\%\\_\\f\\g\\h\\j'),
				'\u0000\b\n\r\t\u001a\\%\\_fghj'
			);
		});

		it('custom callbacks', () => {
			const results = [
				['c', 2],
				['d', 4],
				['f', 7]
			];

			const handler = (...args) => {
				const expected = results.shift();

				assert.deepStrictEqual(args, expected);

				return '>' + args[0] + '<';
			};

			const r = Quoter.unescape(
				"ab\\c\\de\\f",
				{
					c: handler,
					d: handler,
					f: handler
				}
			);

			assert.strictEqual(results.length, 0);
			assert.strictEqual(r, 'ab>c<>d<e>f<');
		});
	});
});


text:
module RMeetup
  module Fetcher
    Domain = "api.meetup.com"

    class ApiError < StandardError
      def initialize(error_message, request_url)
        super "Meetup API Error: #{error_message} - API URL: #{request_url}"
      end
    end

    class NoResponseError < StandardError
      def initialize
        super "No Response was returned from the Meetup API."
      end
    end

    # == RMeetup::Fetcher::Base
    #
    # Base fetcher class that other fetchers will inherit from.
    class Base
      def initialize
        @type = nil
      end

      # Fetch and parse a response based on a set of options.  Override this method to ensure neccessary options are passed for the request.
      #
      # @param options [Hash] Options for deciding what and how to fetch
      # @return [RMeetup::Collection] Collection of appropriate entities
      def fetch(options = {})
        raise NotConfiguredError, /fetches only possible with a concrete fetcher/ if @type.nil?
        path = path_and_query(options)

        # Fetch and parse data from Meetup
        response_body = requester(options).get(path).body || raise(NoResponseError.new)
        data = JSON.parse(response_body)

        # Check to see if the api returned an error
        raise ApiError.new(data['details'],path) if data.has_key?('problem')

        collection = RMeetup::Collection.build(data)

        # Format each result in the collection and return it
        collection.map!{|result| format_result(result)}
      end

      def path_and_query(options)
        base_path + query(options)
      end

      def base_path
        "/2/#{@type}"
      end

      # Create a query string from an options hash
      def query(options)
        '?' + URI.encode_www_form(options)
      end

      # Decides whether to use HTTP or HTTPS. HTTPS is needed if we're authoizing via the :access_token
      #
      # @param q [Hash] Constructed HTTP(S) query
      # @return [Net:HTTP] Constructs an HTTP request if client is given an API key
      # @return [Net:HTTPS] Constructs an HTTPS request if client is given an access token
      def requester(q)
        if q.has_key?(:api_key)
          http
        elsif q.has_key?(:access_token)
          https
        else
          http
        end
      end

      protected
      # OVERRIDE this method to format a result section
      # as per Result type.
      # Takes a result in a collection and
      # formats it to be put back into the collection.
      def format_result(result)
        result
      end

      def http
        Net::HTTP.new Domain, 80
      end

      def https
        c = Net::HTTP.new Domain, 443
        c.use_ssl = true
        c
      end

    end
  end
end


text:
package com.expidevapps.android.measurements.db;

import static com.expidevapps.android.measurements.db.Contract.Mcc.COLUMN_MCC;
import static com.expidevapps.android.measurements.db.Contract.MinistryId.COLUMN_MINISTRY_ID;
import static com.expidevapps.android.measurements.db.Contract.Story.COLUMN_CONTENT;
import static com.expidevapps.android.measurements.db.Contract.Story.COLUMN_CREATED;
import static com.expidevapps.android.measurements.db.Contract.Story.COLUMN_CREATED_BY;
import static com.expidevapps.android.measurements.db.Contract.Story.COLUMN_ID;
import static com.expidevapps.android.measurements.db.Contract.Story.COLUMN_IMAGE;
import static com.expidevapps.android.measurements.db.Contract.Story.COLUMN_PENDING_IMAGE;
import static com.expidevapps.android.measurements.db.Contract.Story.COLUMN_PRIVACY;
import static com.expidevapps.android.measurements.db.Contract.Story.COLUMN_STATE;
import static com.expidevapps.android.measurements.db.Contract.Story.COLUMN_TITLE;
import static org.ccci.gto.android.common.db.util.CursorUtils.getNonNullEnum;

import android.content.ContentValues;
import android.database.Cursor;
import android.support.annotation.NonNull;

import com.expidevapps.android.measurements.model.Ministry;
import com.expidevapps.android.measurements.model.Ministry.Mcc;
import com.expidevapps.android.measurements.model.Story;
import com.expidevapps.android.measurements.model.Story.Privacy;
import com.expidevapps.android.measurements.model.Story.State;

import org.joda.time.LocalDate;

import java.io.File;

class StoryMapper extends LocationMapper<Story> {
    @Override
    protected void mapField(@NonNull final ContentValues values, @NonNull final String field,
                            @NonNull final Story story) {
        switch (field) {
            case COLUMN_ID:
                values.put(field, story.getId());
                break;
            case COLUMN_MINISTRY_ID:
                values.put(field, story.getMinistryId());
                break;
            case COLUMN_MCC:
                values.put(field, story.getMcc().toString());
                break;
            case COLUMN_TITLE:
                values.put(field, story.getTitle());
                break;
            case COLUMN_CONTENT:
                values.put(field, story.getContent());
                break;
            case COLUMN_IMAGE:
                values.put(field, story.getImageUrl());
                break;
            case COLUMN_PENDING_IMAGE:
                final File file = story.getPendingImage();
                values.put(field, file != null ? file.getPath() : null);
                break;
            case COLUMN_STATE:
                values.put(field, story.getState().toString());
                break;
            case COLUMN_PRIVACY:
                values.put(field, story.getPrivacy().toString());
                break;
            case COLUMN_CREATED:
                values.put(field, story.getCreated().toString());
                break;
            case COLUMN_CREATED_BY:
                values.put(field, story.getCreatedBy());
                break;
            default:
                super.mapField(values, field, story);
                break;
        }
    }

    @NonNull
    @Override
    protected Story newObject(@NonNull final Cursor c) {
        return new Story();
    }

    @NonNull
    @Override
    public Story toObject(@NonNull Cursor c) {
        final Story story = super.toObject(c);

        story.setId(getLong(c, COLUMN_ID, Story.INVALID_ID));
        story.setMinistryId(getNonNullString(c, COLUMN_MINISTRY_ID, Ministry.INVALID_ID));
        story.setMcc(getNonNullEnum(c, COLUMN_MCC, Mcc.class, Mcc.UNKNOWN));
        story.setTitle(getNonNullString(c, COLUMN_TITLE, ""));
        story.setContent(getNonNullString(c, COLUMN_CONTENT, ""));
        story.setImageUrl(getString(c, COLUMN_IMAGE, null));
        story.setPendingImage(getFile(c, COLUMN_PENDING_IMAGE, null));
        story.setState(getNonNullEnum(c, COLUMN_STATE, State.class, State.UNKNOWN));
        story.setPrivacy(getNonNullEnum(c, COLUMN_PRIVACY, Privacy.class, Privacy.DEFAULT));
        story.setCreated(getNonNullLocalDate(c, COLUMN_CREATED, LocalDate.now()));
        story.setCreatedBy(getString(c, COLUMN_CREATED_BY, null));

        return story;
    }
}


text:
class Group < ActiveRecord::Base
  has_many :groups_users, dependent: :destroy
  has_many :users, through: :groups_users
  has_many :groups_permissions, dependent: :destroy
  has_many :permissions, through: :groups_permissions

  validates :name, :description, presence: true
  validates :name, uniqueness: true
end


text:
package org.apache.camel.component.file;
import org.apache.camel.ContextTestSupport;
import org.apache.camel.Exchange;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.junit.Before;
import org.junit.Test;

/**
 * Unit test to verify the append option
 */
public class FileProduceAppendTest extends ContextTestSupport {

    @Test
    public void testAppendText() throws Exception {
        MockEndpoint mock = getMockEndpoint("mock:result");
        mock.expectedMessageCount(1);
        mock.expectedFileExists("target/data/test-file-append/hello.txt", "Hello World");

        template.sendBody("direct:start", " World");

        assertMockEndpointsSatisfied();
    }

    @Override
    @Before
    public void setUp() throws Exception {
        deleteDirectory("target/data/test-file-append");
        super.setUp();
        template.sendBodyAndHeader("file://target/data/test-file-append", "Hello", Exchange.FILE_NAME, "hello.txt");
        template.sendBodyAndHeader("file://target/data/test-file-append", " World", Exchange.FILE_NAME, "world.txt");
    }

    @Override
    protected RouteBuilder createRouteBuilder() {
        return new RouteBuilder() {
            public void configure() {
                from("direct:start")
                    .setHeader(Exchange.FILE_NAME, constant("hello.txt"))
                    .to("file://target/data/test-file-append?fileExist=Append", "mock:result");
            }
        };
    }

}


text:
from __future__ import absolute_import, unicode_literals

import copy

from ..datetimes import registerDateHandler, _parse_date
from ..urls import _makeSafeAbsoluteURI
from ..util import FeedParserDict

class Namespace(object):
    """Support for the Atom, RSS, RDF, and CDF feed formats.

    The feed formats all share common elements, some of which have conflicting
    interpretations. For simplicity, all of the base feed format support is
    collected here.
    """

    supported_namespaces = {
        '': '',
        'http://backend.userland.com/rss': '',
        'http://blogs.law.harvard.edu/tech/rss': '',
        'http://purl.org/rss/1.0/': '',
        'http://my.netscape.com/rdf/simple/0.9/': '',
        'http://example.com/newformat#': '',
        'http://example.com/necho': '',
        'http://purl.org/echo/': '',
        'uri/of/echo/namespace#': '',
        'http://purl.org/pie/': '',
        'http://purl.org/atom/ns#': '',
        'http://www.w3.org/2005/Atom': '',
        'http://purl.org/rss/1.0/modules/rss091#': '',
    }

    def _start_rss(self, attrsD):
        versionmap = {'0.91': 'rss091u',
                      '0.92': 'rss092',
                      '0.93': 'rss093',
                      '0.94': 'rss094'}
        #If we're here then this is an RSS feed.
        #If we don't have a version or have a version that starts with something
        #other than RSS then there's been a mistake. Correct it.
        if not self.version or not self.version.startswith('rss'):
            attr_version = attrsD.get('version', '')
            version = versionmap.get(attr_version)
            if version:
                self.version = version
            elif attr_version.startswith('2.'):
                self.version = 'rss20'
            else:
                self.version = 'rss'

    def _start_channel(self, attrsD):
        self.infeed = 1
        self._cdf_common(attrsD)

    def _cdf_common(self, attrsD):
        if 'lastmod' in attrsD:
            self._start_modified({})
            self.elementstack[-1][-1] = attrsD['lastmod']
            self._end_modified()
        if 'href' in attrsD:
            self._start_link({})
            self.elementstack[-1][-1] = attrsD['href']
            self._end_link()

    def _start_feed(self, attrsD):
        self.infeed = 1
        versionmap = {'0.1': 'atom01',
                      '0.2': 'atom02',
                      '0.3': 'atom03'}
        if not self.version:
            attr_version = attrsD.get('version')
            version = versionmap.get(attr_version)
            if version:
                self.version = version
            else:
                self.version = 'atom'

    def _end_channel(self):
        self.infeed = 0
    _end_feed = _end_channel

    def _start_image(self, attrsD):
        context = self._getContext()
        if not self.inentry:
            context.setdefault('image', FeedParserDict())
        self.inimage = 1
        self.title_depth = -1
        self.push('image', 0)

    def _end_image(self):
        self.pop('image')
        self.inimage = 0

    def _start_textinput(self, attrsD):
        context = self._getContext()
        context.setdefault('textinput', FeedParserDict())
        self.intextinput = 1
        self.title_depth = -1
        self.push('textinput', 0)
    _start_textInput = _start_textinput

    def _end_textinput(self):
        self.pop('textinput')
        self.intextinput = 0
    _end_textInput = _end_textinput

    def _start_author(self, attrsD):
        self.inauthor = 1
        self.push('author', 1)
        # Append a new FeedParserDict when expecting an author
        context = self._getContext()
        context.setdefault('authors', [])
        context['authors'].append(FeedParserDict())
    _start_managingeditor = _start_author

    def _end_author(self):
        self.pop('author')
        self.inauthor = 0
        self._sync_author_detail()
    _end_managingeditor = _end_author

    def _start_contributor(self, attrsD):
        self.incontributor = 1
        context = self._getContext()
        context.setdefault('contributors', [])
        context['contributors'].append(FeedParserDict())
        self.push('contributor', 0)

    def _end_contributor(self):
        self.pop('contributor')
        self.incontributor = 0

    def _start_name(self, attrsD):
        self.push('name', 0)

    def _end_name(self):
        value = self.pop('name')
        if self.inpublisher:
            self._save_author('name', value, 'publisher')
        elif self.inauthor:
            self._save_author('name', value)
        elif self.incontributor:
            self._save_contributor('name', value)
        elif self.intextinput:
            context = self._getContext()
            context['name'] = value

    def _start_width(self, attrsD):
        self.push('width', 0)

    def _end_width(self):
        value = self.pop('width')
        try:
            value = int(value)
        except ValueError:
            value = 0
        if self.inimage:
            context = self._getContext()
            context['width'] = value

    def _start_height(self, attrsD):
        self.push('height', 0)

    def _end_height(self):
        value = self.pop('height')
        try:
            value = int(value)
        except ValueError:
            value = 0
        if self.inimage:
            context = self._getContext()
            context['height'] = value

    def _start_url(self, attrsD):
        self.push('href', 1)
    _start_homepage = _start_url
    _start_uri = _start_url

    def _end_url(self):
        value = self.pop('href')
        if self.inauthor:
            self._save_author('href', value)
        elif self.incontributor:
            self._save_contributor('href', value)
    _end_homepage = _end_url
    _end_uri = _end_url

    def _start_email(self, attrsD):
        self.push('email', 0)

    def _end_email(self):
        value = self.pop('email')
        if self.inpublisher:
            self._save_author('email', value, 'publisher')
        elif self.inauthor:
            self._save_author('email', value)
        elif self.incontributor:
            self._save_contributor('email', value)

    def _start_subtitle(self, attrsD):
        self.pushContent('subtitle', attrsD, 'text/plain', 1)
    _start_tagline = _start_subtitle

    def _end_subtitle(self):
        self.popContent('subtitle')
    _end_tagline = _end_subtitle

    def _start_rights(self, attrsD):
        self.pushContent('rights', attrsD, 'text/plain', 1)
    _start_copyright = _start_rights

    def _end_rights(self):
        self.popContent('rights')
    _end_copyright = _end_rights

    def _start_item(self, attrsD):
        self.entries.append(FeedParserDict())
        self.push('item', 0)
        self.inentry = 1
        self.guidislink = 0
        self.title_depth = -1
        id = self._getAttribute(attrsD, 'rdf:about')
        if id:
            context = self._getContext()
            context['id'] = id
        self._cdf_common(attrsD)
    _start_entry = _start_item

    def _end_item(self):
        self.pop('item')
        self.inentry = 0
    _end_entry = _end_item

    def _start_language(self, attrsD):
        self.push('language', 1)

    def _end_language(self):
        self.lang = self.pop('language')

    def _start_webmaster(self, attrsD):
        self.push('publisher', 1)

    def _end_webmaster(self):
        self.pop('publisher')
        self._sync_author_detail('publisher')

    def _start_published(self, attrsD):
        self.push('published', 1)
    _start_issued = _start_published
    _start_pubdate = _start_published

    def _end_published(self):
        value = self.pop('published')
        self._save('published_parsed', _parse_date(value), overwrite=True)
    _end_issued = _end_published
    _end_pubdate = _end_published

    def _start_updated(self, attrsD):
        self.push('updated', 1)
    _start_modified = _start_updated
    _start_lastbuilddate = _start_updated

    def _end_updated(self):
        value = self.pop('updated')
        parsed_value = _parse_date(value)
        self._save('updated_parsed', parsed_value, overwrite=True)
    _end_modified = _end_updated
    _end_lastbuilddate = _end_updated

    def _start_created(self, attrsD):
        self.push('created', 1)

    def _end_created(self):
        value = self.pop('created')
        self._save('created_parsed', _parse_date(value), overwrite=True)

    def _start_expirationdate(self, attrsD):
        self.push('expired', 1)

    def _end_expirationdate(self):
        self._save('expired_parsed', _parse_date(self.pop('expired')), overwrite=True)

    def _start_category(self, attrsD):
        term = attrsD.get('term')
        scheme = attrsD.get('scheme', attrsD.get('domain'))
        label = attrsD.get('label')
        self._addTag(term, scheme, label)
        self.push('category', 1)
    _start_keywords = _start_category

    def _end_category(self):
        value = self.pop('category')
        if not value:
            return
        context = self._getContext()
        tags = context['tags']
        if value and len(tags) and not tags[-1]['term']:
            tags[-1]['term'] = value
        else:
            self._addTag(value, None, None)
    _end_keywords = _end_category

    def _start_cloud(self, attrsD):
        self._getContext()['cloud'] = FeedParserDict(attrsD)

    def _start_link(self, attrsD):
        attrsD.setdefault('rel', 'alternate')
        if attrsD['rel'] == 'self':
            attrsD.setdefault('type', 'application/atom+xml')
        else:
            attrsD.setdefault('type', 'text/html')
        context = self._getContext()
        attrsD = self._itsAnHrefDamnIt(attrsD)
        if 'href' in attrsD:
            attrsD['href'] = self.resolveURI(attrsD['href'])
        expectingText = self.infeed or self.inentry or self.insource
        context.setdefault('links', [])
        if not (self.inentry and self.inimage):
            context['links'].append(FeedParserDict(attrsD))
        if 'href' in attrsD:
            expectingText = 0
            if (attrsD.get('rel') == 'alternate') and (self.mapContentType(attrsD.get('type')) in self.html_types):
                context['link'] = attrsD['href']
        else:
            self.push('link', expectingText)

    def _end_link(self):
        value = self.pop('link')

    def _start_guid(self, attrsD):
        self.guidislink = (attrsD.get('ispermalink', 'true') == 'true')
        self.push('id', 1)
    _start_id = _start_guid

    def _end_guid(self):
        value = self.pop('id')
        self._save('guidislink', self.guidislink and 'link' not in self._getContext())
        if self.guidislink:
            # guid acts as link, but only if 'ispermalink' is not present or is 'true',
            # and only if the item doesn't already have a link element
            self._save('link', value)
    _end_id = _end_guid

    def _start_title(self, attrsD):
        if self.svgOK:
            return self.unknown_starttag('title', list(attrsD.items()))
        self.pushContent('title', attrsD, 'text/plain', self.infeed or self.inentry or self.insource)

    def _end_title(self):
        if self.svgOK:
            return
        value = self.popContent('title')
        if not value:
            return
        self.title_depth = self.depth

    def _start_description(self, attrsD):
        context = self._getContext()
        if 'summary' in context:
            self._summaryKey = 'content'
            self._start_content(attrsD)
        else:
            self.pushContent('description', attrsD, 'text/html', self.infeed or self.inentry or self.insource)

    def _start_abstract(self, attrsD):
        self.pushContent('description', attrsD, 'text/plain', self.infeed or self.inentry or self.insource)

    def _end_description(self):
        if self._summaryKey == 'content':
            self._end_content()
        else:
            value = self.popContent('description')
        self._summaryKey = None
    _end_abstract = _end_description

    def _start_info(self, attrsD):
        self.pushContent('info', attrsD, 'text/plain', 1)
    _start_feedburner_browserfriendly = _start_info

    def _end_info(self):
        self.popContent('info')
    _end_feedburner_browserfriendly = _end_info

    def _start_generator(self, attrsD):
        if attrsD:
            attrsD = self._itsAnHrefDamnIt(attrsD)
            if 'href' in attrsD:
                attrsD['href'] = self.resolveURI(attrsD['href'])
        self._getContext()['generator_detail'] = FeedParserDict(attrsD)
        self.push('generator', 1)

    def _end_generator(self):
        value = self.pop('generator')
        context = self._getContext()
        if 'generator_detail' in context:
            context['generator_detail']['name'] = value

    def _start_summary(self, attrsD):
        context = self._getContext()
        if 'summary' in context:
            self._summaryKey = 'content'
            self._start_content(attrsD)
        else:
            self._summaryKey = 'summary'
            self.pushContent(self._summaryKey, attrsD, 'text/plain', 1)

    def _end_summary(self):
        if self._summaryKey == 'content':
            self._end_content()
        else:
            self.popContent(self._summaryKey or 'summary')
        self._summaryKey = None

    def _start_enclosure(self, attrsD):
        attrsD = self._itsAnHrefDamnIt(attrsD)
        context = self._getContext()
        attrsD['rel'] = 'enclosure'
        context.setdefault('links', []).append(FeedParserDict(attrsD))

    def _start_source(self, attrsD):
        if 'url' in attrsD:
            # This means that we're processing a source element from an RSS 2.0 feed
            self.sourcedata['href'] = attrsD['url']
        self.push('source', 1)
        self.insource = 1
        self.title_depth = -1

    def _end_source(self):
        self.insource = 0
        value = self.pop('source')
        if value:
            self.sourcedata['title'] = value
        self._getContext()['source'] = copy.deepcopy(self.sourcedata)
        self.sourcedata.clear()

    def _start_content(self, attrsD):
        self.pushContent('content', attrsD, 'text/plain', 1)
        src = attrsD.get('src')
        if src:
            self.contentparams['src'] = src
        self.push('content', 1)

    def _start_body(self, attrsD):
        self.pushContent('content', attrsD, 'application/xhtml+xml', 1)
    _start_xhtml_body = _start_body

    def _start_content_encoded(self, attrsD):
        self.pushContent('content', attrsD, 'text/html', 1)
    _start_fullitem = _start_content_encoded

    def _end_content(self):
        copyToSummary = self.mapContentType(self.contentparams.get('type')) in (['text/plain'] + self.html_types)
        value = self.popContent('content')
        if copyToSummary:
            self._save('summary', value)

    _end_body = _end_content
    _end_xhtml_body = _end_content
    _end_content_encoded = _end_content
    _end_fullitem = _end_content

    def _start_newlocation(self, attrsD):
        self.push('newlocation', 1)

    def _end_newlocation(self):
        url = self.pop('newlocation')
        context = self._getContext()
        # don't set newlocation if the context isn't right
        if context is not self.feeddata:
            return
        context['newlocation'] = _makeSafeAbsoluteURI(self.baseuri, url.strip())


text:
	<title>Brooke Vincent's panel show appearances</title>

	<link rel="stylesheet" media="all" href="../style.css" type="text/css"/>

Brooke Vincent's panel show appearances

Brooke Vincent (born 1992-06-04[ref]) has appeared in 9 episodes between 2011-2017.  Brooke Vincent on IMDB. Brooke Vincent on Wikipedia.

2011

2012

2013

2014

2015

2016

2017

2017-01-10 / Virtually Famous

2015-06-04 / Loose Women

2015-05-16 / Play To The Whistle

2015-05-14 / Celebrity Juice

2014-01-28 / Loose Women

2013-05-02 / Celebrity Juice

2013-01-31 / Fake Reaction

2011-11-29 / Loose Women

2011-04-21 / Celebrity Juice


text:
<?php
class MyActionController extends PHPFrame_ActionController
{
    public function __construct(PHPFrame_Application $app)
    {
        parent::__construct($app, "index");
    }

    public function index()
    {
        // Do something...
    }
}


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

package com.google.api.ads.admanager.jaxws.v202208;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for YieldParameter complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="YieldParameter">
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element name="name" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
 *         <element name="isOptional" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/>
 *       </sequence>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "YieldParameter", propOrder = {
    "name",
    "isOptional"
})
public class YieldParameter {

    protected String name;
    protected Boolean isOptional;

    /**
     * Gets the value of the name property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getName() {
        return name;
    }

    /**
     * Sets the value of the name property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setName(String value) {
        this.name = value;
    }

    /**
     * Gets the value of the isOptional property.
     *
     * @return
     *     possible object is
     *     {@link Boolean }
     *
     */
    public Boolean isIsOptional() {
        return isOptional;
    }

    /**
     * Sets the value of the isOptional property.
     *
     * @param value
     *     allowed object is
     *     {@link Boolean }
     *
     */
    public void setIsOptional(Boolean value) {
        this.isOptional = value;
    }

}


text:
class Mutations : public sf::Drawable, public sf::Transformable{

private:
  // Setting up the problem:
  unsigned int fDisx, fDisy;               // True display dimensions in pixels
  unsigned int fNPixels;                   // N Pixels, same for all windows and images
  unsigned int fGridX, fGridY;             // Grid input image, sum rgb for each grid
  int fNtries;                             // # of polygons to be drawn
  int fNvertices;                          // # of vertices

  // Handle the Polygons:
  sf::VertexArray fTri;                         // 1 polygon
  std::vector<sf::VertexArray> fTrianglesNow;   // The set of polygons prior to mutation
  std::vector<sf::VertexArray> fTrianglesNext;  // The set of polygons after mutation
  std::map<int,sf::Vector2f> fTriPositionsNow;  // positions prior to mutation
  std::map<int,sf::Vector2f> fTriPositionsNext; // positions after
  std::map<int,sf::Color> fTriColorsNow;        // colors prior
  std::map<int,sf::Color> fTriColorsNext;       // colors after

  // The Input Image:
  sf::Image fImage;                             // Input image to be replicated
  std::vector<sf::Color> fInput;                // Color vector of input image
  sf::Color fAverage;                           // rgb average of input image
  std::vector<sf::Color> fGridColor;            // grid input image, average pixels in grid
  std::vector<sf::FloatRect> fBoundaryColor;    // boundary representing location of the grid

  // The Mutated Image:
  std::vector<sf::Color> fNow, fNext;           // vector of colors before (after) mutation
  int fTriCountPos, fTriCountCol;               // indices to access vertex array to mutate
  std::map<int,TString> fRGBA;                  // map between random number and random rgba mutated

  // Diagnostics:
  long long int fNMutations, fNAttempts;        // # of mutations, # of attempts
  double fFitness;                              // 1-chi2-minimzation of rgba difference
  long int fN_nochange;                         // # of attempts without mutating
  TRandom fRand;
  std::vector<sf::RectangleShape> fRects;       // testing
  bool fStatus;

  // ROOT Diagnostics:
  TFile *fOut;
  std::vector<double> fNMutateX, fFitnessY;
  std::vector<double> fNAttemptX,fFitnessYY;
  TH2D *hRandPosX_Fitness, *hRandPosY_Fitness;
  double fRandPosX,fRandPosY;

public:
  Mutations(unsigned int, unsigned int, int, int);
  ~Mutations() {};
  void draw(sf::RenderTarget&, sf::RenderStates) const;              // Generic draw

  void GenerateTriangles(bool randcolor,sf::Color color, bool grid); // Generate intial polygons
  void GetAttempt(sf::Image, bool first_try);                        // Get Mutation screen shot

  void Mutate(int,int);  // Apply mutations to position and rgba
  double CalculateFitness(bool,bool); // difference square of rgb(a) b/t input and mutated
  void CheckMutation();               // check fitness level, keep mutation if new fitness is better

  // Retrieve the sample image:
  void SetImage(sf::Image win) {fImage=win;} // Get the Image to process
  void GetAverageRGB();                      // Average the rgb over all pixels
  void GridInput(int);                       // grid input image, then average each grid
  void setImageColorVec(std::vector<sf::Color> a) { fInput = a; } // vector of input colors

  // Retrieve Diagnostics:
  double GetBestChi2() { return fFitness; }
  long long int GetMutationNumber() { return fNMutations; }
  long long int GetNAttempts() { return fNAttempts; }

  // ROOT:
  void setupOutput(const char*);
  void FinishUp();

  // Testing output of window capture and some functionality:
  void Test(const char* output);
  bool CloseProgram(){ return fStatus; }
};
#endif


text:
package com.crawljax.forms;

import com.crawljax.browser.EmbeddedBrowser;
import com.crawljax.core.configuration.CrawlRules;
import com.crawljax.core.state.Identification;
import com.google.inject.Inject;
import com.google.inject.assistedinject.Assisted;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * Creates form value templates by pausing the crawl and allowing the user to manually enter form
 * formInputs.
 *
 * @author qhanam
 */
public class TrainingFormHandler extends FormHandler {

	@SuppressWarnings("unused")
	private static final Logger LOGGER =
			LoggerFactory.getLogger(TrainingFormHandler.class.getName());

	/**
	 * The HTML to display when the crawl is paused for form input.
	 */
	private static final String MODAL_HTML =
			"

&times
Crawl Paused

The crawl has encountered form inputs which have not been trained. Please enter all input data for the page and hit 'F1' when finished.

Crawljax Training Alert

";

	/**
	 * Keeps track of the form data manually entered during training.
	 **/
	private static Set<Identification> visited = new HashSet<>();

	@Inject
	public TrainingFormHandler(@Assisted EmbeddedBrowser browser, CrawlRules config) {
		super(browser, config);
	}

	/**
	 * Fills in form/input elements.
	 * Because we write to the singleton  @code{FormInputValueHelper}, this method
	 * must be mutually exclusive. In practice, this probably has no effect because
	 * it is unlikely that someone would train the crawler using multiple browser
	 * threads.
	 *
	 * @param formInputs form input list.
	 */
	public synchronized void handleFormElements(List<FormInput> formInputs) {

		/* If there are no form elements, there is nothing to do. */
		if (formInputs.isEmpty())
			return;

		/* First fill in the data from previous sessions through
		 * InputSpecification or forms.json */
		super.handleFormElements(formInputs);

		/* If there are form inputs that we haven't seen, pause the crawl and
		 * request user input. */
		if (incomplete(formInputs))
			pauseAndTrainModal(formInputs);

	}

	/**
	 * Checks if the forms on the page are complete.
	 * To invoke a training pause, an element must exist in the DOM such that:
	 * 1. The element is not in the map of visited elements.
	 * 2. The element is visible
	 *
	 * @return true if there are input elements in the DOM that the trainer
	 * has not seen yet.
	 */
	private boolean incomplete(List<FormInput> formInputs) {

		for (FormInput input : formInputs) {

			/* Is the element in the map of visited elements? */
			if (!visited.contains(input.getIdentification())) {

				/* Is the element visible? */
				WebElement inputElement = browser.getWebElement(input.getIdentification());
				if (!inputElement.getAttribute("type").equalsIgnoreCase("hidden")
						&& inputElement.isDisplayed())
					return true;

			}

		}

		return false;

	}

	/**
	 * Pauses the crawl for manual form input. After the user is finished, input formInputs are
	 * stored and shared across handlers in the static map {@code TrainingFormHandler.formInputs}.
	 *
	 * @param formInputs The input elements in the current DOM.
	 */
	private void pauseAndTrainModal(List<FormInput> formInputs) {

		/* If we are doing a training crawl, allow the user to edit remaining forms. */
		WebDriver driver = browser.getWebDriver();
		driver.manage().timeouts().setScriptTimeout(180, TimeUnit.SECONDS);

		String js = "";

		/* Inject the modal notification. */
		js += "function addStyleString(str) {";
		js += "	var node = document.createElement('style');";
		js += "	node.innerHTML = str;";
		js += "	document.body.appendChild(node);";
		js += "}";

		js += "function addHTMLString(str) {";
		js += "	var modal = document.createElement('div');";
		js += "	modal.setAttribute('id', 'myModal');";
		js += "	modal.setAttribute('class', 'modal');";
		js +=
				" modal.setAttribute('style', 'display:none;position:fixed;z-index:1;left:0;top:0;width:100%;height:100%;overflow:auto;background-color:rgb(0,0,0);background-color:rgba(0,0,0,0.4)');";
		js += "	modal.innerHTML = str;";
		js += "	document.body.appendChild(modal);";
		js += "}";

		js += "addHTMLString(\"" + MODAL_HTML + "\");";

		js += "var modal = document.getElementById('myModal');";
		js += "var span = document.getElementsByClassName('close')[0];";

		js += "span.onclick = function() {";
		js += "	modal.style.display = 'none';";
		js += "};";

		js += "window.onclick = function(event) {";
		js += "	if (event.target == modal) {";
		js += "		modal.style.display = 'none';";
		js += "	}";
		js += "};";

		js += "modal.style.display = 'block';";

		/* Inject the callback and continuation keys. */
		js += "var callback = arguments[arguments.length - 1];";
		js += "var title = document.title;";
		js += "document.onkeydown = function(e) {";
		js += "if(e.keyCode === 112) {";
		js += "document.title = title;";
		js += "setTimeout(callback, 1);";
		js += "}";
		js += "}";

		JavascriptExecutor executor = (JavascriptExecutor) driver;
		executor.executeAsyncScript(js);

		/*
		 * Save each FormInput element so the user does not have to enter them again.
		 */
		for (FormInput input : formInputs) {

			/* Create the InputValue for this element. */
			InputValue inputValue = getInputValue(input);

			/* Read the value from the DOM. */
			Set<InputValue> inputValues = new HashSet<>();
			inputValues.add(inputValue);

			/* The DOM value is the new input value. */
			input.inputValues(inputValues);

			/* Label the element as visited. */
			visited.add(input.getIdentification());

			/* Add this input value to the set. */
			formInputValueHelper.addTrainingInput(input.getIdentification(), input);

		}

	}

	/**
	 * Generates the InputValue for the form input by inspecting the current
	 * value of the corresponding WebElement on the DOM.
	 *
	 * @return The current InputValue for the element on the DOM.
	 */
	private InputValue getInputValue(FormInput input) {

		/* Get the DOM element from Selenium. */
		WebElement inputElement = browser.getWebElement(input.getIdentification());

		switch (input.getType()) {
			case TEXT:
			case PASSWORD:
			case HIDDEN:
			case SELECT:
			case TEXTAREA:
				return new InputValue(inputElement.getAttribute("value"));
			case RADIO:
			case CHECKBOX:
			default:
				String value = inputElement.getAttribute("value");
				Boolean checked = inputElement.isSelected();
				return new InputValue(value, checked);
		}

	}

}


text:
var expect = require('chai').expect;
var gama = require('../src/gama');

describe('gama.dot', function() {

  it('calculates the dot product of two vectors', function() {
    expect(gama.dot(gama.Vector(3.6, 4.8), gama.Vector(3, 4))).to.be.equal(30);
  });

});


text:
package org.wso2.examples.accounts.dataservice.resources;

import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import io.swagger.annotations.Contact;
import io.swagger.annotations.Info;
import io.swagger.annotations.License;
import io.swagger.annotations.SwaggerDefinition;
import org.osgi.framework.BundleContext;
import org.osgi.framework.FrameworkUtil;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Deactivate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.wso2.examples.accounts.dataservice.beans.Account;
import org.wso2.examples.accounts.dataservice.beans.User;
import org.wso2.examples.accounts.dataservice.dao.AccountRepository;
import org.wso2.msf4j.Microservice;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Properties;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;

/**
 * Annotated Resource class.
 */
@Component(
        name = "AccountResource",
        service = Microservice.class,
        immediate = true
)
@Path("/accounts")
@SwaggerDefinition(
        info = @Info(
                title = "Account Resource Swagger Definition",
                version = "1.0.0",
                description = "Accesses accounts in the database",
                license = @License(
                        name = "Apache 2.0",
                        url = "http://www.apache.org/licenses/LICENSE-2.0"),
                contact = @Contact(
                        name = "Vidura Nanayakkara",
                        email = "vidura_nanayakkara@hotmail.com",
                        url = "http://wso2.com"
                )
        )
)
public class AccountResource implements Microservice {

    /**
     * Logger for logging AccountResource information.
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(
            AccountResource.class
    );

    /**
     * User repository reference.
     */
    private AccountRepository accounts;

    /**
     * Operations to perform when the bundle is activated.
     *
     * @param bundleContext bundle context
     */
    @Activate
    protected void activate(BundleContext bundleContext) {
        LOGGER.info("Account resource bundle activated successfully");
    }

    /**
     * Operations to perform when the bundle is activated.
     *
     * @param bundleContext bundle context
     */
    @Deactivate
    protected void deactivate(BundleContext bundleContext) {
        LOGGER.info("Account resource bundle deactivated successfully");
    }

    /**
     * AccountResource constructor.
     */
    public AccountResource() {

        String entityManagerFactoryName = "org.wso2.examples.accounts.dataservice";
        String fileName =
                "configuration/configuration.properties";

        BundleContext context = FrameworkUtil.getBundle(AccountResource.class).getBundleContext();
        URL configURL = context.getBundle().getEntry(fileName);
        Properties properties = new Properties();

        if (configURL != null) {
            try {
                InputStream input = configURL.openStream();
                properties.load(input);
                input.close();
            } catch (IOException e) {
                LOGGER.error(e.getMessage());
            }
        }

        EntityManagerFactory emfactory =
                Persistence.createEntityManagerFactory(entityManagerFactoryName, properties);

        this.accounts = new AccountRepository(emfactory);
    }

    /**
     * Add an account to the database.
     *
     * @param username     String
     * @param emailaddress String
     * @param pass         String
     * @return Response
     */
    @POST
    @Path("/username/{username}/emailaddress/{emailaddress}/pass/{pass}")
    @Produces({"application/json", "text/xml"})
    @ApiOperation(
            value = "Adds an account to the database"
    )
    @ApiResponses(value = {
            @ApiResponse(
                    code = 202,
                    message = "Account added successfully"
            )
    })
    public Response addAccount(@PathParam("username") String username,
                               @PathParam("emailaddress") String emailaddress,
                               @PathParam("pass") String pass) {

        User user = new User(username, emailaddress, pass);

        Account account = new Account(user);
        accounts.createAccount(account);

        LOGGER.info("Account added to the database successfully");

        return Response.accepted().build();
    }

    /**
     * Get an account from the database.
     *
     * @param id integer
     * @return Response account object
     */
    @GET
    @Path("/{id}")
    @Produces({"application/json", "text/xml"})
    @ApiOperation(
            value = "Gets an account from the database"
    )
    @ApiResponses(value = {
            @ApiResponse(
                    code = 202,
                    message = "Account found"
            ),
            @ApiResponse(
                    code = 404,
                    message = "Account not found"
            )
    })
    public Response getAccount(@PathParam("id") int id) {

        Account account = accounts.findAccount(id);

        if (account != null) {

            LOGGER.info(
                    new StringBuilder()
                            .append("Account ")
                            .append(id)
                            .append(" is located")
                            .toString()
            );

            return Response.status(Response.Status.ACCEPTED)
                    .entity(account).build();
        }

        LOGGER.info(
                new StringBuilder()
                        .append("Account ")
                        .append(id)
                        .append(" is not located")
                        .toString()
        );

        return Response.status(Response.Status.NOT_FOUND).build();
    }

    /**
     * Deletes an account from the database.
     *
     * @param id integer
     * @return Response account object
     */
    @DELETE
    @Path("/{id}")
    @Produces({"application/json", "text/xml"})
    @ApiOperation(
            value = "Deletes an account from the database"
    )
    @ApiResponses(value = {
            @ApiResponse(
                    code = 202,
                    message = "Account removed from the database"
            ),
            @ApiResponse(
                    code = 404,
                    message = "Account not found"
            )
    })
    public Response deleteAccount(@PathParam("id") int id) {

        Account account = accounts.findAccount(id);

        if (account != null) {

            accounts.removeAccount(account);

            LOGGER.info(
                    new StringBuilder()
                            .append("Account ")
                            .append(id)
                            .append(" is deleted")
                            .toString()
            );

            return Response.status(Response.Status.ACCEPTED)
                    .entity(account).build();
        }

        LOGGER.info(
                new StringBuilder()
                        .append("Account ")
                        .append(id)
                        .append(" is not located")
                        .toString()
        );

        return Response.status(Response.Status.NOT_FOUND).build();
    }

    /**
     * Gets all the accounts from the database.
     *
     * @return Response accounts list
     */
    @GET
    @Path("/")
    @Produces({"application/json", "text/xml"})
    @ApiOperation(
            value = "Gets all the accounts from the database"
    )
    @ApiResponses(value = {
            @ApiResponse(
                    code = 202,
                    message = "List of accounts found in the database"
            )
    })
    public Response getAccounts() {

        LOGGER.info("Getting all accounts...");

        return Response.status(Response.Status.ACCEPTED)
                .entity(accounts.findAccounts()).build();
    }
}


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<servico>
    <titulo>Cadastro, Consulta e Cancelamento – Procuração via e-CAC (centro virtual de atendimento da Receita)</titulo>
    <descricao>
        <![CDATA[Possuidor de certificado digital cadastrar procuração eletrônica para terceiro, também possuidor de certificado digital, para realização de serviços dentro do Portal e-CAC. Consultar procuração eletrônica por outorgante ou por procurador. Cancelar procuração eletrônica.]]>
    </descricao>
    <requisitos/>
    <etapas></etapas>
    <canaisPrestacaoServico>
        <canalPrestacaoServico>
            <tipoCanalPrestacaoServico>
                <titulo>Web</titulo>
            </tipoCanalPrestacaoServico>
            <descricao>Endereço eletrônico do serviço</descricao>
            <url>https://cav.receita.fazenda.gov.br/eCAC/publico/login.aspx?sistema=05020</url>
        </canalPrestacaoServico>
    </canaisPrestacaoServico>
    <taxa></taxa>
    <informacoesUteis/>
    <compromissosAtendimento></compromissosAtendimento>
    <legislacoes></legislacoes>
    <palavrasChave></palavrasChave>
    <orgaoResponsavel>
        <titulo>Receita Federal</titulo>
    </orgaoResponsavel>
    <orgaoPrestador>
        <titulo>Receital Federal</titulo>
        <endereco></endereco>
        <telefone></telefone>
    </orgaoPrestador>
    <publicosAlvo>
        <publicoAlvo>
            <titulo>Serviços aos cidadãos</titulo>
            <linhasDaViva>
                <linhaDaVida>
                    <titulo>Meu negócio</titulo>
                    <eventoslinhaDaVida>
                        <eventolinhaDaVida>
                            <titulo>Pagar impostos</titulo>
                        </eventolinhaDaVida>
                    </eventoslinhaDaVida>
                </linhaDaVida>
            </linhasDaViva>
        </publicoAlvo>
        <publicoAlvo>
            <titulo>Serviços às empresas</titulo>
            <linhasDaViva>
                <linhaDaVida>
                    <titulo>Meu Negócio</titulo>
                    <eventoslinhaDaVida>
                        <eventolinhaDaVida>
                            <titulo>Pagar impostos</titulo>
                        </eventolinhaDaVida>
                    </eventoslinhaDaVida>
                </linhaDaVida>
            </linhasDaViva>
        </publicoAlvo>
    </publicosAlvo>
    <areasInteresse>
        <area>
            <titulo>Economia e Finanças</titulo>
        </area>
    </areasInteresse>
</servico>


text:
use std::time::Duration;

use quire::validate::{Structure, Scalar, Enum, Numeric, Nothing};
use quire::validate::{Sequence};

#[derive(Deserialize, Debug, PartialEq, Eq)]
#[allow(non_camel_case_types)]
pub enum LoadBalancing {
    queue,
}

#[derive(Deserialize, Debug, PartialEq, Eq)]
pub struct Destination {
    pub load_balancing: LoadBalancing,
    pub queue_size_for_503: usize,
    pub backend_connections_per_ip_port: u32,
    pub in_flight_requests_per_backend_connection: usize,
    pub addresses: Vec<String>,
    #[serde(with="::quire::duration")]
    pub keep_alive_timeout: Duration,
    #[serde(with="::quire::duration")]
    pub max_request_timeout: Duration,
    #[serde(with="::quire::duration")]
    pub safe_pipeline_timeout: Duration,
    pub override_host_header: Option<String>,
    pub request_id_header: Option<String>,
}

pub fn validator<'x>() -> Structure<'x> {
    Structure::new()
    .member("load_balancing", Enum::new()
        .option("queue", Nothing)
        .allow_plain()
        .plain_default("queue"))
    .member("queue_size_for_503",
        Numeric::new().min(0).max(1 << 32).default(100_000))
    .member("backend_connections_per_ip_port",
        Numeric::new().min(1).max(100_000).default(100))
    .member("in_flight_requests_per_backend_connection",
        Numeric::new().min(1).max(1000).default(2))
    .member("addresses", Sequence::new(Scalar::new()).min_length(1))
    .member("keep_alive_timeout", Scalar::new().default("4 sec"))
    .member("max_request_timeout", Scalar::new().default("30 secs"))
    .member("safe_pipeline_timeout", Scalar::new().default("300 ms"))
    .member("override_host_header", Scalar::new().optional())
    .member("request_id_header", Scalar::new().optional())
}


text:
'use strict';

const models = require('./index');

/**
 * A lab.
 *
 * @extends models['Resource']
 */
class Lab extends models['Resource'] {
  /**
   * Create a Lab.
   * @member {string} [defaultStorageAccount] The lab's default storage
   * account.
   * @member {string} [defaultPremiumStorageAccount] The lab's default premium
   * storage account.
   * @member {string} [artifactsStorageAccount] The lab's artifact storage
   * account.
   * @member {string} [premiumDataDiskStorageAccount] The lab's premium data
   * disk storage account.
   * @member {string} [vaultName] The lab's Key vault.
   * @member {string} [labStorageType] Type of storage used by the lab. It can
   * be either Premium or Standard. Default is Premium. Possible values
   * include: 'Standard', 'Premium'
   * @member {date} [createdDate] The creation date of the lab.
   * @member {string} [premiumDataDisks] The setting to enable usage of premium
   * data disks.
   * When its value is 'Enabled', creation of standard or premium data disks is
   * allowed.
   * When its value is 'Disabled', only creation of standard data disks is
   * allowed. Possible values include: 'Disabled', 'Enabled'
   * @member {string} [provisioningState] The provisioning status of the
   * resource.
   * @member {string} [uniqueIdentifier] The unique immutable identifier of a
   * resource (Guid).
   */
  constructor() {
    super();
  }

  /**
   * Defines the metadata of Lab
   *
   * @returns {object} metadata of Lab
   *
   */
  mapper() {
    return {
      required: false,
      serializedName: 'Lab',
      type: {
        name: 'Composite',
        className: 'Lab',
        modelProperties: {
          id: {
            required: false,
            readOnly: true,
            serializedName: 'id',
            type: {
              name: 'String'
            }
          },
          name: {
            required: false,
            readOnly: true,
            serializedName: 'name',
            type: {
              name: 'String'
            }
          },
          type: {
            required: false,
            readOnly: true,
            serializedName: 'type',
            type: {
              name: 'String'
            }
          },
          location: {
            required: false,
            serializedName: 'location',
            type: {
              name: 'String'
            }
          },
          tags: {
            required: false,
            serializedName: 'tags',
            type: {
              name: 'Dictionary',
              value: {
                  required: false,
                  serializedName: 'StringElementType',
                  type: {
                    name: 'String'
                  }
              }
            }
          },
          defaultStorageAccount: {
            required: false,
            readOnly: true,
            serializedName: 'properties.defaultStorageAccount',
            type: {
              name: 'String'
            }
          },
          defaultPremiumStorageAccount: {
            required: false,
            readOnly: true,
            serializedName: 'properties.defaultPremiumStorageAccount',
            type: {
              name: 'String'
            }
          },
          artifactsStorageAccount: {
            required: false,
            readOnly: true,
            serializedName: 'properties.artifactsStorageAccount',
            type: {
              name: 'String'
            }
          },
          premiumDataDiskStorageAccount: {
            required: false,
            readOnly: true,
            serializedName: 'properties.premiumDataDiskStorageAccount',
            type: {
              name: 'String'
            }
          },
          vaultName: {
            required: false,
            readOnly: true,
            serializedName: 'properties.vaultName',
            type: {
              name: 'String'
            }
          },
          labStorageType: {
            required: false,
            serializedName: 'properties.labStorageType',
            type: {
              name: 'String'
            }
          },
          createdDate: {
            required: false,
            readOnly: true,
            serializedName: 'properties.createdDate',
            type: {
              name: 'DateTime'
            }
          },
          premiumDataDisks: {
            required: false,
            serializedName: 'properties.premiumDataDisks',
            type: {
              name: 'String'
            }
          },
          provisioningState: {
            required: false,
            serializedName: 'properties.provisioningState',
            type: {
              name: 'String'
            }
          },
          uniqueIdentifier: {
            required: false,
            serializedName: 'properties.uniqueIdentifier',
            type: {
              name: 'String'
            }
          }
        }
      }
    };
  }
}

module.exports = Lab;


text:
import {URL} from './AppSettings.js'
import {getAndLogErrorMessage} from './AjaxErrorMessage.js'

export function fetchPredictionSettings(onData, onError) {
    $.ajax({
        url: URL.settings,
        dataType: 'json',
        type: 'GET',
        cache: false,
        success: function (data) {
            onData(data.genomes, data.maxBindingOffset);
        }.bind(this),
        error: function (xhr, status, err) {
            let message = getAndLogErrorMessage('fetching genome metadata', xhr, status, err);
            onError(message);
        }.bind(this)
    });
}


text:
<!DOCTYPE html>

	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	<meta name="generator" content="ApiGen 2.6.1" />

	<title>Class DibiNetteExtension | Dibi 2.0.2 API documentation</title>

	<link rel="stylesheet" type="text/css" media="all" href="resources/style.css?1321461267" />
	<link rel="search" type="application/opensearchdescription+xml" title="Dibi 2.0.2 API documentation" href="http://api.dibiphp.com/2.0/opensearch.xml" />

Packages

dibi

drivers

nette

reflection

None

PHP

Classes

DibiNetteExtension

DibiNettePanel

	<form action="http://www.google.com/cse" id="search">
		<input type="hidden" name="cx" value="011549293477758430224:x_apk4yrmjm" />
		<input type="hidden" name="ie" value="UTF-8" />
		<input type="hidden" name="more" value="api" />
		<input type="text" name="q" class="text" />
		<input type="submit" value="Search" />
	</form>

				Overview

				Package

Class

				Tree

Class DibiNetteExtension

Dibi extension for Nette Framework. Creates 'connection' service.

Nette\Config\CompilerExtension

DibiNetteExtension

		Package: dibi\nette

				Author:
				David Grudl

				Phpversion:
				5.3

		Located at Nette/DibiNetteExtension.php

Methods summary

			 public

		#
		loadConfiguration( )

		Dibi 2.0.2 API documentation API documentation generated by ApiGen 2.6.1


text:
import { Injectable }    from '@angular/core';
import { Headers, Http, RequestOptions } from '@angular/http';

import { GreensService } from './greens.service';
import { PreferencesService } from './preferences.service';
import { ProgressBarService } from './progress-bar.service';
import { LoggerService } from './logger.service';

import { Erc } from 'app/classes/erc';

import 'rxjs/add/operator/toPromise';

@Injectable()
export class MintService {

  private progressBarId: string = '';

  constructor(
    private minter: GreensService,
    private preferenceService: PreferencesService,
    private barService: ProgressBarService,
    private log: LoggerService) {
      this.preferenceService.preferencesChange.subscribe(data => this.updatePreferences(data));
      this.updatePreferences(this.preferenceService.data);
  }

  public async arks(objects: any): Promise<any> {
    if (!this.preferenceService.data.minter || this.preferenceService.data.minter.endpoint === '') {
      this.log.warn("Minter preferences are not set so I can't mint any objects.");
      return Promise.resolve();
    }

    this.progressBarId = this.barService.newProgressBar(1, 'Minting Arks');
    let minted = 0;
    for (let object of objects) {
      try {
        await this.mintObject(object);
      }
      catch(err) {
        Promise.reject(err);
      }
      this.barService.setProgressBar(this.progressBarId, ((++minted) / objects.length));
    }

    this.barService.clearProgressBar(this.progressBarId);
    this.progressBarId = '';

    return Promise.resolve();
  }

  private mintObject(object: any): Promise<any> {
    if (object.do_ark) {
      return Promise.resolve();
    }
    let erc = new Erc(
      object.getFieldValue('dcterms.creator') || 'unknown',
      object.getFieldValue('dcterms.title'),
      object.getFieldValue('dc.date') || 'unknown'
    );
    return this.minter.mint(erc)
      .then((id) => {
        object.do_ark = id;
        object.setField('edm.isShownAt', id);
        return id;
      })
      .catch((err) => {
        this.log.error(err);
      });
  }

  private updatePreferences(data: any): void {
    this.minter.setEndpoint(data.minter.endpoint, data.minter.prefix);
    this.minter.setApiKey(data.minter.key);
  }

}


text:
namespace Apache.Ignite.Core.Datastream
{
    using System.Collections.Generic;
    using Apache.Ignite.Core.Binary;
    using Apache.Ignite.Core.Cache;
    using Apache.Ignite.Core.Impl.Binary;
    using Apache.Ignite.Core.Impl.Common;
    using Apache.Ignite.Core.Impl.Datastream;

    /// <summary>
    /// Convenience adapter to transform update existing values in streaming cache
    /// based on the previously cached value.
    /// </summary>
    /// <typeparam name="TK">Key type.</typeparam>
    /// <typeparam name="TV">Value type.</typeparam>
    /// <typeparam name="TArg">The type of the processor argument.</typeparam>
    /// <typeparam name="TRes">The type of the processor result.</typeparam>
    public sealed class StreamTransformer<TK, TV, TArg, TRes> : IStreamReceiver<TK, TV>,
        IBinaryWriteAware
    {
        /** Entry processor. */
        private readonly ICacheEntryProcessor<TK, TV, TArg, TRes> _proc;

        /// <summary>
        /// Initializes a new instance of the <see cref="StreamTransformer{K, V, A, R}"/> class.
        /// </summary>
        /// <param name="proc">Entry processor.</param>
        public StreamTransformer(ICacheEntryProcessor<TK, TV, TArg, TRes> proc)
        {
            IgniteArgumentCheck.NotNull(proc, "proc");

            _proc = proc;
        }

        /** <inheritdoc /> */
        public void Receive(ICache<TK, TV> cache, ICollection<ICacheEntry<TK, TV>> entries)
        {
            var keys = new List<TK>(entries.Count);

            foreach (var entry in entries)
                keys.Add(entry.Key);

            cache.InvokeAll(keys, _proc, default(TArg));
        }

        /** <inheritdoc /> */
        void IBinaryWriteAware.WriteBinary(IBinaryWriter writer)
        {
            var w = (BinaryWriter)writer;

            w.WriteByte(StreamReceiverHolder.RcvTransformer);

            w.WriteObject(_proc);
        }
    }
}


text:
package com.astoev.cave.survey.activity.draw;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.PorterDuff;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;

import com.astoev.cave.survey.Constants;
import com.astoev.cave.survey.R;
import com.astoev.cave.survey.activity.UIUtilities;

/**
 * Created by IntelliJ IDEA.
 * User: almondmendoza
 * Date: 07/11/2010
 * Time: 2:15 AM
 * Link: http://www.tutorialforandroid.com/
 */
public class DrawingSurface extends View {

    public DrawingPath previewPath;
    private Bitmap mOldBitmap;
    private CommandManager commandManager;

    public DrawingSurface(Context context, AttributeSet attrs) {
        super(context, attrs);

        commandManager = new CommandManager();

        // disable optimizations causing drawing path not visible
        setWillNotDraw(false);
    }

    @Override
    public void onDraw(Canvas aCanvas) {

        // need to call parent
        super.onDraw(aCanvas);

        try {
            drawOldBitmapAndCurrentPaths(aCanvas);
        } catch (Exception e) {
            Log.e(Constants.LOG_TAG_UI, "Failed to draw", e);
            UIUtilities.showNotification(R.string.error);
        }

    }

    private void drawOldBitmapAndCurrentPaths(Canvas aCanvas) {
        aCanvas.drawColor(0, PorterDuff.Mode.CLEAR);

        // old bitmap, e.g. map below the drawing
        if (mOldBitmap != null) {
            int left = (aCanvas.getWidth() - mOldBitmap.getWidth()) / 2;
            int top = (aCanvas.getHeight() - mOldBitmap.getHeight()) / 2;
            aCanvas.drawBitmap(mOldBitmap, left, top, null);
        }

        // user notes above
        commandManager.executeAll(aCanvas);
        previewPath.draw(aCanvas);
    }

    public void addDrawingPath(DrawingPath drawingPath) {
        commandManager.addCommand(drawingPath);
    }

    public boolean hasMoreRedo() {
        return commandManager.hasMoreRedo();
    }

    public void redo() {
        commandManager.redo();
    }

    public void undo() {
        commandManager.undo();
    }

    public boolean hasMoreUndo() {
        return commandManager.hasMoreUndo();
    }

    public Bitmap getBitmap() {

        // repeat the drawing in a buffer and return to be saved
        Bitmap bitmap = Bitmap.createBitmap(getWidth(), getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        drawOldBitmapAndCurrentPaths(canvas);
        return bitmap;
    }

    public Bitmap getOldBitmap() {
        return mOldBitmap;
    }

    public void setOldBitmap(Bitmap aOldBitmap) {
        mOldBitmap = aOldBitmap;
    }

}


text:
angular.module('PetShelterController', ['ngRoute', 'ngCookies', 'PetFinder', 'ImageArray', 'PetModel'])

.controller('PetShelterController',
['$scope', '$filter', '$document', '$timeout', '$route', '$routeParams', '$location', '$cookies', 'petfinder', 'imageArray', 'petmodel',

function ($scope, $filter, $document, $timeout, $route, $routeParams, $location, $cookies, petfinder,
 ImageArray, petmodel) {

  $scope.shelters = petmodel.shelters;

  $scope.find = function () {
    if (!$scope.location || $scope.location.length < 5) return;

    $scope.showspinner = true;
    var callback = function (data) {
      if (!data || !data.petfinder || !data.petfinder.shelters || !data.petfinder.shelters.shelter) {
        try {
          $scope.message = data.petfinder.header.status.message.$t;
        } catch (e) {
          $scope.message = "No pets found in that area";
        }
        petmodel.shelters.value = [];
      }
      else {
        $scope.message = undefined;
        petmodel.shelters.value = data.petfinder.shelters.shelter;
      }
      // use timeout because cached hits are too fast and this will wait until content is loaded
      $timeout(function () {
        $scope.showspinner = false;
        $scope.initTooltips();
      }, 0);
    };
    petfinder.findShelters({ 'location': $scope.location }, callback);
  };

  $scope.find();

} ]);


text:
var PORT = 3231;

console.log('Server started at port ' + PORT + '...');
var Locker = require('locker-server'),
  locker = new Locker();

locker.listen(PORT);


text: Implementation of the xUnit framework described in the book Test Driven Development by Kent Beck


text:
package apple.foundation.enums;

import org.moe.natj.general.ann.Generated;
import org.moe.natj.general.ann.NUInt;

/**
 * Options for use with -addObserver:forKeyPath:options:context: and
 * -addObserver:toObjectsAtIndexes:forKeyPath:options:context:.
 */
@Generated
public final class NSKeyValueObservingOptions {
    /**
     * Whether the change dictionaries sent in notifications should contain NSKeyValueChangeNewKey and
     * NSKeyValueChangeOldKey entries, respectively.
     */
    @Generated @NUInt public static final long New = 0x0000000000000001L;
    /**
     * Whether the change dictionaries sent in notifications should contain NSKeyValueChangeNewKey and
     * NSKeyValueChangeOldKey entries, respectively.
     */
    @Generated @NUInt public static final long Old = 0x0000000000000002L;
    /**
     * Whether a notification should be sent to the observer immediately, before the observer registration method even
     * returns. The change dictionary in the notification will always contain an NSKeyValueChangeNewKey entry if
     * NSKeyValueObservingOptionNew is also specified but will never contain an NSKeyValueChangeOldKey entry. (In an
     * initial notification the current value of the observed property may be old, but it's new to the observer.) You
     * can use this option instead of explicitly invoking, at the same time, code that is also invoked by the observer's
     * -observeValueForKeyPath:ofObject:change:context: method. When this option is used with
     * -addObserver:toObjectsAtIndexes:forKeyPath:options:context: a notification will be sent for each indexed object
     * to which the observer is being added.
     */
    @Generated @NUInt public static final long Initial = 0x0000000000000004L;
    /**
     * Whether separate notifications should be sent to the observer before and after each change, instead of a single
     * notification after the change. The change dictionary in a notification sent before a change always contains an
     * NSKeyValueChangeNotificationIsPriorKey entry whose value is [NSNumber numberWithBool:YES], but never contains an
     * NSKeyValueChangeNewKey entry. You can use this option when the observer's own KVO-compliance requires it to
     * invoke one of the -willChange... methods for one of its own properties, and the value of that property depends on
     * the value of the observed object's property. (In that situation it's too late to easily invoke -willChange...
     * properly in response to receiving an -observeValueForKeyPath:ofObject:change:context: message after the change.)
     * <p>
     * When this option is specified, the change dictionary in a notification sent after a change contains the same
     * entries that it would contain if this option were not specified, except for ordered unique to-many relationships
     * represented by NSOrderedSets. For those, for NSKeyValueChangeInsertion and NSKeyValueChangeReplacement changes,
     * the change dictionary for a will-change notification contains an NSKeyValueChangeIndexesKey (and
     * NSKeyValueChangeOldKey in the case of Replacement where the NSKeyValueObservingOptionOld option was specified at
     * registration time) which give the indexes (and objects) which *may* be changed by the operation. The second
     * notification, after the change, contains entries reporting what did actually change. For NSKeyValueChangeRemoval
     * changes, removals by index are precise.
     */
    @Generated @NUInt public static final long Prior = 0x0000000000000008L;

    @Generated
    private NSKeyValueObservingOptions() {
    }
}


text:
<!DOCTYPE html>

<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="/css/style.css">

<meta property="fb:pages" content="267523766781017" />
<title>Abused and Discriminated Against Yet Thriving and Proud</title>
<link rel="canonical" href="https://www.allamericanmuslim.com/amanda-morris/">
<meta property="og:locale" content="en-us">
<meta property="og:title" content="Abused and Discriminated Against Yet Thriving and Proud">
<meta property="og:site_name" content="All American Muslim">
<meta property="og:description" content="Amanda Morris from Wales">
<meta property="og:url" content="https://www.allamericanmuslim.com/amanda-morris/">

    <meta property="og:image" content="/images/amanda-morris.jpg">

<meta property="og:type" content="article">

<meta property="fb:app_id" content="347123062352978">
<meta http-equiv="cleartype" content="on">
<meta name="description" content="Amanda Morris from Wales">

All American Muslim

Home

DMCA

Abused and Discriminated Against Yet Thriving and Proud

   Share on Facebook

Amanda Morris converted to Islam when she was 25 years old. Originally from Canada she now lives outside of Cardiff, UK. She mentors young girls who recently embraced Islam. Because of her faith she has been facing so much abuse from her neighbors and she says that is forcing her to move from the area.

“She’s as white as her neighbours are, but just because she’s started wearing a headscarf she’s suddenly an object to hate… It’s like she can’t step out of her door without these people threatening her life,” said a friend of hers.

Amanda has a bubbly personality but when she speaks about the troubles that the young girls are facing, she becomes visibly defensive. These girls are going through the same experience that she went through 30 years ago, but hers was during more tolerant times.

“There’s a couple of girls who quite simply keep [their conversion] a secret from their parents because they would get thrown out of their own homes,” she said.

“You could become literally any other religion and your family would be like ‘Well, it’s your choice’. But the minute you become Muslim, it’s suddenly like ‘How could you?’.”

Public attitudes to Islam scare her.

“Here at work, I’ve had a teacher in a town outside of Cardiff that had planned a school trip to Cardiff to visit a mosque and a synagogue. Thirty per cent of the parents withdrew their children from the school visit because they didn’t want them visiting the mosque,” she said.

People in all walks of life who are Muslim in Wales tell a similar story.

The chairman of the South Wales Islamic Centre on Alice Street in Butetown, Cardiff, Mr Daoud Salama said “Our women get treated badly when they're out if they're covered, It's not very nice for them. They spit at them. They call them names. They do all kinds of things. The women weren't causing any trouble, and they come home and they're upset but it doesn't go any further.”

Despite the hostility towards Islam, a 2011 report by Swansea University for the think tank ‘Faith Matters’ found that thousands of mainly young white women were converting in the UK - and that the numbers had almost doubled to around 100,000 in 2010. Most are young with an average age of 28.

   Share on Facebook