text:
package org.apache.hadoop.hdfs.server.datanode;

import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_BLOCKREPORT_INITIAL_DELAY_DEFAULT;
import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_BLOCKREPORT_INITIAL_DELAY_KEY;
import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_BLOCKREPORT_INTERVAL_MSEC_DEFAULT;
import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_BLOCKREPORT_INTERVAL_MSEC_KEY;
import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_CLIENT_SOCKET_TIMEOUT_KEY;
import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_CLIENT_WRITE_PACKET_SIZE_DEFAULT;
import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_CLIENT_WRITE_PACKET_SIZE_KEY;
import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_DATANODE_SOCKET_WRITE_TIMEOUT_KEY;
import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_DATANODE_SYNCONCLOSE_DEFAULT;
import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_DATANODE_SYNCONCLOSE_KEY;
import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_DATANODE_TRANSFERTO_ALLOWED_DEFAULT;
import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_DATANODE_TRANSFERTO_ALLOWED_KEY;
import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_HEARTBEAT_INTERVAL_DEFAULT;
import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_HEARTBEAT_INTERVAL_KEY;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hdfs.DFSConfigKeys;
import org.apache.hadoop.hdfs.server.common.HdfsServerConstants;

/**
 * Simple class encapsulating all of the configuration that the DataNode
 * loads at startup time.
 */
class DNConf {
  final int socketTimeout;
  final int socketWriteTimeout;
  final int socketKeepaliveTimeout;

  final boolean transferToAllowed;
  final boolean dropCacheBehindWrites;
  final boolean syncBehindWrites;
  final boolean dropCacheBehindReads;
  final boolean syncOnClose;

  final long readaheadLength;
  final long heartBeatInterval;
  final long blockReportInterval;
  final long deleteReportInterval;
  final long initialBlockReportDelay;
  final int writePacketSize;

  public DNConf(Configuration conf) {
    socketTimeout = conf.getInt(DFS_CLIENT_SOCKET_TIMEOUT_KEY,
        HdfsServerConstants.READ_TIMEOUT);
    socketWriteTimeout = conf.getInt(DFS_DATANODE_SOCKET_WRITE_TIMEOUT_KEY,
        HdfsServerConstants.WRITE_TIMEOUT);
    socketKeepaliveTimeout = conf.getInt(
        DFSConfigKeys.DFS_DATANODE_SOCKET_REUSE_KEEPALIVE_KEY,
        DFSConfigKeys.DFS_DATANODE_SOCKET_REUSE_KEEPALIVE_DEFAULT);

    /* Based on results on different platforms, we might need set the default
     * to false on some of them. */
    transferToAllowed = conf.getBoolean(
        DFS_DATANODE_TRANSFERTO_ALLOWED_KEY,
        DFS_DATANODE_TRANSFERTO_ALLOWED_DEFAULT);

    writePacketSize = conf.getInt(DFS_CLIENT_WRITE_PACKET_SIZE_KEY,
        DFS_CLIENT_WRITE_PACKET_SIZE_DEFAULT);

    readaheadLength = conf.getLong(
        DFSConfigKeys.DFS_DATANODE_READAHEAD_BYTES_KEY,
        DFSConfigKeys.DFS_DATANODE_READAHEAD_BYTES_DEFAULT);
    dropCacheBehindWrites = conf.getBoolean(
        DFSConfigKeys.DFS_DATANODE_DROP_CACHE_BEHIND_WRITES_KEY,
        DFSConfigKeys.DFS_DATANODE_DROP_CACHE_BEHIND_WRITES_DEFAULT);
    syncBehindWrites = conf.getBoolean(
        DFSConfigKeys.DFS_DATANODE_SYNC_BEHIND_WRITES_KEY,
        DFSConfigKeys.DFS_DATANODE_SYNC_BEHIND_WRITES_DEFAULT);
    dropCacheBehindReads = conf.getBoolean(
        DFSConfigKeys.DFS_DATANODE_DROP_CACHE_BEHIND_READS_KEY,
        DFSConfigKeys.DFS_DATANODE_DROP_CACHE_BEHIND_READS_DEFAULT);

    this.blockReportInterval = conf.getLong(DFS_BLOCKREPORT_INTERVAL_MSEC_KEY,
    DFS_BLOCKREPORT_INTERVAL_MSEC_DEFAULT);

    long initBRDelay = conf.getLong(
        DFS_BLOCKREPORT_INITIAL_DELAY_KEY,
        DFS_BLOCKREPORT_INITIAL_DELAY_DEFAULT) * 1000L;
    if (initBRDelay >= blockReportInterval) {
      initBRDelay = 0;
      DataNode.LOG.info("dfs.blockreport.initialDelay is greater than " +
          "dfs.blockreport.intervalMsec." + " Setting initial delay to 0 msec:");
    }
    initialBlockReportDelay = initBRDelay;

    heartBeatInterval = conf.getLong(DFS_HEARTBEAT_INTERVAL_KEY,
        DFS_HEARTBEAT_INTERVAL_DEFAULT) * 1000L;

    this.deleteReportInterval = 100 * heartBeatInterval;
    // do we need to sync block file contents to disk when blockfile is closed?
    this.syncOnClose = conf.getBoolean(DFS_DATANODE_SYNCONCLOSE_KEY,
        DFS_DATANODE_SYNCONCLOSE_DEFAULT);

  }
}

redpajama_set_name: RedPajamaGithub


text:
package mesosphere.marathon.core.externalvolume.impl

import mesosphere.marathon.core.externalvolume.impl.providers.DVDIProvider

/**
  * StaticExternalVolumeProviderRegistry is a fixed, precomputed storage provider registry
  */
protected[externalvolume] object StaticExternalVolumeProviderRegistry extends ExternalVolumeProviderRegistry {
  def make(prov: ExternalVolumeProvider*): Map[String, ExternalVolumeProvider] =
    prov.map(p => p.name -> p).toMap

  val registry = make(
    // list supported providers here; all MUST provide a non-empty "name" trait
    DVDIProvider
  )

  override def get(name: String): Option[ExternalVolumeProvider] = registry.get(name)

  override def all: Iterable[ExternalVolumeProvider] = registry.values
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Proc. Linn. Soc. N. S. W. 78: 59 (1953)

#### Original name
Meliola prostantherae Hansf.

### Remarks
null


text:
package io.crate.execution.engine.join;

import com.carrotsearch.randomizedtesting.RandomizedRunner;
import com.carrotsearch.randomizedtesting.annotations.Name;
import com.carrotsearch.randomizedtesting.annotations.ParametersFactory;
import com.carrotsearch.randomizedtesting.annotations.ThreadLeakScope;
import io.crate.breaker.RowAccounting;
import io.crate.data.BatchIterator;
import io.crate.data.Row;
import io.crate.data.join.CombinedRow;
import io.crate.testing.BatchIteratorTester;
import io.crate.testing.BatchSimulatingIterator;
import io.crate.testing.TestingBatchIterators;
import org.elasticsearch.common.breaker.CircuitBreaker;
import org.junit.Test;
import org.junit.runner.RunWith;

import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.function.Predicate;
import java.util.function.Supplier;
import java.util.function.ToIntFunction;

import static com.carrotsearch.randomizedtesting.RandomizedTest.$;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

@RunWith(RandomizedRunner.class)
@ThreadLeakScope(ThreadLeakScope.Scope.NONE)
public class HashInnerJoinBatchIteratorTest {

    private final CircuitBreaker circuitBreaker = mock(CircuitBreaker.class);
    private final List<Object[]> expectedResult;
    private final Supplier<BatchIterator<Row>> leftIterator;
    private final Supplier<BatchIterator<Row>> rightIterator;

    private static Predicate<Row> getCol0EqCol1JoinCondition() {
        return row -> Objects.equals(row.get(0), row.get(1));
    }

    private static ToIntFunction<Row> getHashForLeft() {
        return row -> Objects.hash(row.get(0));
    }

    private static ToIntFunction<Row> getHashForRight() {
        return row -> Objects.hash(row.get(0));
    }

    private static ToIntFunction<Row> getHashWithCollisions() {
        return row -> (Integer) row.get(0) % 3;
    }

    public HashInnerJoinBatchIteratorTest(@SuppressWarnings("unused") @Name("dataSetName") String testName,
                                          @Name("dataForLeft") Supplier<BatchIterator<Row>> leftIterator,
                                          @Name("dataForRight") Supplier<BatchIterator<Row>> rightIterator,
                                          @Name("expectedResult") List<Object[]> expectedResult) {
        this.leftIterator = leftIterator;
        this.rightIterator = rightIterator;
        this.expectedResult = expectedResult;
        when(circuitBreaker.getLimit()).thenReturn(110L);
        when(circuitBreaker.getUsed()).thenReturn(10L);
    }

    @ParametersFactory
    public static Iterable<Object[]> testParameters() {
        List<Object[]> resultForUniqueValues = Arrays.asList(
            new Object[] { 2, 2 }, new Object[] { 3, 3 }, new Object[] { 4, 4 });
        List<Object[]> resultForDuplicateValues = Arrays.asList(
            new Object[] { 1, 1 }, new Object[] { 1, 1 },
            new Object[] { 2, 2 }, new Object[] { 2, 2 },
            new Object[] { 3, 3 },
            new Object[] { 4, 4 }, new Object[] { 4, 4 }, new Object[] { 4, 4 }, new Object[] { 4, 4 }
        );

        return Arrays.asList(
            $("UniqueValues-plain",
              (Supplier<BatchIterator<Row>>) () -> TestingBatchIterators.range(0, 5),
              (Supplier<BatchIterator<Row>>) () -> TestingBatchIterators.range(2, 6),
              resultForUniqueValues),
            $("UniqueValues-batchedSource",
              (Supplier<BatchIterator<Row>>) () ->
                  new BatchSimulatingIterator<>(TestingBatchIterators.range(0, 5), 2, 2, null),
              (Supplier<BatchIterator<Row>>) () ->
                  new BatchSimulatingIterator<>(TestingBatchIterators.range(2, 6), 2, 2, null),
              resultForUniqueValues),
            $("DuplicateValues-plain",
              (Supplier<BatchIterator<Row>>) () -> TestingBatchIterators.ofValues(Arrays.asList(0, 0, 1, 2, 2, 3, 4, 4)),
              (Supplier<BatchIterator<Row>>) () ->
                  TestingBatchIterators.ofValues(Arrays.asList(1, 1, 2, 3, 4, 4, 5, 5, 6)),
              resultForDuplicateValues),
            $("DuplicateValues-batchedSource",
              (Supplier<BatchIterator<Row>>) () ->
                  new BatchSimulatingIterator<>(
                      TestingBatchIterators.ofValues(Arrays.asList(0, 0, 1, 2, 2, 3, 4, 4)), 2, 4, null),
              (Supplier<BatchIterator<Row>>) () -> new BatchSimulatingIterator<>(
                TestingBatchIterators.ofValues(Arrays.asList(1, 1, 2, 3, 4, 4, 5, 5, 6)), 2, 4, null),
              resultForDuplicateValues),
            $("DuplicateValues-leftLoadedRightBatched",
              (Supplier<BatchIterator<Row>>) () -> TestingBatchIterators.ofValues(Arrays.asList(0, 0, 1, 2, 2, 3, 4, 4)),
              (Supplier<BatchIterator<Row>>) () -> new BatchSimulatingIterator<>(
              TestingBatchIterators.ofValues(Arrays.asList(1, 1, 2, 3, 4, 4, 5, 5, 6)), 2, 4, null),
              resultForDuplicateValues));
    }

    @Test
    public void testInnerHashJoin() throws Exception {
        Supplier<BatchIterator<Row>> batchIteratorSupplier = () -> new HashInnerJoinBatchIterator(
            leftIterator.get(),
            rightIterator.get(),
            mock(RowAccounting.class),
            new CombinedRow(1, 1),
            getCol0EqCol1JoinCondition(),
            getHashForLeft(),
            getHashForRight(),
            () -> 5
        );
        BatchIteratorTester tester = new BatchIteratorTester(batchIteratorSupplier);
        tester.verifyResultAndEdgeCaseBehaviour(expectedResult);
    }

    @Test
    public void testInnerHashJoinWithHashCollisions() throws Exception {
        Supplier<BatchIterator<Row>> batchIteratorSupplier = () -> new HashInnerJoinBatchIterator(
            leftIterator.get(),
            rightIterator.get(),
            mock(RowAccounting.class),
            new CombinedRow(1, 1),
            getCol0EqCol1JoinCondition(),
            getHashWithCollisions(),
            getHashWithCollisions(),
            () -> 5
        );
        BatchIteratorTester tester = new BatchIteratorTester(batchIteratorSupplier);
        tester.verifyResultAndEdgeCaseBehaviour(expectedResult);
    }

    @Test
    public void testInnerHashJoinWithBlockSizeSmallerThanDataSet() throws Exception {
        Supplier<BatchIterator<Row>> batchIteratorSupplier = () -> new HashInnerJoinBatchIterator(
            leftIterator.get(),
            rightIterator.get(),
            mock(RowAccounting.class),
            new CombinedRow(1, 1),
            getCol0EqCol1JoinCondition(),
            getHashForLeft(),
            getHashForRight(),
            () -> 1
        );
        BatchIteratorTester tester = new BatchIteratorTester(batchIteratorSupplier);
        tester.verifyResultAndEdgeCaseBehaviour(expectedResult);
    }

    @Test
    public void testInnerHashJoinWithBlockSizeBiggerThanIteratorBatchSize() throws Exception {
        Supplier<BatchIterator<Row>> batchIteratorSupplier = () -> new HashInnerJoinBatchIterator(
            leftIterator.get(),
            rightIterator.get(),
            mock(RowAccounting.class),
            new CombinedRow(1, 1),
            getCol0EqCol1JoinCondition(),
            getHashForLeft(),
            getHashForRight(),
            () -> 3
        );
        BatchIteratorTester tester = new BatchIteratorTester(batchIteratorSupplier);
        tester.verifyResultAndEdgeCaseBehaviour(expectedResult);
    }
}


text:
import libcontext, bee
from bee.segments import *
from libcontext.socketclasses import *
from libcontext.pluginclasses import *

class collision(object):

    """The collision sensor reports collisions between a specific object and all other objects
    The other objects can be filtered by material, property or identifier"""

    metaguiparams = {
        "idmode": "str",
        "autocreate": {"idmode": "bound"},
    }

    @classmethod
    def form(cls, f):
        f.idmode.name = "ID mode"
        f.idmode.advanced = True
        f.idmode.type = "option"
        f.idmode.options = "unbound", "bound"
        f.idmode.default = "bound"
        f.idmode.optiontitles = "Unbound", "Bound"

    def __new__(cls, idmode):
        assert idmode in ("bound", "unbound"), idmode

        class collision(bee.worker):
            __doc__ = cls.__doc__

            if idmode == "unbound":
                identifier = antenna("pull", ("str", "identifier"))
                identifier_buffer = buffer("pull", ("str", "identifier"))
                connect(identifier, identifier_buffer)
                trigger_identifier_buffer = triggerfunc(identifier_buffer)

                @property
                def entity_name(self):
                    self.trigger_identifier_buffer()
                    return self.identifier_buffer

            # How are the collisions filtered?
            filter_mode = variable("str")
            parameter(filter_mode)

            #What is the value of the filter?
            filter_value = antenna("pull", "str")
            filter_buffer = buffer("pull", "str")
            connect(filter_value, filter_buffer)

            #Has a collision event happened during the last tick?
            is_active = variable("bool")
            startvalue(is_active, False)
            active = output("pull", "bool")
            connect(is_active, active)

            #What was the ID of the colliding object?
            collision_id_variable = variable(("str", "identifier"))
            collision_id = output("pull", ("str", "identifier"))
            connect(collision_id_variable, collision_id)

            trigger_filter_value = triggerfunc(filter_buffer)

            @staticmethod
            def form(f):
                f.filter_mode.name = "Filter mode"
                f.filter_mode.type = "option"
                f.filter_mode.default = "id"
                f.filter_mode.options = "material", "property", "id"
                f.filter_mode.optiontitles = "By material", "By property", "By ID"

            guiparams = {
                "identifier": {"name": "Identifier", "fold": True},
                "filter_value": {"name": "Filter value", "fold": True},
                "active": {"name": "Active"},
                "collision_id": {"name": "Collision ID", "advanced": True},
                "_memberorder": ["filter_value", "identifier", "collision_id", "active"],
                }

            if idmode == "unbound":
                def get_collisions(self):
                    return self.get_collisions_for(self.entity_name)

            def update_value(self):
                filter_func = self.get_filter_func()

                # Request filter value
                self.trigger_filter_value()
                filter_value = self.filter_buffer

                # Find a valid collision
                for collision_identifier in self.get_collisions():
                    if filter_func(collision_identifier, filter_value):
                        break
                else:
                    collision_identifier = None

                # Set outputs
                if collision_identifier is not None:
                    self.collision_id_variable = collision_identifier
                self.is_active = collision_identifier is not None

            def get_filter_func(self):
                """Find an appropriate filter function"""
                filter_mode = self.filter_mode
                if filter_mode == "material":
                    return self.match_material

                if filter_mode == "property":
                    return self.match_property

                if filter_mode == "id":
                    return self.match_identifier

            def match_material(self, entity_name, filter_value):
                """Determine if the entity has a matching material

                :param entity_name: name of filtered entity
                :param filter_value: required material name
                """

                try:
                    self.get_material(entity_name, filter_value)

                except KeyError:
                    return False

                return True

            @staticmethod
            def match_identifier(entity_name, filter_value):
                """Determine if the entity identifier matches the filter identifier

                :param entity_name: name of filtered entity
                :param filter_value: required entity identifier
                """
                return entity_name == filter_value

            def match_property(self, entity_name, filter_value):
                """Determine if the entity has a matching property

                :param entity_name: name of filtered entity
                :param filter_value: required property name
                """
                try:
                    self.get_property(entity_name, filter_value)

                except KeyError:
                    return False

                return True

            def enable(self):
                self.add_listener("trigger", self.update_value, "tick", priority=9)

            def set_get_collisions(self, get_collisions):
                self.get_collisions = get_collisions

            def set_get_collisions_for(self, get_collisions_for):
                self.get_collisions_for = get_collisions_for

            def set_get_property(self, get_property):
                self.get_property = get_property

            def set_get_entity(self, get_entity):
                self.get_entity = get_entity

            def set_get_material(self, get_material):
                self.get_material = get_material

            def place(self):
                if idmode == "bound":
                    libcontext.socket(("entity", "bound", "collisions"), socket_single_required(self.set_get_collisions))

                libcontext.socket(("entity", "collisions"), socket_single_required(self.set_get_collisions_for))
                libcontext.socket(("entity", "property", "get"), socket_single_required(self.set_get_property))
                libcontext.socket(("entity", "material", "get"), socket_single_required(self.set_get_property))

        return collision


text:
<?xml version="1.0" encoding="UTF-8"?>
<project-private xmlns="http://www.netbeans.org/ns/project-private/1">
    <editor-bookmarks xmlns="http://www.netbeans.org/ns/editor-bookmarks/2" lastBookmarkId="0"/>
    <open-files xmlns="http://www.netbeans.org/ns/projectui-open-files/2">
        <group>
            <file>file:/C:/Users/fred/Desktop/SAFE/SAFE/src/safe/views/Patient_View.java</file>
            <file>file:/C:/Users/fred/Desktop/SAFE/SAFE/src/safe/controllers/Patient_Controller.java</file>
            <file>file:/C:/Users/fred/Desktop/SAFE/SAFE/src/safe/views/Doctor_Table_View.java</file>
        </group>
    </open-files>
</project-private>


text:
<?php namespace SistemApi\Model;

use SistemApi\Model\Base\Model;

/**
 * @deprecated use Siparis\SiparisAdres
 *
 * @property int id
 * @property int site_id
 * @property int kullanici_id
 * @property string adi
 * @property string mail
 * @property string telefon
 * @property int ilce_id
 * @property string semt
 * @property string adres
 */
class UrunSiparisAdres extends Model
{

}


text:
//AUTOGENERATED, DO NOTMODIFY.
//Do not edit this file directly.

#pragma warning disable 1591
// ReSharper disable CheckNamespace

using System;
using RethinkDb.Driver.Ast;
using RethinkDb.Driver.Model;
using RethinkDb.Driver.Proto;
using System.Collections.Generic;

namespace RethinkDb.Driver.Ast {

    public class GetNearest : ReqlExpr {

///
/// <para>Get all documents where the specified geospatial index is within a certain distance of the specified point (default 100 kilometers).</para>
///
/// <example><para>Example: Return a list of enemy hideouts within 5000 meters of the secret base.</para>
/// var secretBase = r.point(-122.422876,37.777128);
/// r.table('hideouts').getNearest(secretBase,
///     {index: 'location', maxDist: 5000}
/// ).run(conn, callback)
/// </example>
        public GetNearest (object arg) : this(new Arguments(arg), null) {
        }
///
/// <para>Get all documents where the specified geospatial index is within a certain distance of the specified point (default 100 kilometers).</para>
///
/// <example><para>Example: Return a list of enemy hideouts within 5000 meters of the secret base.</para>
/// var secretBase = r.point(-122.422876,37.777128);
/// r.table('hideouts').getNearest(secretBase,
///     {index: 'location', maxDist: 5000}
/// ).run(conn, callback)
/// </example>
        public GetNearest (Arguments args) : this(args, null) {
        }
///
/// <para>Get all documents where the specified geospatial index is within a certain distance of the specified point (default 100 kilometers).</para>
///
/// <example><para>Example: Return a list of enemy hideouts within 5000 meters of the secret base.</para>
/// var secretBase = r.point(-122.422876,37.777128);
/// r.table('hideouts').getNearest(secretBase,
///     {index: 'location', maxDist: 5000}
/// ).run(conn, callback)
/// </example>
        public GetNearest (Arguments args, OptArgs optargs)
             : this(TermType.GET_NEAREST, args, optargs) {
        }

    protected GetNearest (TermType termType, Arguments args, OptArgs optargs) : base(termType, args, optargs)
    {
    }

///
/// "index": "T_STR",
///  "max_results": "T_NUM",
///  "unit": "E_UNIT",
///  "max_dist": "T_NUM",
///  "geo_system": "E_GEO_SYSTEM"
///
        public GetNearest optArg(string optname, object value) {
             var newOptargs = OptArgs.FromMap(this.OptArgs)
                                     .With(optname, value);
             return new GetNearest (this.Args, newOptargs);
        }

    }
}


text:
module.exports = (function(){
	var jquery = require('jquery'),
		modernizr = require('modernizr'),
		foundation = require('../../bower_components/foundation/js/foundation/foundation.js');
	require('../../bower_components/foundation/js/foundation/foundation.abide.js');
	require('../../bower_components/foundation/js/foundation/foundation.accordion.js');
	require('../../bower_components/foundation/js/foundation/foundation.alert.js');
	require('../../bower_components/foundation/js/foundation/foundation.clearing.js');
	require('../../bower_components/foundation/js/foundation/foundation.dropdown.js');
	require('../../bower_components/foundation/js/foundation/foundation.equalizer.js');
	require('../../bower_components/foundation/js/foundation/foundation.interchange.js');
	require('../../bower_components/foundation/js/foundation/foundation.joyride.js');
	require('../../bower_components/foundation/js/foundation/foundation.magellan.js');
	require('../../bower_components/foundation/js/foundation/foundation.offcanvas.js');
	require('../../bower_components/foundation/js/foundation/foundation.orbit.js');
	require('../../bower_components/foundation/js/foundation/foundation.reveal.js');
	require('../../bower_components/foundation/js/foundation/foundation.slider.js');
	require('../../bower_components/foundation/js/foundation/foundation.tab.js');
	require('../../bower_components/foundation/js/foundation/foundation.tooltip.js');
	require('../../bower_components/foundation/js/foundation/foundation.topbar.js');
	return foundation;
})();


text:
import path from 'path';
import {app} from 'electron';
import tempy from 'tempy';
import {convertToGif, convertToMp4, convertToWebm, convertToApng} from '../scripts/convert';

// `exportOptions` => format filePath width height fps loop, defaultFileName
export default async function (exportOptions) {
  const format = exportOptions.format;

  let convert;
  if (format === 'gif') {
    convert = convertToGif;
  } else if (format === 'mp4') {
    convert = convertToMp4;
  } else if (format === 'webm') {
    convert = convertToWebm;
  } else if (format === 'apng') {
    convert = convertToApng;
  }

  const outputPath = path.join(tempy.directory(), exportOptions.defaultFileName);

  await convert({
    filePath: exportOptions.filePath, // TODO: Rename `filePath` to `inputPath`
    outputPath,
    width: exportOptions.width,
    height: exportOptions.height,
    fps: exportOptions.fps,
    loop: exportOptions.loop,
    startTime: exportOptions.startTime,
    endTime: exportOptions.endTime,
    progressCallback: percentage => {
      app.kap.mainWindow.send('export-progress', {
        text: 'Converting…',
        percentage
      });
    }
  });

  app.kap.mainWindow.send('export-progress', {text: ''});

  return outputPath;
}


text:
package org.qi4j.api.common;

/**
 * Thrown when a Fragment or object could not be instantiated.
 * This includes, but not be limited to;
 *

 *
private constructor.

 *
abstract class for Constraints.

 *
interface instead of a class.

 *
useful constructor missing.

 *
exception thrown in the constructor.

 *
Subclassing of org.qi4j.api.property.Property

 *

 *

 * See the nested exception for additional details.
 *

 */
public class ConstructionException
    extends RuntimeException
{
    private static final long serialVersionUID = 1L;

    public ConstructionException()
    {
    }

    public ConstructionException( String message )
    {
        super( message );
    }

    public ConstructionException( String message, Throwable cause )
    {
        super( message, cause );
    }

    public ConstructionException( Throwable cause )
    {
        super( cause );
    }
}


text:
module Azure::Cosmosdb::Mgmt::V2020_04_01
  module Models
    #
    # Represents metrics values.
    #
    class MetricValue

      include MsRestAzure

      # @return [Float] The number of values for the metric.
      attr_accessor :_count

      # @return [Float] The average value of the metric.
      attr_accessor :average

      # @return [Float] The max value of the metric.
      attr_accessor :maximum

      # @return [Float] The min value of the metric.
      attr_accessor :minimum

      # @return [DateTime] The metric timestamp (ISO-8601 format).
      attr_accessor :timestamp

      # @return [Float] The total value of the metric.
      attr_accessor :total

      #
      # Mapper for MetricValue class as Ruby Hash.
      # This will be used for serialization/deserialization.
      #
      def self.mapper()
        {
          client_side_validation: true,
          required: false,
          serialized_name: 'MetricValue',
          type: {
            name: 'Composite',
            class_name: 'MetricValue',
            model_properties: {
              _count: {
                client_side_validation: true,
                required: false,
                read_only: true,
                serialized_name: '_count',
                type: {
                  name: 'Double'
                }
              },
              average: {
                client_side_validation: true,
                required: false,
                read_only: true,
                serialized_name: 'average',
                type: {
                  name: 'Double'
                }
              },
              maximum: {
                client_side_validation: true,
                required: false,
                read_only: true,
                serialized_name: 'maximum',
                type: {
                  name: 'Double'
                }
              },
              minimum: {
                client_side_validation: true,
                required: false,
                read_only: true,
                serialized_name: 'minimum',
                type: {
                  name: 'Double'
                }
              },
              timestamp: {
                client_side_validation: true,
                required: false,
                read_only: true,
                serialized_name: 'timestamp',
                type: {
                  name: 'DateTime'
                }
              },
              total: {
                client_side_validation: true,
                required: false,
                read_only: true,
                serialized_name: 'total',
                type: {
                  name: 'Double'
                }
              }
            }
          }
        }
      end
    end
  end
end


text:
import numpy as np
import pandas as pd

from vivarium.framework.engine import Builder
from vivarium.framework.event import Event

class Mortality:
    """Introduces death into the simulation.

    Attributes
    ----------
    configuration_defaults :
        A set of default configuration values for this component. These can be
        overwritten in the simulation model specification or by providing
        override values when constructing an interactive simulation.
    """

    configuration_defaults = {
        "mortality": {
            "mortality_rate": 0.01,
        }
    }

    def __init__(self):
        self.name = "mortality"

    # noinspection PyAttributeOutsideInit
    def setup(self, builder: Builder):
        """Performs this component's simulation setup.

        The ``setup`` method is automatically called by the simulation
        framework. The framework passes in a ``builder`` object which
        provides access to a variety of framework subsystems and metadata.

        Parameters
        ----------
        builder :
            Access to simulation tools and subsystems.
        """
        self.config = builder.configuration.mortality
        self.population_view = builder.population.get_view(
            ["alive"], query="alive == 'alive'"
        )
        self.randomness = builder.randomness.get_stream("mortality")

        self.mortality_rate = builder.value.register_rate_producer(
            "mortality_rate", source=self.base_mortality_rate
        )

        builder.event.register_listener("time_step", self.determine_deaths)

    def base_mortality_rate(self, index: pd.Index) -> pd.Series:
        """Computes the base mortality rate for every individual.

        Parameters
        ----------
        index :
            A representation of the simulants to compute the base mortality
            rate for.

        Returns
        -------
            The base mortality rate for all simulants in the index.
        """
        return pd.Series(self.config.mortality_rate, index=index)

    def determine_deaths(self, event: Event):
        """Determines who dies each time step.

        Parameters
        ----------
        event :
            An event object emitted by the simulation containing an index
            representing the simulants affected by the event and timing
            information.
        """
        effective_rate = self.mortality_rate(event.index)
        effective_probability = 1 - np.exp(-effective_rate)
        draw = self.randomness.get_draw(event.index)
        affected_simulants = draw < effective_probability
        self.population_view.update(pd.Series("dead", index=event.index[affected_simulants]))


text:
#include "tensorflow/core/framework/fake_input.h"
#include "tensorflow/core/framework/node_def_builder.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/framework/tensor_testutil.h"
#include "tensorflow/core/framework/types.h"
#include "tensorflow/core/kernels/ops_testutil.h"
#include "tensorflow/core/kernels/ops_util.h"
#include "tensorflow/core/lib/strings/str_util.h"
#include "tensorflow/core/lib/strings/strcat.h"

namespace tensorflow {
namespace {

class StringFormatGraphTest : public OpsTestBase {
 protected:
  Status Init(int num_inputs, DataType input_type,
              const string& template_ = "%s", const string& placeholder = "%s",
              int summarize = 3) {
    TF_CHECK_OK(NodeDefBuilder("op", "StringFormat")
                    .Input(FakeInput(num_inputs, input_type))
                    .Attr("template", template_)
                    .Attr("placeholder", placeholder)
                    .Attr("summarize", summarize)
                    .Finalize(node_def()));
    return InitOp();
  }
};

TEST_F(StringFormatGraphTest, Int32Success_7) {
  TF_ASSERT_OK(Init(1, DT_INT32, "First tensor: %s"));

  AddInputFromArray<int32>(TensorShape({7}), {1, 2, 3, 4, 5, 6, 7});
  TF_ASSERT_OK(RunOpKernel());
  Tensor expected(allocator(), DT_STRING, TensorShape({}));
  test::FillValues<tstring>(&expected, {"First tensor: [1 2 3 ... 5 6 7]"});
  test::ExpectTensorEqual<tstring>(expected, *GetOutput(0));
}

TEST_F(StringFormatGraphTest, Int32Success_3_3) {
  TF_ASSERT_OK(Init(1, DT_INT32, "First tensor: %s", "%s", 1));

  AddInputFromArray<int32>(TensorShape({3, 3}), {1, 2, 3, 4, 5, 6, 7, 8, 9});
  TF_ASSERT_OK(RunOpKernel());
  Tensor expected(allocator(), DT_STRING, TensorShape({}));
  test::FillValues<tstring>(&expected, {"First tensor: [[1 ... 3]\n ..."
                                        "\n [7 ... 9]]"});
  test::ExpectTensorEqual<tstring>(expected, *GetOutput(0));
}

}  // end namespace
}  // end namespace tensorflow


text:
Introduction
============
This quickstart demonstrates how policy can be used to control the security characteristics of a
service invocation.  The only service in the application is a Bean service called "WorkService".
SSL and/or WS-Security encryption can be used for "confidentiality", and WS-Security is used to verify the Signature and Encryption
of the SOAP message.

Running the quickstart
======================

EAP
----------

1. Start JBoss EAP in standalone mode:

        ${AS}/bin/standalone.sh

2. Build and deploy the quickstart

        mvn install -Pdeploy

3. Execute the test. (See "Options" section below.)

4. Check the server console for output from the service.

5. Undeploy the application

        mvn clean -Pdeploy

Wildfly
----------

1. Start Wildfly in standalone mode :

        ${WILDFLY}/bin/standalone.sh

2. Build and deploy the demo :

        mvn install -Pdeploy -Pwildfly

3. Execute the test. (See "Options" section below.)

4. Check the server console for output from the service.

5. Undeploy the application

        mvn clean -Pdeploy -Pwildfly

Warning --> Wildfly 8.0.0 When the application is undeployed, it is required to restart the server to get all the undeployment changes done.

Options
=======

When running with no options:

    mvn exec:java

You will be hitting the http (non-SSL) URL while NOT providing signed and encrypted information, and see this in your log:

```
[org.apache.cxf.phase.PhaseInterceptorChain] (http-/127.0.0.1:8080-1) Interceptor for
{urn:switchyard-quickstart-demo:policy-security-wss-signencrypt:0.1.0}WorkService#{urn:switchyard-quickstart-demo:policy-security-wss-signencrypt:0.1.0}doWork has thrown
exception, unwinding now: org.apache.cxf.ws.policy.PolicyException: These policy alternatives can not be satisfied:
{http://docs.oasis-open.org/ws-sx/ws-securitypolicy/200702}X509Token: The received token does not match the token inclusion requirement
{http://docs.oasis-open.org/ws-sx/ws-securitypolicy/200702}SignedParts: {http://schemas.xmlsoap.org/soap/envelope/}Body not SIGNED
{http://docs.oasis-open.org/ws-sx/ws-securitypolicy/200702}EncryptedParts: {http://schemas.xmlsoap.org/soap/envelope/}Body not ENCRYPTED
```

When running with this option:

    mvn exec:java -Dexec.args="confidentiality signencrypt" -Djavax.net.ssl.trustStore=connector.jks

You will be hitting the https (SSL) URL while providing signed and encrypted information, and see this in your log:

    :: WorkService :: Received work command => CMD-86

When running with this option:

    mvn exec:java -Dexec.args="signencrypt"

You will be hitting the http (non-SSL) URL while providing signed and encrypted information, and see this in your log:

    :: WorkService :: Received work command => CMD-86

Wait - why did this work? Even though SSL was not used, the content of the message is encrypted, thus the confidentiality policy is still being fulfilled.

Success!


text:
#ifndef _nix_Client_hpp__
#define _nix_Client_hpp__

// Copyright (c) 2011-2012, Andre Caron (andre.l.caron@gmail.com)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//   Redistributions of source code must retain the above copyright
//   notice, this list of conditions and the following disclaimer.
//
//   Redistributions in binary form must reproduce the above copyright
//   notice, this list of conditions and the following disclaimer in the
//   documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Copyright(c) 2011, Andre Caron (andre.l.caron@gmail.com)

/*!
 * @file demo/nix/Client.hpp
 * @author Andre Caron (andre.l.caron@gmail.com)
 */

#include "Tunnel.hpp"

namespace nix {

    class Client :
        public Tunnel
    {
        /* constrution. */
    public:
        Client ( nix::File& host, nix::net::Stream& peer );

        /* methods. */
    private:
        std::size_t handshake
            ( const std::string& host, char * data, std::size_t size );

        /* overrides. */
    protected:
        virtual void handshake ( const std::string& host );
    };

}

#endif /* _nix_Client_hpp__ */


text:
/*
 * SPDX-License-Identifier: Apache-2.0
 */

#include "LoopHelpers.hpp"
#include "onnx2trt_utils.hpp"

namespace onnx2trt
{

nvinfer1::ITensor* addLoopCounter(IImporterContext* ctx, nvinfer1::ILoop* loop, int32_t initial)
{
    nvinfer1::ITensor* initialTensor = addConstantScalar(ctx, initial, ::ONNX_NAMESPACE::TensorProto::INT32, nvinfer1::Dims{1, 1})->getOutput(0);
    nvinfer1::ITensor* one = addConstantScalar(ctx, 1, ::ONNX_NAMESPACE::TensorProto::INT32, nvinfer1::Dims{1, 1})->getOutput(0);

    auto counter = loop->addRecurrence(*initialTensor);
    nvinfer1::ITensor* addOne = ctx->network()->addElementWise(*counter->getOutput(0), *one, nvinfer1::ElementWiseOperation::kSUM)->getOutput(0);
    counter->setInput(1, *addOne);
    return counter->getOutput(0);
}

} // namespace onnx2trt


text:
package persistence.jpa;

import java.io.Serializable;
import java.util.UUID;

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Version;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.ToStringBuilder;

@Entity
@NamedQueries({
    @NamedQuery(name="list", query="select p from Ping p"),
    @NamedQuery(name="listById", query="select p from Ping p where p.id = ?1"),
    @NamedQuery(name="listByParameterId", query="select p from Ping p where p.id = :id"),
    @NamedQuery(name="find", query="select p from Ping p where p.value = 'ping'"),
    @NamedQuery(name="findById", query="select p from Ping p where p.id = ?1")
})
@XmlRootElement(name="Ping", namespace="http://javawerks/ping")
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "ping", propOrder = { "id", "version", "value"})
public class Ping implements Serializable {
	private static final long serialVersionUID = 1494933710390964019L;

	@Id
    @XmlElement()
    private String id;

    @Version
    @XmlElement()
    private int version;

    @XmlElement()
    private String value;

    protected Ping() {
        this.id = UUID.randomUUID().toString();
    }

    public Ping(String value) {
        this();
        this.value = value;
    }

    public String getId() {
        return id;
    }

    public int getVersion() {
		return version;
	}

	public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }

    @Override
    public int hashCode() {
        return id.hashCode();
    }

    @Override
    public boolean equals(Object object) {
        if (object == null) return false;
        if (object == this) return true;
        if (object.getClass() != getClass()) return false;
        Ping ping = (Ping) object;
        return new EqualsBuilder()
            .append(id, ping.getId())
            .append(value, ping.getValue())
            .isEquals();
    }

    @Override
    public String toString() {
        return new ToStringBuilder(this)
            .append("id", id)
            .append("value", value)
            .toString();
    }
}


text:
package org.apache.flex.compiler.internal.as.codegen;

import java.util.Iterator;

import org.apache.flex.abc.ABCConstants;
import org.apache.flex.abc.instructionlist.InstructionList;
import org.apache.flex.abc.semantics.ClassInfo;
import org.apache.flex.abc.semantics.InstanceInfo;
import org.apache.flex.abc.semantics.MethodInfo;
import org.apache.flex.abc.semantics.Name;
import org.apache.flex.abc.visitors.IABCVisitor;
import org.apache.flex.abc.visitors.IClassVisitor;
import org.apache.flex.abc.visitors.IMethodVisitor;
import org.apache.flex.abc.visitors.ITraitVisitor;
import org.apache.flex.abc.visitors.ITraitsVisitor;

import static org.apache.flex.abc.ABCConstants.*;

import org.apache.flex.compiler.common.ASModifier;
import org.apache.flex.compiler.common.IMetaInfo;
import org.apache.flex.compiler.common.ModifiersSet;
import org.apache.flex.compiler.constants.INamespaceConstants;
import org.apache.flex.compiler.definitions.IDefinition;
import org.apache.flex.compiler.definitions.IInterfaceDefinition;
import org.apache.flex.compiler.definitions.INamespaceDefinition;
import org.apache.flex.compiler.definitions.references.INamespaceReference;
import org.apache.flex.compiler.internal.definitions.AmbiguousDefinition;
import org.apache.flex.compiler.internal.definitions.ClassDefinition;
import org.apache.flex.compiler.internal.definitions.DefinitionBase;
import org.apache.flex.compiler.internal.definitions.FunctionDefinition;
import org.apache.flex.compiler.internal.definitions.InterfaceDefinition;
import org.apache.flex.compiler.internal.semantics.SemanticUtils;
import org.apache.flex.compiler.internal.tree.as.ExpressionNodeBase;
import org.apache.flex.compiler.internal.tree.as.FunctionNode;
import org.apache.flex.compiler.internal.tree.as.ImportNode;
import org.apache.flex.compiler.internal.tree.as.InterfaceNode;
import org.apache.flex.compiler.internal.tree.as.NamespaceIdentifierNode;
import org.apache.flex.compiler.internal.tree.as.VariableNode;
import org.apache.flex.compiler.problems.AmbiguousReferenceProblem;
import org.apache.flex.compiler.problems.CannotExtendClassProblem;
import org.apache.flex.compiler.problems.ConstructorInInterfaceProblem;
import org.apache.flex.compiler.problems.DuplicateInterfaceDefinitionProblem;
import org.apache.flex.compiler.problems.FinalOutsideClassProblem;
import org.apache.flex.compiler.problems.ICompilerProblem;
import org.apache.flex.compiler.problems.InterfaceBindablePropertyProblem;
import org.apache.flex.compiler.problems.InterfaceMethodWithBodyProblem;
import org.apache.flex.compiler.problems.InvalidOverrideProblem;
import org.apache.flex.compiler.problems.NamespaceInInterfaceProblem;
import org.apache.flex.compiler.problems.NativeUsedInInterfaceProblem;
import org.apache.flex.compiler.problems.StaticOutsideClassProblem;
import org.apache.flex.compiler.problems.UnknownInterfaceProblem;
import org.apache.flex.compiler.problems.BadAccessInterfaceMemberProblem;
import org.apache.flex.compiler.problems.InterfaceNamespaceAttributeProblem;
import org.apache.flex.compiler.problems.VarInInterfaceProblem;
import org.apache.flex.compiler.problems.VirtualOutsideClassProblem;
import org.apache.flex.compiler.projects.ICompilerProject;
import org.apache.flex.compiler.tree.as.IASNode;
import org.apache.flex.compiler.tree.as.IExpressionNode;
import org.apache.flex.compiler.tree.as.IIdentifierNode;
import org.apache.flex.compiler.tree.as.INamespaceDecorationNode;

/**
 *  The InterfaceDirectiveProcessor translates an InterfaceNode AST
 *  and children into an interface declaration and definition in the
 *  ABC and the init script, respectively.
 */
public class InterfaceDirectiveProcessor extends DirectiveProcessor
{
    /**
     *  The interface's syntax node.
     */
    InterfaceNode interfaceNode;

    /**
     *  The interface's lexical scope.
     */
    LexicalScope interfaceScope;

    /**
     *  The active ABC emitter.
     */
    IABCVisitor emitter;

    /**
     *  The name of the interface.
     */
    Name interfaceName;

    /** The interface' instance traits */
    ITraitsVisitor itraits;

    /** The AET visitor implementing this interface. */
    IClassVisitor cv;
    /** The interface' AET ClassInfo. */
    ClassInfo cinfo = new ClassInfo();
    /** The interface' AET InstanceInfo. */
    InstanceInfo iinfo = new InstanceInfo();

    /**
     *  Create an InterfaceDirectiveProcessor and set up the basic AET structures.
     *  @param in - the InterfaceNode.
     *  @param enclosing_scope - the lexical scope that encloses this interface
     *    declaration.  Either the global scope or a package scope.
     *  @param emitter - the active ABC emitter.
     */
    InterfaceDirectiveProcessor(InterfaceNode in, LexicalScope enclosing_scope, IABCVisitor emitter)
    {
        super(enclosing_scope.getProblems());

        this.interfaceNode   = in;
        this.emitter = emitter;

        this.interfaceScope = enclosing_scope.pushFrame();

        //  Create the class level structures.
        InterfaceDefinition interfDef = interfaceNode.getDefinition();
        this.interfaceName = interfDef.getMName(interfaceScope.getProject());

        iinfo.name = this.interfaceName;

        //  Check for a duplicate interface name.
        switch ( SemanticUtils.getMultiDefinitionType(interfaceNode.getDefinition(), interfaceScope.getProject()))
        {
            case AMBIGUOUS:
                this.interfaceScope.addProblem(new DuplicateInterfaceDefinitionProblem(in, this.interfaceName.getBaseName()));
                break;
            case NONE:
                break;
            default:
                assert false;       // I don't think interfaces can have other type of multiple definitions
        }

        if (this.interfaceName != null)
        {
            SemanticUtils.checkScopedToDefaultNamespaceProblem(this.interfaceScope, in, interfDef, this.interfaceName.getBaseName());
        }

        // Check for circular definition by iterating over all parent interfaces.
        Iterator<IInterfaceDefinition> ifaces = interfDef.interfaceIterator(interfaceScope.getProject(), false, interfaceScope.getProblems());
        while (ifaces.hasNext()) {
            ifaces.next();

        }
        // check that args are valid
      //  checkArguments(interfDef, interfaceScope.getProject(), interfaceScope.getProblems());

        //  Interfaces can't have a superclass.
        iinfo.superName = null;

        //  Add implmented interfaces.
        IExpressionNode[] raw_interfaces = this.interfaceNode.getExtendedInterfaceNodes();
        iinfo.interfaceNames = new Name[raw_interfaces.length];

        for ( int i = 0; i < raw_interfaces.length; i++)
        {
            IExpressionNode extendedInterface = raw_interfaces[i];
            IDefinition extendedDefinition = extendedInterface.resolve(interfaceScope.getProject());

            if ( extendedDefinition instanceof IInterfaceDefinition )
            {
                Name interfaceName = ((DefinitionBase)extendedDefinition).getMName(interfaceScope.getProject());
                iinfo.interfaceNames[i] = interfaceName;
            }
            else if ( extendedDefinition instanceof ClassDefinition )
            {
                this.interfaceScope.addProblem(new CannotExtendClassProblem(extendedInterface, extendedDefinition.getBaseName()));
            }
            else if ( extendedDefinition instanceof AmbiguousDefinition )
            {
                if ( extendedInterface instanceof IIdentifierNode )
                {
                    this.interfaceScope.addProblem(new AmbiguousReferenceProblem(extendedInterface, ((IIdentifierNode)extendedInterface).getName()));
                }
                else
                {
                    //  Parser let something weird through.
                    this.interfaceScope.addProblem(new AmbiguousReferenceProblem(extendedInterface, ""));
                }
            }
            else if ( extendedDefinition != null )
            {
                this.interfaceScope.addProblem(new UnknownInterfaceProblem(extendedInterface, extendedDefinition.getBaseName()));
            }
            else
            {
                if ( extendedInterface instanceof IIdentifierNode )
                {
                    this.interfaceScope.addProblem(new UnknownInterfaceProblem(extendedInterface, ((IIdentifierNode)extendedInterface).getName()));
                }
                else
                {
                    //  Parser let something weird through.
                    this.interfaceScope.addProblem(new UnknownInterfaceProblem(extendedInterface, ""));
                }
            }

            // Report a problem if the interface is deprecated
            // and the reference to it is not within a deprecated API.
            if ( extendedDefinition != null && extendedDefinition.isDeprecated())
            {
                if (!SemanticUtils.hasDeprecatedAncestor(extendedInterface))
                {
                    ICompilerProblem problem = SemanticUtils.createDeprecationProblem(extendedDefinition, extendedInterface);
                    this.interfaceScope.addProblem(problem);
                }
            }
        }

        // Set the flags corresponding to 'final' and 'dynamic'.
        if (interfDef.isFinal())
            iinfo.flags |= ABCConstants.CLASS_FLAG_final;
        if (!interfDef.isDynamic())
            iinfo.flags |= ABCConstants.CLASS_FLAG_sealed;
        iinfo.flags |= ABCConstants.CLASS_FLAG_interface;

        this.cv = emitter.visitClass(iinfo, cinfo);
        cv.visit();

        this.itraits = cv.visitInstanceTraits();

        //  Define the interface in the init script.
        InstructionList setup_insns = this.interfaceScope.getGlobalScope().getInitInstructions();
        setup_insns.addInstruction(OP_getscopeobject, 0);

        //  Interfaces don't have a base class.
        setup_insns.addInstruction(OP_pushnull);

        setup_insns.addInstruction(OP_newclass, cinfo);
        setup_insns.addInstruction(OP_initproperty, interfaceName);

        ITraitVisitor tv = this.interfaceScope.getGlobalScope().traitsVisitor.visitClassTrait(TRAIT_Class, interfaceName, 0, cinfo);
        this.interfaceScope.processMetadata(tv, interfDef.getAllMetaTags());
        tv.visitEnd();
    }

    /**
     *  Finish processing an interface declaration.
     */
    void finishInterfaceDefinition()
    {
        this.itraits.visitEnd();
        this.cv.visitEnd();
    }

    /**
     * Translate a VaribleNode AST into ABC.
     * Interfaces can't have vars in them, so just emit a diagnostic.
     * @param var - the variable's AST.
     */
    @Override
    void declareVariable(VariableNode var)
    {
        interfaceScope.addProblem(new VarInInterfaceProblem(var.getNameExpressionNode()));
    }

    /**
     * Declare a function.
     */
    @Override
    void declareFunction(FunctionNode func)
    {
        func.parseFunctionBody(interfaceScope.getProblems());
        functionSemanticChecks(func);

        FunctionDefinition func_def = func.getDefinition();

        final String interfaceBaseName = interfaceNode.getShortName();

        // ignore a constructor in an interface.
        // functionSemanticChecks() will already have issued a diagnostic.
        if (func_def.getBaseName().equals(interfaceBaseName))
        {
            return;
        }

        // make the method info, including any default vaules of parameters. Will do semantic checks
        // on the default values, too.
        MethodInfo mi = interfaceScope.getGenerator().createMethodInfoWithDefaultArgumentValues(this.interfaceScope, func);

        ICompilerProject project = interfaceScope.getProject();

        ExpressionNodeBase return_type_expr = (ExpressionNodeBase)func.getReturnTypeNode();
        if ( return_type_expr != null )
        {
            Name return_type_name = return_type_expr.getMName(project);
            mi.setReturnType(return_type_name);
        }

        IMethodVisitor mv = this.emitter.visitMethod(mi);
        mv.visit();
        mv.visitEnd();

        Name funcName = func_def.getMName(project);

        ITraitVisitor tv = itraits.visitMethodTrait(functionTraitKind(func, TRAIT_Method), funcName, 0, mi);
        IMetaInfo[] metaTags = func_def.getAllMetaTags();
        if (metaTags != null && metaTags.length > 0)
        {
            interfaceScope.processMetadata(tv, metaTags);
        }

    }

    /**
     * This method performs the semantic analysis of a function declared in a class.
     * @param func  the FunctionNode to semantically analyze
     */
    void functionSemanticChecks(FunctionNode func)
    {
        final FunctionDefinition func_def = func.getDefinition();
        final String interfaceBaseName = interfaceNode.getShortName();

        // Check for constructor and log a problem.  If it is a constructor,
        // don't bother doing anymore checking
        if (func_def.getBaseName().equals(interfaceBaseName))
        {
            interfaceScope.addProblem(new ConstructorInInterfaceProblem(func));
            return;
        }

        // check the modifiers
        verifyFunctionModifiers(func);

        // Make sure the function doesn't have a namespace
        verifyFunctionNamespace(func, func_def);

        // Warn if there is no return type
        SemanticUtils.checkReturnValueHasNoTypeDeclaration(interfaceScope, func, func_def);

        // Interface methods can't have a body
        if( func.hasBody() )
        {
            interfaceScope.addProblem(new InterfaceMethodWithBodyProblem(SemanticUtils.getFunctionProblemNode(func)));
        }

        ICompilerProject project = interfaceScope.getProject();

        // Do some semantic checking on the function
        interfaceScope.getMethodBodySemanticChecker().checkFunctionDecl(func);

        //  Ensure the return type is defined.
        IDefinition return_type = func_def.resolveReturnType(project);

        if ( !SemanticUtils.isType(return_type) )
        {
            interfaceScope.getMethodBodySemanticChecker().addTypeProblem(func.getReturnTypeNode(), return_type, func_def.getReturnTypeAsDisplayString(), true);
        }

        Name funcName = func_def.getMName(project);

        if (funcName != null)
        {
            interfaceScope.getMethodBodySemanticChecker().checkInterfaceFunctionForConflictingDefinitions(func, func_def);
        }

    }
        /**
        * Verify that interface function does not have a namespace on it. If it does, print the appropriate error
        * Note that "appropriate" means what the old compiler did: internal, public, private are special cased.
        *
        * @param func is the function node do be analyzed
        * @param func_def is the definition for func
        */
    private void verifyFunctionNamespace(FunctionNode func, FunctionDefinition func_def)
    {
        INamespaceDecorationNode nsNode = func.getActualNamespaceNode();

        // if we have no "actual" node, then there is no namespace in front of our function
        if (nsNode != null)
        {
            boolean isLanguateNS = false;

            // We need a special check for "internal", because tree building has already munged innternal to
            // make it just look like the default. But here we need to know what it really is
            if (INamespaceConstants.internal_.equals(nsNode.getName()))
            {
                isLanguateNS = true;
            }

            else
            {
                // If it's not "internal", then we can use our normal check to find out what it is
                INamespaceReference ns_ref = func_def.getNamespaceReference();
                if ( ns_ref instanceof INamespaceDefinition.ILanguageNamespaceDefinition )
                {
                    isLanguateNS = true;
                }

            }

            // generate the appropriate error
            if (isLanguateNS)
            {
                interfaceScope.addProblem(new BadAccessInterfaceMemberProblem(func));
            }
            else
            {
                interfaceScope.addProblem(new InterfaceNamespaceAttributeProblem(func));
            }
        }
    }

    /**
     * Validate that the modifiers used on a function are allowed
     */
    protected void verifyFunctionModifiers(FunctionNode f)
    {
        ModifiersSet modifiersSet = f.getModifiers();
        if (modifiersSet == null)
            return;

        ASModifier[] modifiers = modifiersSet.getAllModifiers();
        IExpressionNode site = f.getNameExpressionNode();
        for (ASModifier modifier : modifiers)
        {
            if( modifier == ASModifier.STATIC )
            {
                this.interfaceScope.addProblem(new StaticOutsideClassProblem(site));
            }
            else if ( modifier == ASModifier.OVERRIDE )
            {
                interfaceScope.addProblem(new InvalidOverrideProblem(site));
            }
            else if( modifier == ASModifier.FINAL )
            {
                interfaceScope.addProblem(new FinalOutsideClassProblem(site));
            }
            else if( modifier == ASModifier.NATIVE )
            {
                interfaceScope.addProblem(new NativeUsedInInterfaceProblem(site));
            }
            else if( modifier == ASModifier.VIRTUAL )
            {
                interfaceScope.addProblem(new VirtualOutsideClassProblem(site));
            }
            else if ( modifier == ASModifier.DYNAMIC )
            {
                //  Allow this and continue.
            }
        }
        interfaceScope.getMethodBodySemanticChecker().checkForDuplicateModifiers(f);
    }

    /**
     * Process a namespace identifier.
     */
    @Override
    void processNamespaceIdentifierDirective(NamespaceIdentifierNode ns)
    {
        interfaceScope.addProblem(new NamespaceInInterfaceProblem(ns));
    }

    /**
     * Process an import directive.
     */
    @Override
    void processImportDirective(ImportNode imp)
    {
        // Run the BURM, but for the purpose of semantic checking not code generation.
        interfaceScope.getGenerator().generateInstructions(imp, CmcEmitter.__statement_NT, this.interfaceScope);
    }

    /**
     *
     */
    @Override
    void processDirective(IASNode n)
    {
        switch ( n.getNodeID() )
        {
            case NamespaceID:
                interfaceScope.addProblem(new NamespaceInInterfaceProblem(n));
                break;
            default:
                super.processDirective(n);
        }
    }

    @Override
    void declareBindableVariable(VariableNode varNode)
    {
        interfaceScope.addProblem(new InterfaceBindablePropertyProblem(varNode));
    }
}


text:
{% load i18n %}
{% load hq_shared_tags %}
{% load xforms_extras %}

{% include 'hqmedia/partials/multimedia_js.html' %}

{% comment %}
todo fix

{% endcomment %}

    <form class="form-horizontal">

            <fieldset data-bind="visible: notEmpty">
                <legend>

                </legend>

                                {% blocktrans %}
                                    Oops!
                                    This setting shouldn't be here.
                                    Could you change it to the default
                                    to make it go away?
                                    Sorry about that.
                                {% endblocktrans %}

                                {% blocktrans %}
                                    This is not an allowed value for this field
                                {% endblocktrans %}

                            {% trans "Preview" %}

            </fieldset>

        {% if request|toggle_enabled:"CUSTOM_PROPERTIES" %}
        <fieldset>
            <legend>

                    {% trans "Custom Properties" %}

            </legend>

                    <button class="btn btn-primary" data-bind="
                        click: onAddCustomProperty
                        ">
                        {% trans "Add Custom Property" %}
                    </button>

        </fieldset>
        {% endif %}
    </form>


text:
                <button type="button" class="close" data-dismiss="modal"
                        aria-label="Close">
                    ×
                </button>

Create File

                <form id="fileForm" role="form">

                            Name
                            <input type="text" class="form-control" id="inputName"
                                   placeholder="The File" required>

                            Description
                            <input type="text" class="form-control" id="inputDescription"
                                   placeholder="Description" required>

                            Upload File

                                    file_name.txt

                                        Browse
                                        <input type="file" id="file-data" name="file-data">

                    <button type="submit" class="hidden" id="theSubmit"></button>
                </form>

                <button type="button" id="cancelButton" class="btn btn-default" data-dismiss="modal">
                    ✖ Close</button>
                <button id="saveButton" type="button" class="btn btn-primary">
                     Save</button>


text:
namespace data_source {

class FigureQueueI {
 public:
  virtual bool isFigureQueueEmpty() = 0;
  virtual std::shared_ptr<dom::figures::Figure> popFigure() = 0;

  virtual ~FigureQueueI() {}
};

class BinaryFiguresReaderI {
 public:
  virtual uint32_t read(const char* data, const int data_size) = 0;

  virtual ~BinaryFiguresReaderI() {}
};

class BinaryDataFiguresReader : public BinaryFiguresReaderI,
                                public FigureQueueI {
 private:
  using FigureQueue = std::queue<std::shared_ptr<dom::figures::Figure>>;

  enum class Type { square, rectangle, polygon, circle };

  std::map<int, Type> m_id_to_type_ref = {{1, Type::square},
                                          {2, Type::rectangle},
                                          {3, Type::polygon},
                                          {4, Type::circle}};

  BinarySquareReader m_square_reader;
  BinaryRectangleReader m_rectangle_reader;
  BinaryCircleReader m_circle_reader;
  BinaryPolygonReader m_polygon_reader;

  std::mutex m_queue_mutex;

  FigureQueue m_figure_queue;

 public:
  BinaryDataFiguresReader(){};
  virtual ~BinaryDataFiguresReader(){};

  // inherited from FigureQueueI
  virtual std::shared_ptr<dom::figures::Figure> popFigure() override;
  virtual bool isFigureQueueEmpty() override;

  // inherited from BinaryFiguresReaderI
  uint32_t read(const char* data, const int data_size) override;
};
}

#endif


text:
def do_nothing(remoteip, remoteport, sock, thishand, listenhand):
  mycontext['connections'] += 1
  stopcomm(thishand)
  mycontext['lock'].release()

  # don't let this function exit in case there are unknown side effects
  while mycontext['keep_testing']:
    sleep(1)

def fail_test(handle,sock):
  stopcomm(handle)
  sock.close()
  print 'test failed due to recv timeout'

if callfunc == "initialize":
  mycontext['keep_testing'] = True
  mycontext['connections'] = 0
  mycontext['lock'] = getlock()
  ip = '127.0.0.1'
  waitport = 12345

  lock = mycontext['lock']

  # the waitfor conn we will connect to
  handle = waitforconn(ip,waitport,do_nothing)

  lock.acquire()
  sock = openconn(ip,waitport)

  lock.acquire()
  lock.release()

  # in case the call to recv blocks
  timerhandle = settimer(2, fail_test,[handle,sock])

  # ensure the socket is closed
  try:
    sock.recv('1')
  except:
    pass
  else:
    print 'no exception when recv from closed connection'

  canceltimer(timerhandle)

  #ensure that the listener is still active
  lock.acquire()
  sock2 = openconn(ip,waitport)

  lock.acquire()
  lock.release()

  mycontext['keep_testing'] = False
  stopcomm(handle)
  sock.close()

  if mycontext['connections'] != 2:
    print "ERROR, inncorect number of connections made: "+str(mycontext['connections'])


text:
package com.navercorp.pinpoint.plugin.thrift.interceptor.tprotocol.server;

import com.navercorp.pinpoint.bootstrap.interceptor.AroundInterceptor;
import com.navercorp.pinpoint.bootstrap.interceptor.scope.InterceptorScope;
import com.navercorp.pinpoint.bootstrap.interceptor.scope.InterceptorScopeInvocation;
import com.navercorp.pinpoint.bootstrap.logging.PLogger;
import com.navercorp.pinpoint.bootstrap.logging.PLoggerFactory;
import com.navercorp.pinpoint.plugin.thrift.ThriftClientCallContext;
import com.navercorp.pinpoint.plugin.thrift.ThriftClientCallContextAttachmentFactory;
import com.navercorp.pinpoint.plugin.thrift.ThriftConstants;
import com.navercorp.pinpoint.plugin.thrift.field.accessor.AsyncMarkerFlagFieldAccessor;
import org.apache.thrift.protocol.TMessage;

/**
 * This interceptor retrieves the method name called by the client and stores it for other interceptors in the chain to use.
 *

 * <tt>TBaseAsyncProcessorProcessInterceptor</tt> -> <tt>TProtocolReadMessageBeginInterceptor</tt> -> <tt>TProtocolReadFieldBeginInterceptor</tt> <->
 * <tt>TProtocolReadTTypeInterceptor</tt> -> <tt>TProtocolReadMessageEndInterceptor</tt>
 *

 * Based on Thrift 0.8.0+
 *
 * @author HyunGil Jeong
 * @see com.navercorp.pinpoint.plugin.thrift.interceptor.tprotocol.server.TProtocolReadMessageBeginInterceptor TProtocolReadMessageBeginInterceptor
 * @see com.navercorp.pinpoint.plugin.thrift.interceptor.tprotocol.server.TProtocolReadFieldBeginInterceptor TProtocolReadFieldBeginInterceptor
 * @see com.navercorp.pinpoint.plugin.thrift.interceptor.tprotocol.server.TProtocolReadTTypeInterceptor TProtocolReadTTypeInterceptor
 * @see com.navercorp.pinpoint.plugin.thrift.interceptor.tprotocol.server.TProtocolReadMessageEndInterceptor TProtocolReadMessageEndInterceptor
 */
public class TProtocolReadMessageBeginInterceptor implements AroundInterceptor {

    private final PLogger logger = PLoggerFactory.getLogger(this.getClass());
    private final boolean isDebug = logger.isDebugEnabled();

    private final InterceptorScope scope;

    public TProtocolReadMessageBeginInterceptor(InterceptorScope scope) {
        this.scope = scope;
    }

    @Override
    public void before(Object target, Object[] args) {
        // Do nothing
    }

    @Override
    public void after(Object target, Object[] args, Object result, Throwable throwable) {
        if (isDebug) {
            logger.afterInterceptor(target, args, result, throwable);
        }
        if (!validate(target)) {
            return;
        }
        final boolean shouldTrace = ((AsyncMarkerFlagFieldAccessor) target)._$PINPOINT$_getAsyncMarkerFlag();
        if (shouldTrace) {
            String methodName = ThriftConstants.UNKNOWN_METHOD_NAME;
            if (result instanceof TMessage) {
                TMessage message = (TMessage) result;
                methodName = message.name;
            }
            final InterceptorScopeInvocation currentTransaction = this.scope.getCurrentInvocation();
            final Object attachment = currentTransaction.getOrCreateAttachment(ThriftClientCallContextAttachmentFactory.INSTANCE);
            if (attachment instanceof ThriftClientCallContext) {
                final ThriftClientCallContext clientCallContext = (ThriftClientCallContext) attachment;
                clientCallContext.setMethodName(methodName);
            }
        }
    }

    private boolean validate(Object target) {
        if (!(target instanceof AsyncMarkerFlagFieldAccessor)) {
            if (isDebug) {
                logger.debug("Invalid target object. Need field accessor({}).", AsyncMarkerFlagFieldAccessor.class.getName());
            }
            return false;
        }
        return true;
    }

}


text:
package uk.ac.ebi.eva.test.data;

import org.apache.commons.io.FileUtils;

import java.io.IOException;

import static uk.ac.ebi.eva.utils.FileUtils.getResource;

public class VariantData {

    private static final String VARIANT_WITHOUT_ANNOTATION_PATH = "/input-files/annotation/VariantWithOutAnnotation.json";
    private static final String VARIANT_WITHOUT_ANNOTATION_OTHER_STUDY_PATH = "/input-files/annotation/VariantWithOutAnnotationOtherStudy.json";
    private static final String VARIANT_WITH_ANNOTATION_PATH = "/input-files/annotation/VariantWithAnnotation.json";
    private static final String POPULATION_STATS_PATH = "/input-files/statistics/PopulationStatistics.json";
    private static final String VARIANT_WITH_ONE_STUDY_TO_DROP_PATH = "/input-files/variant/VariantWithOneStudyToDrop.json";
    private static final String OTHER_VARIANT_WITH_ONE_STUDY_TO_DROP_PATH = "/input-files/variant/OtherVariantWithOneStudyToDrop.json";
    private static final String VARIANT_WITH_ONE_STUDY_PATH = "/input-files/variant/VariantWithOneStudy.json";
    private static final String VARIANT_WITH_TWO_STUDIES_PATH = "/input-files/variant/VariantWithTwoStudies.json";

    public static String getVariantWithoutAnnotationOtherStudy() throws IOException {
        return FileUtils.readFileToString(getResource(VARIANT_WITHOUT_ANNOTATION_OTHER_STUDY_PATH));
    }

    public static String getVariantWithoutAnnotation() throws IOException {
        return FileUtils.readFileToString(getResource(VARIANT_WITHOUT_ANNOTATION_PATH));
    }

    public static String getVariantWithAnnotation() throws IOException {
        return FileUtils.readFileToString(getResource(VARIANT_WITH_ANNOTATION_PATH));
    }

    public static String getPopulationStatistics() throws IOException {
        return FileUtils.readFileToString(getResource(POPULATION_STATS_PATH));
    }

    public static String getVariantWithOneStudyToDrop() throws IOException {
        return FileUtils.readFileToString(getResource(VARIANT_WITH_ONE_STUDY_TO_DROP_PATH));
    }

    public static String getOtherVariantWithOneStudyToDrop() throws IOException {
        return FileUtils.readFileToString(getResource(OTHER_VARIANT_WITH_ONE_STUDY_TO_DROP_PATH));
    }

    public static String getVariantWithOneStudy() throws IOException {
        return FileUtils.readFileToString(getResource(VARIANT_WITH_ONE_STUDY_PATH));
    }

    public static String getVariantWithTwoStudies() throws IOException {
        return FileUtils.readFileToString(getResource(VARIANT_WITH_TWO_STUDIES_PATH));
    }
}


text:
from django.db import models
from django.contrib.auth.models import User
from django.shortcuts import resolve_url as r

class Doctor(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    slug = models.SlugField('slug')
    address = models.CharField('endereço', max_length=255, blank=True)
    neighborhood = models.CharField('bairro', max_length=255, blank=True)
    city = models.CharField('cidade', max_length=255, blank=True)
    phone = models.CharField('telefone', max_length=255, blank=True)
    specialization = models.CharField('especialização', max_length=255,
                                      blank=True)

    class Meta:
        verbose_name = 'médico'
        verbose_name_plural = 'médicos'

    def __str__(self):
        return ' '.join([self.user.first_name, self.user.last_name])

    def get_absolute_url(self):
        return r('doctor_details', slug=self.slug)


text:
package web

import (
	"testing"
)

func Test_injectPartials(t *testing.T) {
	got, want := injectPartials(before), after
	if got != want {
		t.Errorf("Want html %q, got %q", want, got)
	}
}

var before = `<!DOCTYPE html>

	<meta charset="utf-8">

<link rel="shortcut icon" href="/favicon.png">

`

var after = `<!DOCTYPE html>

	<meta charset="utf-8">
	{{ template "version" . }}
	{{ template "user" . }}
	{{ template "csrf" . }}
<link rel="shortcut icon" href="/favicon.png">

`


text:
#include <tinyxml.h>

#include "oss_sdk_cpp/utils/utils.h"
#include "oss_sdk_cpp/utils/string_utils.h"
#include "oss_sdk_cpp/utils/xml_utils.h"

#include "oss_sdk_cpp/message/get_bucket_lifecycle_result.h"

namespace oss {

const LifeCycleList& GetBucketLifecycleResult::GetBucketLifecycle() const {
  return rules_;
}

bool GetBucketLifecycleResult::DeserializeFromXml(const std::string& content) {
  TiXmlDocument doc;
  if (doc.Parse(content.c_str(), 0, TIXML_ENCODING_UTF8) == NULL)
    return false;

  TiXmlNode* node = NULL;
  TiXmlNode* root_node = doc.FirstChild("LifecycleConfiguration");
  // RefererConfiguration is required.
  if (root_node == NULL)
    return false;

  TiXmlNode* rule_node = root_node->FirstChild("Rule");
  while (rule_node != NULL) {
    LifeCycleRule rule;

    node = rule_node->FirstChild("ID");
    if (node != NULL) {
      rule.SetId(GetXmlNodeText(node));
    }

    node = rule_node->FirstChild("Prefix");
    if (node != NULL) {
      rule.SetPrefix(GetXmlNodeText(node));
    }

    node = rule_node->FirstChild("Status");
    if (node != NULL) {
      const char* status = GetXmlNodeText(node);
      rule.SetEnabled(stricmp(status, "Enabled") == 0);
    }

    TiXmlNode* expiration_node = rule_node->FirstChild("Expiration");
    if (expiration_node != NULL) {
      node = expiration_node->FirstChild("Days");
      if (node != NULL) {
        // use Days.
        rule.SetExpirationDays(atoi(GetXmlNodeText(node)));
      } else {
        node = expiration_node->FirstChild("Date");
        if (node != NULL) {
          // use Date.
          rule.SetExpirationDate(GetXmlNodeText(node));
        }
      }
      rules_.push_back(rule);
    }

    rule_node = rule_node->NextSibling("Rule");
  }

  return true;
}

}  // namespace oss


text:
/**
 *
 * @type {*|exports|module.exports}
 */
/** requires module: url-join */
var urljoin = require('url-join');
/** requires module: request */
var request = require('request');
/** requires module: bluebird */
var Promise = require('bluebird');
/** requires module: ./../../config.js */
var config = require('./../../config.js');

/**@function rest
 * @constructor
 */
function rest(){}

/** Prototype to check connection
 * @memberof rest
 * @function checkConnection
 */
rest.prototype.checkConnection = function(){
  var options = {
    url:  urljoin(config.rest.host, 'helloWorld'),
    rejectUnauthorized: false, // TODO certificate needs to be bundled correctly
    auth: config.auth
  };

  return new Promise(function(resolve, reject){
    request.get(options, function(err, res, body){
      if(err) reject(err);
      if(body == 'Hello World!'){
        resolve({status: 'ok'});
      }
    });
  });
};

/** Prototype to get orders by status
 * @memberof rest
 * @function getOrdersByStatus
 */
rest.prototype.getOrdersByStatus = function(status){
  var options = {
    url:  urljoin(config.rest.host, config.rest.getOrdersByStatus),
    rejectUnauthorized: false, // TODO certificate needs to be bundled correctly
    form: {status: status},
    auth: config.auth
  };

  return new Promise(function(resolve, reject){
    request.post(options, function(err, res, body){
      if(err) reject(err);
      try {
        body = JSON.parse(body);
        resolve(body);
      } catch (err){
        reject('could not perform getOrdersByStatus, maybe server is not reached, or body is not json');
      }
    });
  });
};

/** Prototype to get active orders
 * @memberof rest
 * @function getActiveOrders
 */
rest.prototype.getActiveOrders = function(status){
  var options = {
    url:  urljoin(config.rest.host, config.rest.getActiveOrders),
    rejectUnauthorized: false, // TODO certificate needs to be bundled correctly
    auth: config.auth
  };

  return new Promise(function(resolve, reject){
    request.post(options, function(err, res, body){
      if(err) reject(err);
      try {
        body = JSON.parse(body);
        resolve(body);
      } catch (err){
        reject('could not perform getOrdersByStatus, maybe server is not reached, or body is not json');
      }
    });
  });
};

/** Prototype to get Orders Updated since a Timestamp
 * @memberof rest
 * @function getOrdersUpdatedSince
 * @param timestamp
 */
rest.prototype.getOrdersUpdatedSince = function(timestamp){
  var options = {
    url:  urljoin(config.rest.host, 'getOrdersUpdatedSince'),
    rejectUnauthorized: false, // TODO certificate needs to be bundled correctly
    timestamp: timestamp,
    auth: config.auth
  };

  return new Promise(function(resolve, reject){
    request.post(options, function(err, res, body){
      if(err) reject(err);
      try {
        body = JSON.parse(body);
        resolve(body);
      } catch (err){
        reject('could not perform getOrdersByStatus, maybe server is not reached, or body is not json');
      }
    });
  });
};

/** Prototype to get Cocktail Data by OrderId
 * @memberof rest
 * @function getCocktailDataByOrderId
 * @param id
 */
rest.prototype.getCocktailDataByOrderId = function(id){
  var options = {
    url:  urljoin(config.rest.host, 'getCocktailDataByOrderId'),
    rejectUnauthorized: false, // TODO certificate needs to be bundled correctly
    form: {id: id},
    auth: config.auth
  };

  return new Promise(function(resolve, reject){
    request.post(options, function(err, res, body){
      if(err) reject(err);
      try {
        body = JSON.parse(body);
        resolve(body);
      } catch (err){
        reject(err);
      }
    });
  });
};

/** Prototype to get Irder by Id
 * @memberof rest
 * @function getOrderById
 * @param id
 */
rest.prototype.getOrderById = function(id){
  var options = {
    url:  urljoin(config.rest.host, 'getOrderById'),
    rejectUnauthorized: false, // TODO certificate needs to be bundled correctly
    form: {id: id},
    auth: config.auth
  };

  return new Promise(function(resolve, reject){
    request.post(options, function(err, res, body){
      if(err) reject(err);
      try {
        body = JSON.parse(body);
        resolve(body);
      } catch (err){
        reject('could not perform getOrdersByStatus, maybe server is not reached, or body is not json');
      }
    });
  });
};

/** Prototype to get Orders Filtered
 * @memberof rest
 * @function getOrdersFiltered
 * @param filter
 */
rest.prototype.getOrdersFiltered = function(filter){
  var options = {
    url:  urljoin(config.rest.host, 'getOrdersFiltered'),
    rejectUnauthorized: false, // TODO certificate needs to be bundled correctly
    form: filter,
    auth: config.auth
  };

  return new Promise(function(resolve, reject){
    request.post(options, function(err, res, body){
      if(err) reject(err);
      try {
        body = JSON.parse(body);
        resolve(body);
      } catch (err){
        reject('could not perform getOrdersByStatus, maybe server is not reached, or body is not json');
      }
    });
  });
};

/** Prototype to update Orders status
 * @memberof rest
 * @function updateOrderStatus
 * @param orderid
 * @param status
 */
rest.prototype.updateOrderStatus = function(orderid, status){
  var options = {
    url:  urljoin(config.rest.host, config.rest.updateOrderStatus),
    rejectUnauthorized: false, // TODO certificate needs to be bundled correctly
    form: {id: orderid, status: status},
    auth: config.auth
  };

  return new Promise(function(resolve, reject){
    request.post(options, function(err, res, body){
      if(err) reject(err);
      try {
        body = JSON.parse(body);
        resolve(body);
      } catch (err){
        reject('problems in JSON.parse, probably return is not JSON formatted');
      }
    });
  });
};

/** Prototype to perform Order
 * @memberof rest
 * @function performOrder
 */
rest.prototype.performOrder = function(){
  var options = {
    url:  urljoin(config.rest.host, config.rest.placeOrder),
    rejectUnauthorized: false, // TODO certificate needs to be bundled correctly
    form: {order: '{"recipeId":10010,"parameters":[],"marketPlaceId":"eu"}'},
    auth: config.auth
  };

  return new Promise(function(resolve, reject){
    request.post(options, function(err, res, body){
      if(err) reject(err);
      try {
        body = JSON.parse(body);
        resolve(body);
      } catch (err){
        reject('problems in JSON.parse, probably return is not JSON formatted');
      }
    });
  });
};

module.exports = new rest();


text:
from temboo.core.choreography import Choreography
from temboo.core.choreography import InputSet
from temboo.core.choreography import ResultSet
from temboo.core.choreography import ChoreographyExecution

import json

class ReleaseAddress(Choreography):

    def __init__(self, temboo_session):
        """
        Create a new instance of the ReleaseAddress Choreo. A TembooSession object, containing a valid
        set of Temboo credentials, must be supplied.
        """
        super(ReleaseAddress, self).__init__(temboo_session, '/Library/Amazon/EC2/ReleaseAddress')

    def new_input_set(self):
        return ReleaseAddressInputSet()

    def _make_result_set(self, result, path):
        return ReleaseAddressResultSet(result, path)

    def _make_execution(self, session, exec_id, path):
        return ReleaseAddressChoreographyExecution(session, exec_id, path)

class ReleaseAddressInputSet(InputSet):
    """
    An InputSet with methods appropriate for specifying the inputs to the ReleaseAddress
    Choreo. The InputSet object is used to specify input parameters when executing this Choreo.
    """
    def set_AWSAccessKeyId(self, value):
        """
        Set the value of the AWSAccessKeyId input for this Choreo. ((required, string) The Access Key ID provided by Amazon Web Services.)
        """
        super(ReleaseAddressInputSet, self)._set_input('AWSAccessKeyId', value)
    def set_AWSSecretKeyId(self, value):
        """
        Set the value of the AWSSecretKeyId input for this Choreo. ((required, string) The Secret Key ID provided by Amazon Web Services.)
        """
        super(ReleaseAddressInputSet, self)._set_input('AWSSecretKeyId', value)
    def set_AllocationId(self, value):
        """
        Set the value of the AllocationId input for this Choreo. ((conditional, string) [EC2-VPC] The allocation ID that AWS provided when you allocated the address for use with a VPC.)
        """
        super(ReleaseAddressInputSet, self)._set_input('AllocationId', value)
    def set_PublicIp(self, value):
        """
        Set the value of the PublicIp input for this Choreo. ((conditional, string) [EC2-Classic] The Elastic IP address.)
        """
        super(ReleaseAddressInputSet, self)._set_input('PublicIp', value)
    def set_ResponseFormat(self, value):
        """
        Set the value of the ResponseFormat input for this Choreo. ((optional, string) The format that the response should be in. Valid values are "xml" (the default) and "json".)
        """
        super(ReleaseAddressInputSet, self)._set_input('ResponseFormat', value)
    def set_UserRegion(self, value):
        """
        Set the value of the UserRegion input for this Choreo. ((optional, string) The AWS region that corresponds to the EC2 endpoint you wish to access. The default region is "us-east-1". See description below for valid values.)
        """
        super(ReleaseAddressInputSet, self)._set_input('UserRegion', value)

class ReleaseAddressResultSet(ResultSet):
    """
    A ResultSet with methods tailored to the values returned by the ReleaseAddress Choreo.
    The ResultSet object is used to retrieve the results of a Choreo execution.
    """

    def getJSONFromString(self, str):
        return json.loads(str)

    def get_Response(self):
        """
        Retrieve the value for the "Response" output from this Choreo execution. (The response from Amazon.)
        """
        return self._output.get('Response', None)

class ReleaseAddressChoreographyExecution(ChoreographyExecution):

    def _make_result_set(self, response, path):
        return ReleaseAddressResultSet(response, path)


text:
package frodo

import "testing"

func TestGetConnectionCount(t *testing.T) {
	es := NewEventSource()

	if es.ConnectionCount() != 0 {
		t.Fatal("There's clients connected. How?")
	}
}


text:
package com.vngrs.android.pomodoro.shared.data.prefs;

import java.lang.annotation.Documented;
import java.lang.annotation.Retention;

import javax.inject.Qualifier;

import static java.lang.annotation.RetentionPolicy.RUNTIME;

@Qualifier @Documented @Retention(RUNTIME)
public @interface LastPomodoro {
}


text:
try offical python tutorial 3h

- 0.5h tutorial
- [waste]1h pip2/3 conflict issues, try to fix but end with a mess
- [waste]1h launch a new ec2 instance, setup saki env
- 0.5h tutorial

q: what's the fastest way to have a basic understanding of mongodb?

1. features + applications <- offical tutorial or wiki?
2. books

maybe. always keep time-efficiency in mind when learning new things.


text:
from tensorpack import ProxyDataFlow, get_rng

class DisturbLabel(ProxyDataFlow):
    def __init__(self, ds, prob):
        super(DisturbLabel, self).__init__(ds)
        self.prob = prob

    def reset_state(self):
        super(DisturbLabel, self).reset_state()
        self.rng = get_rng(self)

    def get_data(self):
        for dp in self.ds.get_data():
            img, l = dp
            if self.rng.rand() < self.prob:
                l = self.rng.choice(10)
            yield [img, l]


text:
using System;

namespace PlayingCards
{
    public interface ICard
    {
    }
}


text:
import { Message } from "discord.js";

import * as Skins from "../../data/skins";

async function handler(message: Message): Promise<void> {
  const classic = await Skins.getClassicSkinCount();
  const {
    tweeted,
    approved,
    rejected,
    nsfw,
    tweetable,
    webUploads,
    uploadsAwaitingProcessing,
    uploadsErrored,
  } = await Skins.getStats();

  await message.channel.send(`Unique Skins: ${classic.toLocaleString()}
Tweeted: ${tweeted.toLocaleString()}
Rejected: ${rejected.toLocaleString()}
NSFW: ${nsfw.toLocaleString()}
Approved: ${approved.toLocaleString()}
Tweetable: ${tweetable.toLocaleString()}
Uploaded Via Web: ${webUploads.toLocaleString()}
Uploads Awaiting Processing: ${uploadsAwaitingProcessing.toLocaleString()}
Uploads that Errored: ${uploadsErrored.toLocaleString()}
 `);
}

module.exports = {
  command: "stats",
  handler,
  usage: "",
  description: "Give some statistics about the skin archive",
};


text:
<?php

namespace backend\models;

use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use backend\models\ActivityRoom;

/**
 * ActivityRoomSearch represents the model behind the search form about `backend\models\ActivityRoom`.
 */
class ActivityRoomSearch extends ActivityRoom
{
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['id', 'type', 'activity_id', 'tb_room_id', 'status', 'createdBy', 'modifiedBy'], 'integer'],
            [['startTime', 'finishTime', 'note', 'created', 'modified'], 'safe'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function scenarios()
    {
        // bypass scenarios() implementation in the parent class
        return Model::scenarios();
    }

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function search($params)
    {
        $query = ActivityRoom::find();

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);

        if (!($this->load($params) && $this->validate())) {
            return $dataProvider;
        }

        $query->andFilterWhere([
            'id' => $this->id,
            'type' => $this->type,
            'activity_id' => $this->activity_id,
            'tb_room_id' => $this->tb_room_id,
            'startTime' => $this->startTime,
            'finishTime' => $this->finishTime,
            'status' => $this->status,
            'created' => $this->created,
            'createdBy' => $this->createdBy,
            'modified' => $this->modified,
            'modifiedBy' => $this->modifiedBy,
        ]);

        $query->andFilterWhere(['like', 'note', $this->note]);

        return $dataProvider;
    }
}


text:
package client

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"strings"
)

// Client is the basic type for interacting with the API. It provides methods
// matching the available actions in the API.
type Client struct {
	Endpoint string
}

// NewClient creates a instance of the client type.
func NewClient(endpoint string) (*Client, error) {
	return &Client{Endpoint: endpoint}, nil
}

// APIError represents an error returned by the Snickers API.
//
type APIError struct {
	Status int    `json:"status,omitempty"`
	Errors string `json:"errors,omitempty"`
}

// Error converts the whole interlying information to a representative string.
//
// It encodes the list of errors in JSON format.
func (apiErr *APIError) Error() string {
	data, _ := json.Marshal(apiErr)
	return fmt.Sprintf("Error returned by the Snickers API: %s", data)
}

func (c *Client) do(method string, path string, body interface{}, out interface{}) error {

	jsonRequest, err := json.Marshal(body)
	if err != nil {
		return err
	}

	req, err := http.NewRequest(method, c.Endpoint+path, strings.NewReader(string(jsonRequest)))
	if err != nil {
		return err
	}

	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		return err
	}
	defer resp.Body.Close()
	respData, err := ioutil.ReadAll(resp.Body)

	if err != nil {
		return err
	}

	if resp.StatusCode < http.StatusOK || resp.StatusCode >= http.StatusMultipleChoices {
		return &APIError{
			Status: resp.StatusCode,
			Errors: string(respData),
		}
	}

	if out != nil && len(respData) > 1 {
		return json.Unmarshal(respData, out)
	}

	return nil
}


text:
<?php

namespace yeesoft\multilingual\assets;

use yii\web\AssetBundle;

class FormLanguageSwitcherAsset extends AssetBundle
{

    public $js = [
        'js/form-switcher.js',
    ];
    public $css = [
        'css/form-switcher.css',
    ];
    public $depends = [
        'yii\web\JqueryAsset',
        'yii\web\YiiAsset',
    ];

    public function init()
    {
        $this->sourcePath = __DIR__ . '/source/form-switcher';
    }

}


text:
package com.xq.myxuanqi.ui.view;

import android.app.Dialog;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

import com.xq.myxuanqi.R;

/**
 * Created by tjy on 2017/6/19.
 */
public class LoadingDialog extends Dialog {

    public LoadingDialog(Context context) {
        super(context);
    }

    public LoadingDialog(Context context, int themeResId) {
        super(context, themeResId);
    }

    public static class Builder{

        private Context context;
        private String message;
        private boolean isShowMessage=true;
        private boolean isCancelable=false;
        private boolean isCancelOutside=false;

        public Builder(Context context) {
            this.context = context;
        }

        /**
         * 设置提示信息
         * @param message
         * @return
         */

        public Builder setMessage(String message){
            this.message=message;
            return this;
        }

        /**
         * 设置是否显示提示信息
         * @param isShowMessage
         * @return
         */
        public Builder setShowMessage(boolean isShowMessage){
            this.isShowMessage=isShowMessage;
            return this;
        }

        /**
         * 设置是否可以按返回键取消
         * @param isCancelable
         * @return
         */

        public Builder setCancelable(boolean isCancelable){
            this.isCancelable=isCancelable;
            return this;
        }

        /**
         * 设置是否可以取消
         * @param isCancelOutside
         * @return
         */
        public Builder setCancelOutside(boolean isCancelOutside){
            this.isCancelOutside=isCancelOutside;
            return this;
        }

        public LoadingDialog create(){

            LayoutInflater inflater = LayoutInflater.from(context);
            View view=inflater.inflate(R.layout.dialog_loading,null);
            LoadingDialog loadingDialog=new LoadingDialog(context,R.style.MyDialogStyle);
            TextView msgText= (TextView) view.findViewById(R.id.tipTextView);
            if(isShowMessage){
                msgText.setText(message);
            }else{
                msgText.setVisibility(View.GONE);
            }
            loadingDialog.setContentView(view);
            loadingDialog.setCancelable(isCancelable);
            loadingDialog.setCanceledOnTouchOutside(isCancelOutside);
            return  loadingDialog;

        }

    }
}


text:
		Kezdőlap
       •
      Tartalom
       •
      Bemutatkozás
       •
      Elérhetőség
       •
      Feliratkozás

Kapcsolat:

{{ site.email }}

					{% if site.github_username %}

						{% include icon-github.html username=site.github_username %}

					{% endif %}

					{% if site.instagram_username %}

						{% include icon-instagram.html username=site.instagram_username %}

					{% endif %}

					{% if site.twitter_username %}

						{% include icon-twitter.html username=site.twitter_username %}

					{% endif %}

{{ site.description }}

MINDEN JOG FENNTARTVA – DR. PUSKÁS JÁNOS © 2015
		A Compliance & Investigations Blog hasznos információkkal szolgál a vállalatok számára, a compliance munkát és belső vizsgálatokat érintő kérdéseket dolgoz fel a bloggazda szubjektív véleményének megfelelően. A cikkek és az azokhoz a complianceblog.hu-n vagy közösségi médiában fűzött megjegyzések egyike sem minősül jogi vagy üzleti tanácsnak, a bloggazda azokat általános jelleggel fogalmazza meg. Egyedi ügyekben kérje szakember tanácsát, segítségét.


text:
date: 2014-11-30
title: Bicycle Belladone
thumbnail: /images/bicycle-belladone/thumbnail.jpg
tags: [sewing, deer and doe, sewing]
---

{{
}}

One of the most infuriating feelings in the world is getting to a train station just as the train is pulling out. This time, I ran up to the train as the doors shut in my face, and the conductor sad-shrugged at me. Sadly, the Caltrain runs every hour, so missing the train results in being catastrophically late for whatever you were planning to do.

And that's how I found myself at the 22nd Street Caltrain station with an hour to kill, and no one around. Perfect time to start making silly faces at a camera, while I figure out how this self-timer thing works! I don't know how people look natural in photos -- I'm actually the worst at this. I end up making the grumpy cat face in at least half of the things I take.

{{
}}
{{
}}

This is easily my favorite pattern right now -- I've only made 3 versions of it. :P It's an 8-piece pattern, with 8 darts total, so it comes together in a few hours. The bias tape binding and skirt facing make finishing the dress a breeze, since there's no fussy folding hem.

{{
}}

You can tell I haven't seen sun in ages. So much wincing!

The fabric makes me so happy. This is Art Gallery Fabric's Cleta run, in bikaleidescope.

{{
}}
{{
}}

The insides are pinked, with a line of straight stitches right before the pinked edge. This is my third blind hem, and I'm still in love with the technique. I don't have a blind hem foot, so it's a lot of careful and finicky sewing.

{{
}}

My back is freakishly bent -- I need to make a sway back adjustment to everything I make. I think this fits pretty well, though! Unlike the space dress, I didn't take in the side seams, so this has more ease around the waist. I think I like the space dress more because of that alteration, though.

{{
}}

I love how perfectly the back pieces lie. This is the same adjustment I've made with all the other Belladones -- take a wedge out of the back.

**Fabric** // Quilting weight cotton by Art Gallery Fabric ([Bikaleidoscope from Cleta](http://www.artgalleryfabrics.com/cgi-bin/fabricshop/gallery.cgi?func=show&file=10&Category=109&Page=1&v=1))

**Pattern** // Deer and Doe's [Belladone](https://shop.deer-and-doe.fr/en/sewing-patterns/8-belladone-dress-pattern.html)

## Adjustments

Same as the [spaceship belladone](/spaceship-belladone) and the [hot pink belladone](/first-belladone-dress), minus the waist-cinching.