text:
package com.google.common.collect;
public class EmptyImmutableTableTest_gwt extends com.google.gwt.junit.client.GWTTestCase {
@Override public String getModuleName() {
  return "com.google.common.collect.testModule";
}
public void testCellSet() throws Exception {
  com.google.common.collect.EmptyImmutableTableTest testCase = new com.google.common.collect.EmptyImmutableTableTest();
  testCase.testCellSet();
}

public void testClear() throws Exception {
  com.google.common.collect.EmptyImmutableTableTest testCase = new com.google.common.collect.EmptyImmutableTableTest();
  testCase.testClear();
}

public void testColumn() throws Exception {
  com.google.common.collect.EmptyImmutableTableTest testCase = new com.google.common.collect.EmptyImmutableTableTest();
  testCase.testColumn();
}

public void testColumnKeySet() throws Exception {
  com.google.common.collect.EmptyImmutableTableTest testCase = new com.google.common.collect.EmptyImmutableTableTest();
  testCase.testColumnKeySet();
}

public void testColumnMap() throws Exception {
  com.google.common.collect.EmptyImmutableTableTest testCase = new com.google.common.collect.EmptyImmutableTableTest();
  testCase.testColumnMap();
}

public void testConsistentHashCode() throws Exception {
  com.google.common.collect.EmptyImmutableTableTest testCase = new com.google.common.collect.EmptyImmutableTableTest();
  testCase.testConsistentHashCode();
}

public void testConsistentToString() throws Exception {
  com.google.common.collect.EmptyImmutableTableTest testCase = new com.google.common.collect.EmptyImmutableTableTest();
  testCase.testConsistentToString();
}

public void testContains() throws Exception {
  com.google.common.collect.EmptyImmutableTableTest testCase = new com.google.common.collect.EmptyImmutableTableTest();
  testCase.testContains();
}

public void testContainsColumn() throws Exception {
  com.google.common.collect.EmptyImmutableTableTest testCase = new com.google.common.collect.EmptyImmutableTableTest();
  testCase.testContainsColumn();
}

public void testContainsRow() throws Exception {
  com.google.common.collect.EmptyImmutableTableTest testCase = new com.google.common.collect.EmptyImmutableTableTest();
  testCase.testContainsRow();
}

public void testContainsValue() throws Exception {
  com.google.common.collect.EmptyImmutableTableTest testCase = new com.google.common.collect.EmptyImmutableTableTest();
  testCase.testContainsValue();
}

public void testEqualsObject() throws Exception {
  com.google.common.collect.EmptyImmutableTableTest testCase = new com.google.common.collect.EmptyImmutableTableTest();
  testCase.testEqualsObject();
}

public void testGet() throws Exception {
  com.google.common.collect.EmptyImmutableTableTest testCase = new com.google.common.collect.EmptyImmutableTableTest();
  testCase.testGet();
}

public void testHashCode() throws Exception {
  com.google.common.collect.EmptyImmutableTableTest testCase = new com.google.common.collect.EmptyImmutableTableTest();
  testCase.testHashCode();
}

public void testIsEmpty() throws Exception {
  com.google.common.collect.EmptyImmutableTableTest testCase = new com.google.common.collect.EmptyImmutableTableTest();
  testCase.testIsEmpty();
}

public void testPut() throws Exception {
  com.google.common.collect.EmptyImmutableTableTest testCase = new com.google.common.collect.EmptyImmutableTableTest();
  testCase.testPut();
}

public void testPutAll() throws Exception {
  com.google.common.collect.EmptyImmutableTableTest testCase = new com.google.common.collect.EmptyImmutableTableTest();
  testCase.testPutAll();
}

public void testRemove() throws Exception {
  com.google.common.collect.EmptyImmutableTableTest testCase = new com.google.common.collect.EmptyImmutableTableTest();
  testCase.testRemove();
}

public void testRow() throws Exception {
  com.google.common.collect.EmptyImmutableTableTest testCase = new com.google.common.collect.EmptyImmutableTableTest();
  testCase.testRow();
}

public void testRowKeySet() throws Exception {
  com.google.common.collect.EmptyImmutableTableTest testCase = new com.google.common.collect.EmptyImmutableTableTest();
  testCase.testRowKeySet();
}

public void testRowMap() throws Exception {
  com.google.common.collect.EmptyImmutableTableTest testCase = new com.google.common.collect.EmptyImmutableTableTest();
  testCase.testRowMap();
}

public void testSize() throws Exception {
  com.google.common.collect.EmptyImmutableTableTest testCase = new com.google.common.collect.EmptyImmutableTableTest();
  testCase.testSize();
}

public void testToString() throws Exception {
  com.google.common.collect.EmptyImmutableTableTest testCase = new com.google.common.collect.EmptyImmutableTableTest();
  testCase.testToString();
}

public void testValues() throws Exception {
  com.google.common.collect.EmptyImmutableTableTest testCase = new com.google.common.collect.EmptyImmutableTableTest();
  testCase.testValues();
}
}


text:
module ClusterFsck
  class Reader
    include S3Methods

    LOCAL_OVERRIDE_DIR = "clusterfsck"
    SHARED_ENV = "shared"

    attr_reader :cluster_fsck_env, :key, :version_count
    def initialize(key, opts={})
      @key = key
      @cluster_fsck_env = opts[:cluster_fsck_env] || ClusterFsck.cluster_fsck_env
      @ignore_local = opts[:ignore_local]
    end

    def set_cluster_fsck_env_to_shared_unless_key_found!
      unless has_local_override? or stored_object.exists?
        original_cluster_fsck_env = @cluster_fsck_env
        @cluster_fsck_env = SHARED_ENV
        raise KeyDoesNotExistError, "there was no #{key} in either #{original_cluster_fsck_env} or #{SHARED_ENV}" unless stored_object(true).exists?
      end
    end

    def read(opts = {})
      set_cluster_fsck_env_to_shared_unless_key_found!
      yaml = data_for_key(opts)
      if yaml
        @version_count = stored_object.versions.count unless has_local_override?
        Configuration.from_yaml(yaml)
      end
    end

    def has_local_override?
      File.exists?(local_override_path)
    end

    def local_override_path
      File.join(LOCAL_OVERRIDE_DIR, full_s3_path(key))
    end

  private
    def data_for_key(opts = {})
      if has_local_override? and !opts[:remote_only]
        File.read(local_override_path)
      else
        stored_object.read
      end
    end

    def stored_object(reload = false)
      return @stored_object if @stored_object and !reload
      @stored_object = s3_object(key)
    end

  end
end

redpajama_set_name: RedPajamaGithub


text:
from sqlalchemy import *
from migrate import *

from migrate.changeset import schema
pre_meta = MetaData()
post_meta = MetaData()
access_event = Table('access_event', post_meta,
    Column('id', Integer, primary_key=True, nullable=False),
    Column('rfid_tag', String(length=20)),
    Column('user_id', Integer),
    Column('event_date', DateTime),
    Column('access_granted', Boolean, default=ColumnDefault(False)),
)

def upgrade(migrate_engine):
    # Upgrade operations go here. Don't create your own engine; bind
    # migrate_engine to your metadata
    pre_meta.bind = migrate_engine
    post_meta.bind = migrate_engine
    post_meta.tables['access_event'].create()

def downgrade(migrate_engine):
    # Operations to reverse the above upgrade go here.
    pre_meta.bind = migrate_engine
    post_meta.bind = migrate_engine
    post_meta.tables['access_event'].drop()


text:
/******************************************************************************\
*
* File:          Transform.h
* Creation date: January 15, 2002
* Purpose:       Declaration of class 'Transform'
*
\******************************************************************************/
#ifndef _TRANSFORM_H
#define _TRANSFORM_H

#include "Template.h"

/**
* CSLTransform class
* This class handles the transformation matrix of a model. It provides functions to set
* the local scaling, rotation and position of the model and also provides easy and fast
* access to the model's global tranform.
*/
class XSIEXPORT CSLTransform
    : public CSLTemplate
{
public:
    CSLTransform(CSLScene* in_pScene, CSLModel *in_pModel, CdotXSITemplate* in_pTemplate);
    virtual ~CSLTransform();

	/*!	Return the transformation matrix.
		\return	CSIBCMatrix4x4	Transformation matrix.
	*/
	CSIBCMatrix4x4 GetMatrix();

	/*!	Change the transformation matrix.
		\param	CSIBCMatrix4x4&	New Transformation matrix.
		\return	None
	*/
	SI_Void SetMatrix(CSIBCMatrix4x4 &in_rValue);

	/*!	Return the actual rotation in euler representation.
		\return	CSIBCVector3D	Rotation value.
	*/
	CSIBCVector3D GetEulerRotation();

	/*!	Change the rotation value in euler representation.
		\param	CSIBCVector3D&	New rotation value
		\return	None
	*/
	SI_Void SetEulerRotation(CSIBCVector3D &in_rValue);

	/*!	Return the actual scale.
		\return	CSIBCVector3D	Scale value.
	*/
	CSIBCVector3D GetScale();

	/*!	Change the scale value.
		\param	CSIBCVector3D&	New scale value
		\return	None
	*/
	SI_Void SetScale(CSIBCVector3D &in_rValue);

	/*!	Return the actual translation.
		\return	CSIBCVector3D	Translation value.
	*/
	CSIBCVector3D GetTranslation();

	/*!	Change the translation value.
		\param	CSIBCVector3D&	New translation value
		\return	None
	*/
	SI_Void SetTranslation(CSIBCVector3D &in_rValue);

	/*!	Computes this CSLTransform's local matrix.
	\return	Error code
	*/
	SI_Error ComputeLocalMatrix();

	/*!	Computes this CSLTransform's global matrix.
	\return	Error code
	*/
	SI_Error ComputeGlobalMatrix();

	/*!	Returns the global matrix
		\return	CSIBCMatrix4x4 The global matrix
	*/
	CSIBCMatrix4x4 &GetGlobalMatrix();

	/*!	Sets the global transformation matrix.
		\param	CSIBCMatrix4x4&	New Transformation matrix.
		\return	None
	*/
	SI_Void SetGlobalMatrix(CSIBCMatrix4x4 &in_rValue);

	virtual CSLAnimatableType* ParameterFromName(SI_Char *in_szName);
    virtual CSLAnimatableType* ParameterFromType(EFCurveType in_Type, SI_Char *in_szParameterName);
    virtual ETemplateType Type();

private:
    CSLVector3DProxy m_Scale;
    CSLVector3DProxy m_Rotation;
    CSLVector3DProxy m_Translation;
	CSIBCMatrix4x4 m_TransformMatrix;
	CSIBCMatrix4x4 m_GlobalMatrix;

	void *m_pReserved;	// reserved for future extension
};

#endif


text:
module Fog
  module Zerigo
    class DNS < Fog::Service

      requires :zerigo_email, :zerigo_token
      recognizes :timeout, :persistent
      recognizes :provider # remove post deprecation

      model_path 'fog/dns/models/zerigo'
      model       :record
      collection  :records
      model       :zone
      collection  :zones

      request_path 'fog/dns/requests/zerigo'
      request :count_hosts
      request :count_zones
      request :create_host
      request :create_zone
      request :delete_host
      request :delete_zone
      request :find_hosts
      request :get_host
      request :get_zone
      request :get_zone_stats
      request :list_zones
      request :list_hosts
      request :update_host
      request :update_zone

      class Mock

        def self.data
          @data ||= Hash.new do |hash, key|
            hash[key] = {}
          end
        end

        def initialize(options={})
          unless options.delete(:provider)
            location = caller.first
            warning = "[yellow][WARN] Fog::Zerigo::DNS.new is deprecated, use Fog::DNS.new(:provider => 'Zerigo') instead[/]"
            warning << " [light_black](" << location << ")[/] "
            Formatador.display_line(warning)
          end

          @zerigo_email = options[:zerigo_email]
          @zerigo_token = options[:zerigo_token]
          @data = self.class.data[@zerigo_email]
        end

        def reset_data
          self.class.data.delete(@zerigo_email)
          @data = self.class.data[@zerigo_email]
        end

      end

      class Real

        def initialize(options={})
          unless options.delete(:provider)
            location = caller.first
            warning = "[yellow][WARN] Fog::Zerigo::DNS.new is deprecated, use Fog::DNS.new(:provider => 'Zerigo') instead[/]"
            warning << " [light_black](" << location << ")[/] "
            Formatador.display_line(warning)
          end

          require 'fog/core/parser'

          @zerigo_email  = options[:zerigo_email]
          @zerigo_token  = options[:zerigo_token]
          @host   = options[:host]    || "ns.zerigo.com"
          @port   = options[:port]    || 80
          @scheme = options[:scheme]  || 'http'
          @connection = Fog::Connection.new("#{@scheme}://#{@host}:#{@port}", options[:persistent])
        end

        def reload
          @connection.reset
        end

        def request(params)
          params[:headers] ||= {}
          key= "#{@zerigo_email}:#{@zerigo_token}"
          params[:headers].merge!({
            'Authorization' => "Basic #{Base64.encode64(key).delete("\r\n")}"
          })
          case params[:method]
          when 'DELETE', 'GET', 'HEAD'
            params[:headers]['Accept'] = 'application/xml'
          when 'POST', 'PUT'
            params[:headers]['Content-Type'] = 'application/xml'
          end

          begin
            response = @connection.request(params.merge!({:host => @host}))
          rescue Excon::Errors::HTTPStatusError => error
            raise case error
            when Excon::Errors::NotFound
              Fog::Zerigo::DNS::NotFound.slurp(error)
            else
              error
            end
          end

          response
        end

      end
    end
  end
end


text:
package eta.runtime.thunk;

import eta.runtime.stg.Closure;
import eta.runtime.stg.StgContext;

public class ApF extends UpdatableThunk {
    public Closure p1;
    public float p2;

    public ApF(final Closure p1, final float p2) {
        super();
        this.p1 = p1;
        this.p2 = p2;
    }

    @Override
    public Closure thunkEnter(StgContext context) {
        return p1.applyF(context, p2);
    }
}


text:
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using System;
using System.Collections.Immutable;

namespace Microsoft.CodeAnalysis.FindReferences
{
    internal partial class DefinitionItem
    {
        /// <summary>
        /// Implementation of a <see cref="DefinitionItem"/> that sits on top of a
        /// <see cref="DocumentLocation"/>.
        /// </summary>
        // internal for testing purposes.
        internal sealed class DocumentLocationDefinitionItem : DefinitionItem
        {
            internal override bool IsExternal => false;

            public DocumentLocationDefinitionItem(
                ImmutableArray<string> tags,
                ImmutableArray<TaggedText> displayParts,
                ImmutableArray<DocumentLocation> sourceLocations,
                bool displayIfNoReferences)
                : base(tags, displayParts,
                      ImmutableArray.Create(new TaggedText(TextTags.Text, sourceLocations[0].Document.Project.Name)),
                      sourceLocations, displayIfNoReferences)
            {
            }

            public override bool CanNavigateTo() => SourceLocations[0].CanNavigateTo();
            public override bool TryNavigateTo() => SourceLocations[0].TryNavigateTo();
        }
    }
}


text:
from swgpy.object import *

def create(kernel):
	result = Tangible()

	result.template = "object/tangible/lair/langlatch/shared_lair_langlatch_forest.iff"
	result.attribute_template_id = -1
	result.stfName("lair_n","langlatch_forest")

	#### BEGIN MODIFICATIONS ####
	####  END MODIFICATIONS  ####

	return result


text:
package com.visionarts.powerjambda.utils;

import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.stream.Stream;

import com.google.common.collect.ImmutableMap;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;

import static com.visionarts.powerjambda.utils.FunctionalUtils.toBiConsumer;
import static com.visionarts.powerjambda.utils.FunctionalUtils.toConsumer;
import static org.junit.Assert.assertEquals;

/**
 * Test case for FunctionalUtils.
 *
 */
public class FunctionalUtilsTest {

    @Rule
    public ExpectedException thrown = ExpectedException.none();

    private static final Logger logger = LogManager.getLogger(FunctionalUtilsTest.class);

    @Test
    public void isEmptyTest() {
        assertEquals(true, FunctionalUtils.isEmpty((Collection<?>)null));
        assertEquals(true, FunctionalUtils.isEmpty(Collections.emptyList()));

        assertEquals(true, FunctionalUtils.isEmpty((String)null));
        assertEquals(true, FunctionalUtils.isEmpty(""));
    }

    @Test
    public void isNotEmptyTest() {
        assertEquals(true, FunctionalUtils.isNotEmpty(Arrays.asList("a")));

        assertEquals(true, FunctionalUtils.isNotEmpty("a"));
    }

    @Test
    public void canUseConsumerThatThrowsCheckedExceptionInLambda() {
        Stream.of(false).forEach(toConsumer(this::consumerMethodWithChecked, logger));
    }

    @Test
    public void exceptionsForConsumersAreConverted() {
        thrown.expect(RuntimeException.class);
        thrown.expectMessage("Duh, something went wrong");

        Stream.of(true).forEach(toConsumer(this::consumerMethodWithChecked, logger));
    }

    @Test
    public void canUseBiConsumerThatThrowsCheckedExceptionInLambda() {
        ImmutableMap.of(false, "dummy")
                .forEach(toBiConsumer(this::biConsumerMethodWithChecked, logger));
    }

    @Test
    public void exceptionsForBiConsumersAreConverted() {
        thrown.expect(RuntimeException.class);
        thrown.expectMessage("Duh, something went wrong dummy");

        ImmutableMap.of(true, "dummy")
                .forEach(toBiConsumer(this::biConsumerMethodWithChecked, logger));
    }

    private void consumerMethodWithChecked(Boolean shouldThrow) throws Exception {
        if (shouldThrow) {
            throw new Exception("Duh, something went wrong");
        }
    }

    private void biConsumerMethodWithChecked(Boolean shouldThrow, String dummy) throws Exception {
        if (shouldThrow) {
            throw new Exception("Duh, something went wrong " + dummy);
        }
    }
}


text:
{% include css/bootstrap.min.css %}

{{ content }}


text:
package com.github.joschi.jadconfig.guice;

import com.github.joschi.jadconfig.JadConfig;
import com.github.joschi.jadconfig.Parameter;
import com.github.joschi.jadconfig.Repository;
import com.github.joschi.jadconfig.RepositoryException;
import com.github.joschi.jadconfig.ValidationException;
import com.github.joschi.jadconfig.repositories.PropertiesRepository;
import com.github.joschi.jadconfig.testbeans.EmptyBean;
import com.github.joschi.jadconfig.testbeans.SimpleConfigurationBean;
import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Injector;
import org.junit.Before;
import org.junit.Test;

import javax.annotation.Nullable;
import javax.inject.Inject;
import javax.inject.Named;
import java.io.File;
import java.net.URI;
import java.util.Collections;
import java.util.List;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;

public class NamedConfigParametersModuleTest {
    private static final String PROPERTIES_FILE = PropertiesRepository.class.getResource("/testConfiguration.properties").getFile();

    private Repository repository;

    @Before
    public void setUp() {
        repository = new PropertiesRepository(PROPERTIES_FILE);
    }

    @Test
    public void testEmptyBean() throws RepositoryException, ValidationException {
        final EmptyBean emptyBean = new EmptyBean();
        final Injector injector = Guice.createInjector(new NamedConfigParametersModule(Collections.singleton(emptyBean)));

        assertSame(emptyBean, injector.getInstance(EmptyBean.class));
    }

    @Test
    public void testDoNotRegisterBeans() throws RepositoryException, ValidationException {
        final EmptyBean emptyBean = new EmptyBean();
        final Injector injector = Guice.createInjector(new NamedConfigParametersModule(Collections.singleton(emptyBean), false));

        assertNotSame(emptyBean, injector.getInstance(EmptyBean.class));
    }

    @Test
    public void testNamedParameters() throws RepositoryException, ValidationException {
        SimpleConfigurationBean bean = new SimpleConfigurationBean();
        new JadConfig(repository, bean).process();

        final Injector injector = Guice.createInjector(new NamedConfigParametersModule(Collections.singleton(bean)),
                new AbstractModule() {
                    @Override
                    protected void configure() {
                        bind(NamedParametersBean.class);
                    }
                });

        final NamedParametersBean namedParametersBean = injector.getInstance(NamedParametersBean.class);

        assertEquals(bean.getMyString(), namedParametersBean.myString);
    }

    @Test
    public void testNullValuedParameters() throws ValidationException, RepositoryException {
        NullValueBean bean = new NullValueBean();
        new JadConfig(repository, bean).process();

        final Injector injector = Guice.createInjector(new NamedConfigParametersModule(Collections.singleton(bean)),
                new AbstractModule() {
                    @Override
                    protected void configure() {
                        bind(NullTargetBean.class);
                    }
                });

        final NullTargetBean nullTargetBean = injector.getInstance(NullTargetBean.class);

        assertNull(nullTargetBean.target);
    }

    public static final class NullValueBean {
        @Parameter("null-test")
        public Object source = null;
    }

    public static final class NullTargetBean {
        @Inject
        @Named("null-test")
        @Nullable
        public Object target = new Object();
    }

    public static final class NamedParametersBean {
        @Inject
        @Named("test.string")
        private String myString;

        @Inject
        @Named("test.byte")
        private byte myByte;

        @Inject
        @Named("test.short")
        private short myShort;

        @Inject
        @Named("test.integer")
        private int myInt;

        @Inject
        @Named("test.long")
        private long myLong;

        @Inject
        @Named("test.float")
        private float myFloat;

        @Inject
        @Named("test.double")
        private double myDouble;

        @Inject
        @Named("test.boolean")
        private boolean myBoolean;

        @Inject
        @Named("test.list")
        private List<String> stringList;

        @Inject
        @Named("test.uri")
        private URI uri;

        @Inject
        @Named("test.file")
        private File file;
    }

}


text:
package com.streamsets.pipeline.lib.jdbc;

import com.streamsets.pipeline.api.StageException;
import com.streamsets.pipeline.api.Stage.Context;
import com.streamsets.pipeline.lib.operation.ChangeLogFormat;
import com.streamsets.pipeline.lib.operation.OperationType;
import com.streamsets.pipeline.lib.operation.UnsupportedOperationAction;
import com.zaxxer.hikari.HikariDataSource;

import java.util.List;

public final class JdbcRecordReaderWriterFactory {

  private JdbcRecordReaderWriterFactory(){}

  // Called by JdbcTarget
  public static JdbcRecordWriter createJdbcRecordWriter(
      String connectionString,
      HikariDataSource dataSource,
      String schema,
      String tableName,
      List<JdbcFieldColumnParamMapping> customMappings,
      boolean rollbackOnError,
      boolean useMultiRowOp,
      int maxPrepStmtParameters,
      int defaultOpCode,
      UnsupportedOperationAction unsupportedAction,
      DuplicateKeyAction duplicateKeyAction,
      JdbcRecordReader recordReader,
      boolean caseSensitive,
      List<String> customDataSqlStateCodes,
      Context context
  ) throws StageException {
    if (defaultOpCode == OperationType.LOAD_CODE) {
      return new JdbcLoadRecordWriter(
          connectionString,
          dataSource,
          schema,
          tableName,
          customMappings,
          duplicateKeyAction,
          recordReader,
          caseSensitive,
          customDataSqlStateCodes
      );
    } else {
      return createJdbcRecordWriter(
          connectionString,
          dataSource,
          schema,
          tableName,
          customMappings,
          null,
          rollbackOnError,
          useMultiRowOp,
          maxPrepStmtParameters,
          defaultOpCode,
          unsupportedAction,
          recordReader,
          caseSensitive,
          customDataSqlStateCodes,
          context
      );
    }
  }

  // Called by JdbcTeeProcessor
  public static JdbcRecordWriter createJdbcRecordWriter(
       String connectionString,
       HikariDataSource dataSource,
       String schema,
       String tableName,
       List<JdbcFieldColumnParamMapping> customMappings,
       List<JdbcFieldColumnMapping> generatedColumnMappings,
       boolean rollbackOnError,
       boolean useMultiRowOp,
       int maxPrepStmtParameters,
       int defaultOpCode,
       UnsupportedOperationAction unsupportedAction,
       JdbcRecordReader recordReader,
       boolean caseSensitive,
       List<String> customDataSqlStateCodes,
       Context context
  ) throws StageException {

    JdbcRecordWriter recordWriter;

    if (useMultiRowOp) {
      recordWriter = new JdbcMultiRowRecordWriter(
          connectionString,
          dataSource,
          schema,
          tableName,
          rollbackOnError,
          customMappings,
          maxPrepStmtParameters,
          defaultOpCode,
          unsupportedAction,
          generatedColumnMappings,
          recordReader,
          caseSensitive,
          customDataSqlStateCodes,
          context
      );
    } else {
      recordWriter = new JdbcGenericRecordWriter(
          connectionString,
          dataSource,
          schema,
          tableName,
          rollbackOnError,
          customMappings,
          defaultOpCode,
          unsupportedAction,
          generatedColumnMappings,
          recordReader,
          caseSensitive,
          customDataSqlStateCodes,
          true,
          context
      );
    }
    return recordWriter;
  }

  public static JdbcRecordReader createRecordReader(ChangeLogFormat changeLogFormat){
    JdbcRecordReader recordReader;
    switch (changeLogFormat) {
      case MSSQL:
        recordReader = new JdbcMicrosoftRecordReader();
        break;
      case OracleCDC:
        recordReader = new JdbcOracleCDCRecordReader();
        break;
      case NONE:
        recordReader = new JdbcRecordReader();
        break;
      case MySQLBinLog:
        recordReader = new JdbcMySqlBinLogRecordReader();
        break;
      case MongoDBOpLog:
        recordReader = new JdbcMongoDBOplogRecordReader();
        break;
      default:
        throw new IllegalStateException("Unrecognized format specified: " + changeLogFormat);
    }
    return recordReader;
  }
}


text:
package org.classdump.luna.parser.ast;

import java.util.Objects;

public final class SourceInfo {

  private final int line;
  private final int column;

  public SourceInfo(int line, int column) {
    this.line = line;
    this.column = column;
  }

  @Override
  public boolean equals(Object o) {
    if (this == o) {
      return true;
    }
    if (o == null || getClass() != o.getClass()) {
      return false;
    }
    SourceInfo that = (SourceInfo) o;
    return this.line == that.line && this.column == that.column;
  }

  @Override
  public int hashCode() {
    return Objects.hash(line, column);
  }

  @Override
  public String toString() {
    return line + ":" + column;
  }

  public int line() {
    return line;
  }

  public int column() {
    return column;
  }

}


text:
var util = require("util"),
    fs = require("fs"),
    path = require("path"),
    mongodb = require("mongodb"),
    mongoConnectionProvider = require("../jaydata/mongoConnectionProvider.js");

var GridFSBlobStorage = module.exports = function(connectionString) {

    if (!connectionString){
        throw new Error("connectionString must be provided when using gridFS blob storage.");
    }

    if (connectionString.name.toString() !== "mongoDB"){
        throw new Error("connectionString.name must be mongoDB when using gridFS blob storage");
    }

    this.connectionProvider = mongoConnectionProvider(connectionString);
};

GridFSBlobStorage.prototype.write = function(blobName, inputStream, cb) {
    this.connectionProvider(function(err, db) {
        if (err) {
            return cb(err);
        }

        var gs = new mongodb.GridStore(db, blobName, "w", { "chunk_size": 1024 * 4 });
        gs.open(function() {
            gs.write(inputStream, function(err, gs) {
                gs.close(function() {
                    cb(err, blobName);
                });
            });
        });
    });
};

GridFSBlobStorage.prototype.read = function(blobName, cb) {
    this.connectionProvider(function(err, db) {
        if (err) {
            return cb(err);
        }

        var gs = new mongodb.GridStore(db, blobName, "r", { "chunk_size": 1024 * 4 });
        gs.open(function() {
            try {
                cb(null, gs.stream(true));
            }
            catch(e) {
                cb(e);
            }
        });
    });
};


text:
Protective Load Balancing (PLB) is a host based load balancing mechanism
for data center networks developed at Google. PLB builds on top of ECMP
which is the de facto standard mechanism to map flows to egress links in
data center networks. On a high level, PLB senses congestion and upon
meeting a threshold, makes the TCP connection probabilistically switch
to a different path in the network. More details about PLB are
available in SIGCOMM 2022 paper:
  https://doi.org/10.1145/3544216.3544226

# TCP-PLB Open Source

TCP-PLB is open source with two implementation flavors.

## Linux Upstream

PLB support for TCP has been merged into net-next and is slated to be in
Linux v6.2. Additionally, PLB is hooked up to DCTCP but is disabled by
default. net-next commit URLs are listed below

https://git.kernel.org/pub/scm/linux/kernel/git/netdev/net-next.git/commit/?id=bd456f283b66
https://git.kernel.org/pub/scm/linux/kernel/git/netdev/net-next.git/commit/?id=1a91bb7c3ebf
https://git.kernel.org/pub/scm/linux/kernel/git/netdev/net-next.git/commit/?id=c30f8e0b0480
https://git.kernel.org/pub/scm/linux/kernel/git/netdev/net-next.git/commit/?id=29c1c44646ae
https://git.kernel.org/pub/scm/linux/kernel/git/netdev/net-next.git/commit/?id=29c1c44646ae

For more information on how to enable PLB, either consult the PLB paper or lookup the sysctl
documentation under //Documentation/networking/ip-sysctl.rst

## BBR Open Source Repo

TCP-PLB was added to open source BBR repository in v2alpha branch with
the following commit

https://github.com/google/bbr/commit/cf9b1dacabb1ef62481a452f7f169e1679e2da49

More details on how to compile and run the kernel can be found in the
v2alpha branch documentation

https://github.com/google/bbr/tree/v2alpha

# Contact

Please email plb-contact@google.com with any queries


text:
var map;

function initializePlaces() {
  // Change map type when user finishes deciding which to choose
  $('#place_config_maptype').on('change', changeMapType);
  // Clear places preview
  $('#preview_div').html("");
  // Draw the map on initial page load
  drawMap();
}

function changeMapType() {
  // Switch Map Type
  var mapType = $('#place_config_maptype').val().toLowerCase();
  map.setMapTypeId(mapType);
}

function clearMap(prevMapMarker) {
  if (prevMapMarker) {
    // Remove previous map marker
    prevMapMarker.setMap(null);
  }
  // Clear places data in hidden form field
  $('#place_config_map_details').val("");
}

function placesPreview() {
  // Clear places preview
  $('#preview_div').html("");

  // When changes are made to places input, get places data and build preview
  var placesData = $('#place_config_map_details').val().split("|");
  var placeAddress = placesData[0];
  var placePhoto = placesData[1];

  $('#preview_div').html("");
  var preview = "";
  if (placePhoto != "NONE") {
    preview += "";
  }
  preview += "
" + placeAddress + "
";

  $('#preview_div').html(preview);
}

function drawMap() {

  var mapType = $('#place_config_maptype').val().toLowerCase();
    // Create map based on which map type the user specifies
  if (mapType == "roadmap") {
    map = new google.maps.Map($('#mapResults')[0], {
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });
  } else {
    map = new google.maps.Map($('#mapResults')[0], {
      mapTypeId: google.maps.MapTypeId.TERRAIN
    });
  }

  // Set default bounds on our map
  var defaultBounds = new google.maps.LatLngBounds(
    new google.maps.LatLng(27.751608, -121.464844),
    new google.maps.LatLng(49.350177, -63.105469));
  map.fitBounds(defaultBounds);

  // Create a search box to find places
  var input = ($('#target')[0]);
  var searchBox = new google.maps.places.SearchBox(input);

  // Keep track of map details for future recreation
  var placePhoto = "";
  var placeAddress = "";

  // Keep track of previous marker
  var prevMapMarker;

  // Create new markers whenever search box input changes
  var bounds = new google.maps.LatLngBounds();
  google.maps.event.addListener(searchBox, 'places_changed', function() {

    // Clear previous marker and details
    clearMap(prevMapMarker);

    var places = searchBox.getPlaces();

    // Create a marker image, the marker itself, and place it on the map
    var place = places[0];
    var image = {
       url: place.icon,
       size: new google.maps.Size(71, 71),
       origin: new google.maps.Point(0, 0),
       anchor: new google.maps.Point(17, 34),
       scaledSize: new google.maps.Size(25, 25)
     };
    var marker = new google.maps.Marker({
      map: map,
      icon: image,
      title: place.name,
      position: place.geometry.location
    });

    // Save reference to our marker for future deletion
    prevMapMarker = marker;

    console.log(place);

    // Get place address and photo
    if (place.photos) {
      placePhoto = place.photos[0].getUrl({'maxWidth': 9600, 'maxHeight': 7200});
    } else {
      placePhoto = "NONE";
    }
    placeAddress = place.formatted_address;

    // Store place information for content submission
    $('#place_config_map_details').val(placeAddress + "|" + placePhoto);

    // Change map bounds to fit places
    bounds.extend(place.geometry.location);
    map.fitBounds(bounds);

    placesPreview();

  });

  google.maps.event.addListener(map, 'bounds_changed', function() {
    var bounds = map.getBounds();
    searchBox.setBounds(bounds);
  });
}


text:
<?php

// @codingStandardsIgnoreFile

namespace Magento\Backend\Test\Unit\Controller\Adminhtml\Dashboard;

/**
 * Test for \Magento\Backend\Controller\Adminhtml\Dashboard\CustomersMost
 */
class CustomersMostTest extends AbstractTestCase
{
    public function testExecute()
    {
        $this->assertExecute(
            'Magento\Backend\Controller\Adminhtml\Dashboard\CustomersMost',
            'Magento\Backend\Block\Dashboard\Tab\Customers\Most'
        );
    }
}


text:
Gokogiri
========
[![Build Status](https://travis-ci.org/jbowtie/gokogiri.svg?branch=master)](https://travis-ci.org/jbowtie/gokogiri)
[![codecov.io](http://codecov.io/github/jbowtie/gokogiri/coverage.svg?branch=master)](http://codecov.io/github/jbowtie/gokogiri?branch=master)

LibXML bindings for the Go programming language.
------------------------------------------------
By Zhigang Chen and Hampton Catlin

This is a major rewrite from v0 in the following places:

- Separation of XML and HTML
- Put more burden of memory allocation/deallocation on Go
- Fragment parsing -- no more deep-copy
- Serialization
- Some API adjustment

To install:

- sudo apt-get install libxml2-dev libonig-dev
- go get github.com/jbowtie/gokogiri

To run test:

- go test github.com/jbowtie/gokogiri/html
- go test github.com/jbowtie/gokogiri/xml

Basic example:

    package main

    import (
      "net/http"
      "io/ioutil"
      "github.com/jbowtie/gokogiri"
    )

    func main() {
      // fetch and read a web page
      resp, _ := http.Get("http://www.google.com")
      page, _ := ioutil.ReadAll(resp.Body)

      // parse the web page
      doc, _ := gokogiri.ParseHtml(page)

      // perform operations on the parsed page -- consult the tests for examples

      // important -- don't forget to free the resources when you're done!
      doc.Free()
    }


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

<title>Minim : : Waves : : add</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<link href="stylesheet.css" rel="stylesheet" type="text/css">

    	Minim

    		core |
    		ugens |
    		analysis

Waves

add

Description

    	Generates a Wavetable by adding any number of Waveforms, each scaled by an amplitude.

 Calling this method might look like:

 Wavetable wave = Wavetable.add( new float[] { 0.8f, 0.2f }, Waves.SINE, Waves.SAW );

 or:

 Wavetable wave = Wavetable.add( new float[] { 0.2f, 0.3f, 0.5f }, Waves.SINE, Waves.SQUARE, Waves.sawh( 6 ) );

 In other words, the number of elements in the amplitude array
 must match the number of Waveform arguments provided.

Signature

Wavetable add(float[] amps, ddf.minim.ugens.Waveform[] waves)

Parameters

        amps — float[]: an array of amplitudes used to scale the matching Waveform argument
 					 when adding it into the final Wavetable.

        waves — Waveform vararg: The Waveforms to be added together. The number of Waveforms
 			passed in as arguments much match the length of the amps array.

Returns

a Wavetable

Related

    	Waves

Waveform

Wavetable

Example

/* waveformExample<br/>
   is an example of how to construct different waveforms
   for different tones from an oscillator.
   <p>
   For more information about Minim and additional features, visit http://code.compartmental.net/minim/
   <p>
   author: Anderson Mills<br/>
   Anderson Mills's work is supported by numediart (www.numediart.org).
*/

// import everything necessary to make sound.
import ddf.minim.*;
import ddf.minim.ugens.*;

// create all of the variables that will need to be accessed in
// more than one method (setup(), draw()).
Minim minim;
AudioOutput out;

// Every instrument must implement the Instrument interface so
// playNote() can call the instrument's methods.
class ToneInstrument implements Instrument
{
  // create all variables that must be used throughout the class
  Oscil toneOsc;
  ADSR adsr;
  AudioOutput out;

  // constructors for this intsrument
  ToneInstrument( String note, float amplitude, Waveform wave, AudioOutput output )
  {
    // equate class variables to constructor variables as necessary
    out = output;

    // make any calculations necessary for the new UGen objects
    // this turns a note name into a frequency
    float frequency = Frequency.ofPitch( note ).asHz();

    // create new instances of any UGen objects as necessary
    toneOsc = new Oscil( frequency, amplitude, wave );
    adsr = new ADSR( 1.0, 0.04, 0.01, 1.0, 0.1 );

    // patch everything together up to the final output
    toneOsc.patch( adsr );
  }

  // every instrument must have a noteOn( float ) method
  void noteOn( float dur )
  {
    // turn on the adsr
    adsr.noteOn();
    // patch the adsr into the output
    adsr.patch( out );
  }

  void noteOff()
  {
    // turn off the note in the adsr
    adsr.noteOff();
    // but don't unpatch until the release is through
    adsr.unpatchAfterRelease( out );
  }
}

// setup is run once at the beginning
void setup()
{
  // initialize the drawing window
  size( 512, 200, P2D );

  // initialize the minim and out objects
  minim = new Minim( this );
  out = minim.getLineOut( Minim.MONO, 1024 );

  // set a volume variable
  float vol = 0.45;

  // From here through the end of setup() is an example of traditional
  // composition, where every note is known completely beforehand.

  // set the tempo for here
  out.setTempo( 100.0f );
  // set a percentage for the actual duration
  out.setDurationFactor( 0.95f );
  // use pauseNotes to add a bunch of notes at once without time moving forward
  out.pauseNotes();

  // specify the waveform for this group of notes
  Waveform disWave = Waves.sawh( 4 );
  // add these notes with disWave
  out.playNote( 0.0, 1.0, new ToneInstrument( "E4 ", vol, disWave, out ) );
  out.playNote( 1.0, 1.0, new ToneInstrument( "E4 ", vol, disWave, out ) );
  out.playNote( 2.0, 1.0, new ToneInstrument( "E4 ", vol, disWave, out ) );
  out.playNote( 3.0, 0.75, new ToneInstrument( "C4 ", vol, disWave, out ) );
  out.playNote( 3.75, 0.25, new ToneInstrument( "G4 ", vol, disWave, out ) );
  out.playNote( 4.0, 1.0, new ToneInstrument( "E4 ", vol, disWave, out ) );
  out.playNote( 5.0, 0.75, new ToneInstrument( "C4 ", vol, disWave, out ) );
  out.playNote( 5.75, 0.25, new ToneInstrument( "G4 ", vol, disWave, out ) );
  out.playNote( 6.0, 2.0, new ToneInstrument( "E4 ", vol, disWave, out ) );

  // specify the waveform for this group of notes
  disWave = Waves.triangleh( 9 );
  // add these notes with disWave
  out.playNote( 8.0, 1.0, new ToneInstrument( "B4 ", vol, disWave, out ) );
  out.playNote( 9.0, 1.0, new ToneInstrument( "B4 ", vol, disWave, out ) );
  out.playNote(10.0, 1.0, new ToneInstrument( "B4 ", vol, disWave, out ) );
  out.playNote(11.0, 0.75, new ToneInstrument( "C5 ", vol, disWave, out ) );
  out.playNote(11.75, 0.25, new ToneInstrument( "G4 ", vol, disWave, out ) );
  out.playNote(12.0, 1.0, new ToneInstrument( "Eb4 ", vol, disWave, out ) );
  out.playNote(13.0, 0.75, new ToneInstrument( "C4 ", vol, disWave, out ) );
  out.playNote(13.75, 0.25, new ToneInstrument( "G4 ", vol, disWave, out ) );
  out.playNote(14.0, 2.0, new ToneInstrument( "E4 ", vol, disWave, out ) );

  // specify the waveform for this group of notes
  disWave = Waves.randomNOddHarms( 3 );
  // add these notes with disWave
  out.playNote( 0.0, 1.9, new ToneInstrument( "E3 ", vol, disWave, out ) );
  out.playNote( 2.0, 1.9, new ToneInstrument( "E3 ", vol, disWave, out ) );
  out.playNote( 4.0, 1.9, new ToneInstrument( "E3 ", vol, disWave, out ) );
  out.playNote( 6.0, 1.9, new ToneInstrument( "E3 ", vol, disWave, out ) );

  // specify the waveform for this group of notes
  disWave = Waves.TRIANGLE;
  // add these notes with disWave
  out.playNote( 8.0, 1.9, new ToneInstrument( "E3 ", vol, disWave, out ) );
  out.playNote(10.0, 1.9, new ToneInstrument( "E3 ", vol, disWave, out ) );
  out.playNote(12.0, 1.9, new ToneInstrument( "C3 ", vol, disWave, out ) );
  out.playNote(14.0, 1.9, new ToneInstrument( "E3 ", vol, disWave, out ) );

  //-----  this is effectively a section marker
  // all notes from here until the next setNoteOffset will have this offset added to them
  out.setNoteOffset( 16.0 );
  // specify the waveform for this group of notes
  disWave = Waves.triangle( 0.75 );
  // add these notes with disWave
  out.playNote( 0.0, 1.0, new ToneInstrument( "E5 ", vol, disWave, out ) );
  out.playNote( 1.0, 1.0, new ToneInstrument( "E4 ", vol, disWave, out ) );
  out.playNote( 2.0, 1.0, new ToneInstrument( "E5 ", vol, disWave, out ) );
  out.playNote( 3.0, 0.5, new ToneInstrument( "D#5", vol, disWave, out ) );
  out.playNote( 3.5, 0.5, new ToneInstrument( "D5 ", vol, disWave, out ) );
  out.playNote( 4.0, 0.25, new ToneInstrument( "Db5 ", vol, disWave, out ) );
  out.playNote( 4.25, 0.25, new ToneInstrument( "C5 ", vol, disWave, out ) );
  out.playNote( 4.5, 0.50, new ToneInstrument( "Db5 ", vol, disWave, out ) );
  out.playNote( 5.5, 0.5, new ToneInstrument( "F4 ", vol, disWave, out ) );
  out.playNote( 6.0, 1.0, new ToneInstrument( "Bb4 ", vol, disWave, out ) );
  out.playNote( 7.0, 0.5, new ToneInstrument( "A4 ", vol, disWave, out ) );
  out.playNote( 7.5, 0.5, new ToneInstrument( "Ab4 ", vol, disWave, out ) );

  // specify the waveform for this group of notes
  disWave = Waves.add( new float[] { 0.5, 0.5 }, Waves.triangle( 0.05 ), Waves.randomNOddHarms( 3 ) );
  // add these notes with disWave
  out.playNote( 8.0, 0.25, new ToneInstrument( "G4 ", vol, disWave, out ) );
  out.playNote( 8.25, 0.25, new ToneInstrument( "F#4 ", vol, disWave, out ) );
  out.playNote( 8.5, 0.50, new ToneInstrument( "G4 ", vol, disWave, out ) );
  out.playNote( 9.5, 0.5, new ToneInstrument( "C4 ", vol, disWave, out ) );
  out.playNote(10.0, 1.0, new ToneInstrument( "Eb4 ", vol, disWave, out ) );
  out.playNote(11.0, 0.75, new ToneInstrument( "C4 ", vol, disWave, out ) );
  out.playNote(11.75, 0.25, new ToneInstrument( "G4 ", vol, disWave, out ) );
  out.playNote(12.0, 1.0, new ToneInstrument( "E4 ", vol, disWave, out ) );
  out.playNote(13.0, 0.75, new ToneInstrument( "C4 ", vol, disWave, out ) );
  out.playNote(13.75, 0.25, new ToneInstrument( "G4 ", vol, disWave, out ) );
  out.playNote(14.0, 2.0, new ToneInstrument( "E4 ", vol, disWave, out ) );

  // specify the waveform for this group of notes
  disWave = Waves.randomNHarms( 9 );
  // add these notes with disWave
  out.playNote( 4.0, 1.9, new ToneInstrument( "Bb3 ", vol/2, disWave, out ) );
  out.playNote( 4.0, 1.9, new ToneInstrument( "F3 ", vol/2, disWave, out ) );
  out.playNote( 8.0, 1.9, new ToneInstrument( "C3 ", vol/2, disWave, out ) );
  out.playNote( 8.0, 1.9, new ToneInstrument( "Eb3 ", vol/2, disWave, out ) );
  out.playNote(10.0, 1.9, new ToneInstrument( "C3 ", vol, disWave, out ) );
  out.playNote(12.0, 1.9, new ToneInstrument( "E3 ", vol, disWave, out ) );
  out.playNote(14.0, 1.9, new ToneInstrument( "E3 ", vol, disWave, out ) );

  // use resumeNotes at the end of the section which needs guaranteed timing
  out.resumeNotes();
}

// draw is run many times
void draw()
{
  // erase the window to black
  background( 0 );
  // draw using a white stroke
  stroke( 255 );
  // draw the waveforms
  for( int i = 0; i < out.bufferSize() - 1; i++ )
  {
    // find the x position of each buffer value
    float x1  =  map( i, 0, out.bufferSize(), 0, width );
    float x2  =  map( i+1, 0, out.bufferSize(), 0, width );
    // draw a line from one buffer position to the next for both channels
    line( x1, 50 - out.left.get(i)*50, x2, 50 - out.left.get(i+1)*50);
    line( x1, 150 - out.right.get(i)*50, x2, 150 - out.right.get(i+1)*50);
  }
}

Usage

    	Web & Application


text:
layout: redirect
redirect: ../operations/tokenize_with_regex.html
---


text:
<?php
/**
 * This file is part of the Loops framework.
 *
 * @author Lukas <lukas@loopsframework.com>
 * @license https://raw.githubusercontent.com/loopsframework/base/master/LICENSE
 * @link https://github.com/loopsframework/base
 * @link https://loopsframework.com/
 * @version 0.1
 */

use Loops\Misc;
use Loops\Object;
use Loops\ArrayObject;
use Loops\Config\ArrayConfig;
use Loops\Annotations\Access\ReadOnly;

/**
 * The Loops Context
 *
 * The dependency injection class in the Loops framework that provides access to Loops services.
 * Services can be either registered by the registerService method or will be automatically created from classes in the Loops\Service namespace.
 */
class Loops extends Object {
    const VERSION = "0.1";

    /**
     * @var Loops The latest context that has been created.
     */
    private static $current_loops;

    /**
     * @var ArrayAccess The config directives that are used by this Loops context.
     */
    private $config;

    private $services = [];
    private $shared_instances = [];

    /**
     * @var bool Specifies if loops runs in debug mode
     * @ReadOnly
     */
    protected $debug;

    /**
     * Creates the Loops Context
     *
     * Values from the passed config object will be used when creating services on the fly (see getService).
     * The configuration should be stored in keys that are identical to service names.
     *
     * The config file will be made accessible as a service under the name 'config'.
     *
     * @param Loops\ArrayObject $serviceconfig The configuration will be used when creating services.
     */
    public function __construct(ArrayObject $config, $debug = TRUE) {
        $this->config = $config;
        $this->debug = $debug;

        Loops::$current_loops = $this;

        parent::__construct($this);

        $this->registerService("config", $config);
    }

    /**
     * Checks if a service exists
     *
     * @param string $name The name of the service
     * @param bool $resolve Specified if Loops should try to resolve unloaded services from the Loops\Service namespace.
     * @return bool TRUE if the service is registered (or can be created from the Loops\Service namespace if $resolve is TRUE, see getService for details)
     */
    public function hasService($name, $resolve = TRUE) {
        if(array_key_exists($name, $this->services)) {
            return TRUE;
        }

        if(!$resolve) {
            return FALSE;
        }

        $classname = "Loops\\Service\\".Misc::camelize($name);

        if(class_exists($classname)) {
            $reflection = new ReflectionClass($classname);

            if($reflection->implementsInterface("Loops\ServiceInterface")) {
                if(!$classname::hasService($this)) {
                    return FALSE;
                }
                $this->registerService($name, $classname, [], $classname::isShared($this));
            }
        }

        return $this->hasService($name, FALSE);
    }

    /**
     * Returns a service
     *
     * The requested service will be returned. If a service is shared (see Loops\Service\Service for details) the same instance will be returned on subsequent calls.
     * If a service has not been registered, Loops tries to find the service in the "Loops\Service" namespace. The classname is generated by camelizing (see Loops\Misc::camelize) the passed name.
     *
     * @param $name The service name
     * @return Loops\Service\ServiceInterface The requested service
     */
    public function getService($name) {
        if(!$this->hasService($name)) {
            throw new Exception("Service '$name' does not exist.");
        }

        if(array_key_exists($name, $this->shared_instances)) {
            return $this->shared_instances[$name];
        }

        $service = $this->createService($name, NULL, TRUE);

        if($this->services[$name]["shared"]) {
            $this->shared_instances[$name] = $service;
        }

        return $service;
    }

    /**
     * Creates a new instance of a service
     *
     * @param $name The service name
     * @param array $config
     * @return Loops\Service\ServiceInterface The new service
     */
    public function createService($name, ArrayObject $config = NULL, $merge_into_config = FALSE) {
        if($merge_into_config) {
            $service_config = $this->config->offsetExists($name) ? $this->config->offsetGet($name) : new ArrayObject;

            if(is_array($service_config)) {
                $service_config = ArrayObject::fromArray($service_config);
            }

            if($config) {
                $service_config->merge($config);
            }
        }
        else {
            $service_config = $config ?: new ArrayObject;
        }

        if(!$this->hasService($name)) {
            throw new Exception("Service '$name' does not exist.");
        }

        $service = $this->services[$name];

        if(array_key_exists("classname", $service)) {
            $reflection = new ReflectionClass($service["classname"]);

            $params = new ArrayObject($service["params"]);
            $params->merge($service_config);

            if($reflection->implementsInterface("Loops\ServiceInterface")) {
                return call_user_func_array([$service["classname"], "getService" ], [ $params, $this ]);
            }
            else {
                $params->offsetSet("loops", $this);
                return Misc::reflectionInstance($service["classname"], $params);
            }
        }

        if(array_key_exists("callback", $service)) {
            $params = new ArrayObject($service["params"]);
            $params->merge($service_config);
            return call_user_func_array($service["callback"], $params->toArray());
        }

        if(array_key_exists("object", $service)) {
            return $service["object"];
        }
    }

    /**
     * Registers a custom Service
     *
     * @param string $name The service name
     * @param mixed $service A service class name as string, a callable (which returns the service) or an Object that is the service itself.
     * @param array $params If $service is a string/callable: Parameters that are passed to the constructor/callable when the service is created.
     * @param bool $shared If the service is a string/callable, specify if the service should be shared.
     */
    public function registerService($name, $service, array $params = [], $shared = TRUE) {
        if(is_callable($service)) {
            $this->services[$name] = [ "shared" => $shared, "params" => $params, "callback" => $service ];
        }
        elseif(is_object($service)) {
            $this->services[$name] = [ "shared" => $shared, "object" => $service ];
        }
        elseif(is_string($service)) {
            $this->services[$name] = [ "shared" => $shared, "params" => $params, "classname" => $service ];
        }
        else {
            throw new Exception("Failed to register service.");
        }
    }

    /**
     * Returns the current default Context
     *
     * This will be the latest created instance of this class.
     * Normally, only a single context is created during a request.
     *
     * @return Loops\Context The current context
     */
    public static function getCurrentLoops() {
        if(!self::$current_loops) {
            throw new Exception("No Loops Context was created yet.");
        }

        return self::$current_loops;
    }
}


text:
module.exports = function(api) {
  api.plugin('my-custom-gradient', function(api, colors) {
    return {
      background: 'linear-gradient(to bottom, ' + colors.join(", ") + ')'
    };
  });
}


text:
class DataDisplayer

  def self.output(user_data)
    user_data.join("\n") << "\n"
  end
end


text:
layout:      post
title:       Flask Gunicorn Nginx Docker
category:    Python
description: Docker Support for Flask Deployment.
---

Before, we have a manual config approach to deploy Flask app on server, as talked in [THIS POST](https://30141592.xyz/python/2018/01/17/flask-gunicorn-nginx.html).
Now we use Docker to deploy the Flask app.

----------

## Gunicorn ##
Create a file `gunicorn.conf.py`:
```
bind = "0.0.0.0:8080"
workers = 4
```

----------

## Dockerfile ##

```
FROM python:3

WORKDIR /src

COPY requirements.txt ./
RUN pip install --no-cache-dir -r requirements.txt

COPY . .

ENTRYPOINT ["gunicorn", "--config", "/src/gunicorn.conf.py", "jav:app"]
```

----------

## Nginx ##
`vim /etc/nginx/nginx.conf`
```
http {
	server {
		listen 80;
		server_name www.404909.xyz 404909.xyz;

		error_page 497 https://$server_name$request_uri;
		location / {
			proxy_pass http://127.0.0.1:4000;
			proxy_set_header Host $host;
			proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
		}
	}
    ......
}
```

----------

## Dockerhub ##

Config an auto build task in dockerhub account, then dockerhub will build image with every push in your Github.

[![]({{site.baseurl}}/assets/img/dockerhub-autobuild.png)]({{site.baseurl}}/assets/img/dockerhub-autobuild.png)

----------

## Run ##

`sudo docker pull mjyang/goldenshark`
`sudo docker image ls`
`sudo docker ps -a`
`sudo docker stop CONTAINER_ID`
`sudo docker rm CONTAINER_ID`
`sudo docker image rm IMAGE_ID`
`sudo docker run -p 4000:8080 -d mjyang/goldenshark`
`-p` means port mapping, local prot : docker port
`-d` means background running


text:
package com.badlogic.gdx.tests.g3d;

import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.InputMultiplexer;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.PerspectiveCamera;
import com.badlogic.gdx.graphics.VertexAttributes.Usage;
import com.badlogic.gdx.graphics.g3d.Environment;
import com.badlogic.gdx.graphics.g3d.Material;
import com.badlogic.gdx.graphics.g3d.Model;
import com.badlogic.gdx.graphics.g3d.ModelBatch;
import com.badlogic.gdx.graphics.g3d.ModelInstance;
import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute;
import com.badlogic.gdx.graphics.g3d.environment.DirectionalLight;
import com.badlogic.gdx.graphics.g3d.utils.CameraInputController;
import com.badlogic.gdx.graphics.g3d.utils.ModelBuilder;
import com.badlogic.gdx.tests.utils.GdxTest;

public class FogTest extends GdxTest implements ApplicationListener {
	public PerspectiveCamera cam;
	public CameraInputController inputController;
	public ModelBatch modelBatch;
	public Model model;
	public ModelInstance instance;
	public Environment environment;

	@Override
	public void create () {
		modelBatch = new ModelBatch();
		environment = new Environment();
		environment.set(new ColorAttribute(ColorAttribute.AmbientLight, 0.4f, 0.4f, 0.4f, 1.f));
		environment.set(new ColorAttribute(ColorAttribute.Fog, 0.13f, 0.13f, 0.13f, 1f));
		environment.add(new DirectionalLight().set(0.8f, 0.8f, 0.8f, -1f, -0.8f, -0.2f));

		cam = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
		cam.position.set(30f, 10f, 30f);
		cam.lookAt(0, 0, 0);
		cam.near = 0.1f;
		cam.far = 45f;
		cam.update();

		ModelBuilder modelBuilder = new ModelBuilder();
		model = modelBuilder.createBox(5f, 5f, 5f, new Material(ColorAttribute.createDiffuse(Color.GREEN)), Usage.Position
			| Usage.Normal);
		instance = new ModelInstance(model);

		Gdx.input.setInputProcessor(new InputMultiplexer(this, inputController = new CameraInputController(cam)));
	}

	@Override
	public void render () {

		animate();

		inputController.update();

		Gdx.gl.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
		Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT);

		Gdx.gl.glClearColor(0.13f, 0.13f, 0.13f, 1);

		modelBatch.begin(cam);
		modelBatch.render(instance, environment);
		modelBatch.end();
	}

	float delta = 0f, dir = 1;

	private void animate () {

		delta = Gdx.graphics.getDeltaTime();

		instance.transform.val[14] += delta * 4 * dir;

		if (Math.abs(instance.transform.val[14]) > 5) {
			dir *= -1;
		}
	}

	@Override
	public void dispose () {
		modelBatch.dispose();
		model.dispose();
	}

	public boolean needsGL20 () {
		return true;
	}

	public void resume () {
	}

	public void resize (int width, int height) {
	}

	public void pause () {
	}
}


text:
package com.hctrom.romcontrol.otaupdater.misc;

public class Constants {
    public static final String BOOT_CHECK_COMPLETED = "boot_check_completed";
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE topic
  PUBLIC "-//OASIS//DTD DITA Composite//EN" "ditabase.dtd">
<topic id="topic13">
   <title>Using the Greenplum Parallel File Server (gpfdist)</title>

The <cmdname>gpfdist</cmdname> protocol provides the best performance and is the easiest to
         set up. <cmdname>gpfdist</cmdname> ensures optimum use of all segments in your Greenplum Database system for external table reads.

This topic describes the setup and management tasks for using <cmdname>gpfdist</cmdname>
         with external tables.

<xref href="#topic14" format="dita"/>

<xref href="#topic15" format="dita"/>

<xref href="#topic16" format="dita"/>

<xref href="#topic17" format="dita"/>

<xref href="#topic18" format="dita"/>

   <topic id="topic14">
      <title>About gpfdist Setup and Performance</title>

Consider the following scenarios for optimizing your ETL network performance.

Allow network traffic to use all ETL host Network Interface Cards
               (NICs) simultaneously. Run one instance of <cmdname>gpfdist</cmdname> on the ETL
               host, then declare the host name of each NIC in the <codeph>LOCATION</codeph> clause
               of your external table definition (see <xref
                  href="g-creating-external-tables---examples.xml#topic44"/>).

         <fig id="du165872">
            <title>External Table Using Single gpfdist Instance with Multiple NICs</title>
            <image href="../../graphics/ext_tables_multinic.jpg" placement="break" width="472px"
               height="271px" id="image_skb_plg_bbb"/>
         </fig>

Divide external table data equally among multiple
                  <cmdname>gpfdist</cmdname> instances on the ETL host. For example, on an ETL
               system with two NICs, run two <cmdname>gpfdist</cmdname> instances (one on each NIC)
               to optimize data load performance and divide the external table data files evenly
               between the two <cmdname>gpfdist</cmdname>s.

         <fig id="du165882">
            <title>External Tables Using Multiple gpfdist Instances with Multiple NICs</title>
            <image href="../../graphics/ext_tables.jpg" placement="break" width="467px"
               height="282px" id="image_ukb_plg_bbb"/>
         </fig>
         <note type="note">Use pipes (|) to separate formatted text when you submit files to
               <cmdname>gpfdist</cmdname>. Greenplum Database encloses comma-separated text strings
            in single or double quotes. <cmdname>gpfdist</cmdname> has to remove the quotes to parse
            the strings. Using pipes to separate formatted text avoids the extra step and improves
            performance.</note>

   </topic>
   <topic id="topic15">
      <title>Controlling Segment Parallelism</title>

The <codeph>gp_external_max_segs</codeph> server configuration parameter controls the
            number of segment instances that can access a single <cmdname>gpfdist</cmdname> instance
            simultaneously. 64 is the default. You can set the number of segments such that some
            segments process external data files and some perform other database processing. Set
            this parameter in the <codeph>postgresql.conf</codeph> file of your master instance.

   </topic>
   <topic id="topic16">
      <title>Installing gpfdist</title>

            <cmdname>gpfdist</cmdname> is installed in <codeph>$GPHOME/bin</codeph> of your
            Greenplum Database master host installation. Run <cmdname>gpfdist</cmdname> on a machine
            other than the Greenplum Database master or standby master, such as on a machine devoted
            to ETL processing. Running <cmdname>gpfdist</cmdname> on the master or standby master
            can have a performance impact on query execution. To install <cmdname>gpfdist</cmdname>
            on your ETL server, get it from the Greenplum Load Tools package and follow its
            installation instructions.

   </topic>
   <topic id="topic17">
      <title>Starting and Stopping gpfdist</title>

You can start <cmdname>gpfdist</cmdname> in your current directory location or in any
            directory that you specify. The default port is <codeph>8080</codeph>.

From your current directory, type:

            <codeblock>gpfdist &</codeblock>

From a different directory, specify the directory from which to serve files, and
            optionally, the HTTP port to run on.

To start <cmdname>gpfdist</cmdname> in the background and log output messages and errors
            to a log file:

            <codeblock>$ gpfdist -d /var/load_files -p 8081 -l /home/<codeph>gpadmin</codeph>/log &
</codeblock>

For multiple <cmdname>gpfdist</cmdname> instances on the same ETL host (see <xref
               href="#topic14/du165872" format="dita"/>), use a different base directory and port
            for each instance. For example:

            <codeblock>$ gpfdist -d /var/load_files1 -p 8081 -l /home/<codeph>gpadmin</codeph>/log1 &
$ gpfdist -d /var/load_files2 -p 8082 -l /home/<codeph>gpadmin</codeph>/log2 &
</codeblock>

To stop <cmdname>gpfdist</cmdname> when it is running in the background:

First find its process id:

            <codeblock>$ ps -ef | grep gpfdist</codeblock>

Then kill the process, for example (where 3456 is the process ID in this example):

            <codeblock>$ kill 3456
</codeblock>

   </topic>
   <topic id="topic18">
      <title>Troubleshooting gpfdist</title>

The segments access <cmdname>gpfdist</cmdname> at runtime. Ensure that the Greenplum
            segment hosts have network access to <cmdname>gpfdist</cmdname>.
               <cmdname>gpfdist</cmdname> is a web server: test connectivity by running the
            following command from each host in the Greenplum array (segments and master):

            <codeblock>$ wget http://gpfdist_hostname:port/filename
         </codeblock>

The <codeph>CREATE EXTERNAL TABLE</codeph> definition must have the correct host name,
            port, and file names for <cmdname>gpfdist</cmdname>. Specify file names and paths
            relative to the directory from which <cmdname>gpfdist</cmdname> serves files (the
            directory path specified when <cmdname>gpfdist</cmdname> started). See <xref
               href="g-creating-external-tables---examples.xml#topic44"/>.

If you start <cmdname>gpfdist</cmdname> on your system and IPv6 networking is disabled,
               <cmdname>gpfdist</cmdname> displays this warning message when testing for an IPv6
            port.

         <codeblock>[WRN gpfdist.c:2050] Creating the socket failed
</codeblock>

If the corresponding IPv4 port is available, <cmdname>gpfdist</cmdname> uses that port
            and the warning for IPv6 port can be ignored. To see information about the ports that
               <cmdname>gpfdist</cmdname> tests, use the <codeph>-V</codeph> option.

For information about IPv6 and IPv4 networking, see your operating system
            documentation.

When reading or writing data with the <codeph>gpfdist</codeph> or
               <codeph>gfdists</codeph> protocol, the <codeph>gpfdist</codeph> utility rejects HTTP
            requests that do not include <codeph>X-GP-PROTO</codeph> in the request header. If
               <codeph>X-GP-PROTO</codeph> is not detected in the header request
               <codeph>gpfist</codeph> returns a 400 error in the status line of the HTTP response
            header: <codeph>400 invalid request (no gp-proto)</codeph>.

Greenplum Database includes <codeph>X-GP-PROTO</codeph> in the HTTP request header to
            indicate that the request is from Greenplum Database.

   </topic>
</topic>


text:
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;

namespace EFConvention
{
    /// <summary>
    /// Performs seeding functions on a specific entity from the context.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public interface IEntitySeed<T> where T : class
    {
        /// <summary>
        /// Seed the entity
        /// </summary>
        /// <param name="entity"></param>
        void Seed(DbSet<T> entity);
    }
}


text:
package com.ait.lienzo.shared.core.types;

public interface DoublePowerFunction
{
    public double apply(double value);
}


text:
/**
 * This is a specialized field which shows a {@link Ext.picker.Time} when tapped. If it has a predefined value,
 * or a value is selected in the {@link Ext.picker.Time}, it will be displayed like a normal {@link Ext.field.Text}
 * (but not selectable/changable).
 *
 * ## Examples
 *
 * It can be very useful to set a default {@link #value} configuration on {@link Ext.field.DatePicker} fields. In
 * this example, we set the {@link #value} to be the current date. You can also use the {@link #setValue} method to
 * update the value at any time.
 *
 *     @example
 *     Ext.create('Ext.form.Panel', {
 *         fullscreen: true,
 *         items: [
 *             {
 *                 xtype: 'fieldset',
 *                 items: [
 *                     {
 *                         xtype: 'timepickerfield',
 *                         label: 'Start Time',
 *                         name: 'starttime',
 *                         value: new Date()
 *                     }
 *                 ]
 *             }
 *         ]
 *     });
 */
Ext.define( 'Ext.field.TimePicker', {
    extend: 'Ext.field.DatePicker',
    alternateClassName: 'Ext.form.TimePicker',
    xtype: 'timepickerfield',
    requires: [
        'Ext.picker.Time',
        'Ext.DateExtras'
    ],
    config: {
        /**
         * @cfg {String} [dateFormat=Ext.util.Format.defaultDateFormat] The format to be used when displaying the date in this field.
         * Accepts any valid date format. You can view formats over in the {@link Ext.Date} documentation.
         */
        dateFormat: 'h:i A',
        /**
         * @cfg {String} default time
         * The default time to be used when initilizing the field
         * Example: '8:00', '14:50'
         */
        defaultTime: '8:00'
    },
    applyValue: function( value ) {
        var date = new Date();
        // if we have no value whatsoever, set a default
        if ( !Ext.isDate( value ) && !Ext.isObject( value ) ) {
            var defaultTime = this.getDefaultTime().split( ':' );
        	if( value != null && value.indexOf(':') > 0) {
        		defaultTime = value.split( ':' );
        	}
            return new Date( date.getYear(), date.getMonth(), date.getDate(), defaultTime[ 0 ], defaultTime[ 1 ] );
        }
        // if the value is an object, create a new date with time values based on object
        if ( Ext.isObject( value ) ) {
            return new Date( date.getYear(), date.getMonth(), date.getDate(), value.hour, value.minute );
        }
        return value;
    },
    applyPicker: function( picker, pickerInstance ) {
        picker = Ext.factory( picker, 'Ext.picker.Time' );
        picker.setHidden( true );
        Ext.Viewport.add( picker );
        return picker;
    },
    /**
     * @cfg {String} [dateFormat=Ext.util.Format.defaultDateFormat] The format to be used when displaying the time in this field.
     * Accepts any valid date/time format. You can view formats over in the {@link Ext.Date} documentation.
     */
    getValue: function() {
        if ( this._picker && this._picker instanceof Ext.picker.Time ) {
            return this._picker.getValue();
        }
        return this._value;
    },
    getPicker: function() {
        var picker = this._picker,
            value = this.getValue();

        if ( picker && !picker.isPicker ) {
            picker = Ext.factory( picker, Ext.picker.Time );
            if ( value != null ) {
                picker.setValue( value );
            }
        }
        // add listeners
        picker.on({
            scope: this,
            change: 'onPickerChange',
            hide  : 'onPickerHide'
        });
        this._picker = picker;
        return picker;
    }
});


text:
MovableUpAttribute = function(obj) {
  this.perceive(obj);
}
MovableUpAttribute.prototype.key = 'can_move_up';
MovableUpAttribute.prototype.targetType = 'obj';
MovableUpAttribute.prototype.arity = 1;
MovableUpAttribute.prototype.constant = false;

/// Returns an MovableUpAttribute instance, which is the perception of whether the passed
/// object can be moved up. Possible values are 1 or 0.
MovableUpAttribute.prototype.perceive = function(obj) {
  this.obj = obj;
  this.val = this.checkMovability('up', obj.phys_obj, obj.object_node.scene_node.oracle);
}

MovableUpAttribute.prototype.get_activity = function() {
  return this.val ? 1 : 0;
}

MovableUpAttribute.prototype.get_label = function() {
	return 'can-move-up';
}

/// Returns true if the object can be moved towards the passed direction, one of
/// 'up', 'left' or 'right'. This is the case if pulling the object with a small force
/// for 4 seconds into the respective direction will result in the object beeing at
/// the respective edge of the frame or having moved substantially far in the direction.
/// For now only works for 'up'.
MovableUpAttribute.prototype.checkMovability = function(dir, body, oracle) {
	if (oracle.isStatic(body)) return false;

  var f = new Box2D.Common.Math.b2Vec2(0, -body.GetMass()*12);
  //if (dir == 'up') f = new b2Vec2(0, -body.GetMass()*12);
  //else if (dir == 'left') f = new b2Vec2(-body.GetMass()*2, 0);
  //else if (dir == 'right') f = new b2Vec2(body.GetMass()*2, 0);
  //else throw "unknown direction '" + dir + "'";

  // apply force to the body (will be cleared on reset after analyzeFuture automatically)
  var pull = function() {
    body.SetSleepingAllowed(false);
    body.ApplyForce(f, body.GetWorldCenter());
  }

  return oracle.analyzeFuture(2.5, pull, function() {
    // check whether object is close to top of frame
    var res = oracle.getTouchedBodiesWithPos(body);
    return res.some(function (e) {
      if (e.body.master_obj.id !== "|") return false;
      for (var i=0; i<e.pts.length; i++) {
        if (e.pts[i].y < 0.1) return true;
      }
    });
  });
}


text:
ME_NAME='01-import-clientcal-db.sh'

# mysql console command
MYSQL_CMD=${mysql[@]}
[ -n "$MYSQL_CMD" ] || MYSQL_CMD=mysql

# path to schema-sql dir
[ -n "$SCHEMASQL_DIR" ] || SCHEMASQL_DIR=/var/lib/schema-sql

# clientcal database name
[ -n "$CLIENTCAL_DATABASE" ] || CLIENTCAL_DATABASE='clientcal'

# path to db-schema.json
DB_SCHEMA_PATH=$SCHEMASQL_DIR/db-schema.json

# enforce sanity of mysql console command
echo 'SELECT version() as version;' | $MYSQL_CMD > /dev/null || {
   >&2 echo "$ME_NAME: mysql command '$MYSQL_CMD' failed with exit status $?"
   exit 1
}

# enforce sanity of jq command
hash jq || {
   >&2 echo "$ME_NAME: 'jq' command is missing or inaccessible"
   exit 1
}

# enforce sanity of db-schema.json file
[ -f "$DB_SCHEMA_PATH" ] || {
   >&2 echo "$ME_NAME: db-schema.json file '$DB_SCHEMA_PATH' not found"
   exit 1
}

# get 'latestDump' value from /var/lib/schema-sql/db-schema.json
LATEST_DUMP=$(dirname $DB_SCHEMA_PATH)/$(jq -e -r ".latestDump" $DB_SCHEMA_PATH) || {
   CMD_STATUS=$?
   if [ "$CMD_STATUS" = "1" ]; then
      >&2 echo "$ME_NAME: invalid db-schema.json file '$DB_SCHEMA_PATH', missing 'latestDump' value"
   else
      >&2 echo "$ME_NAME: failed to get the latest SQL dump file; 'jq' failed with exit status $?"
   fi
   exit 1
}

# enforce sanity of latest SQL dump file
[ -f "$LATEST_DUMP" ] || {
   >&2 echo "$ME_NAME: latest SQL dump file '$LATEST_DUMP' not found"
   exit 1
}

# import latest SQL dump file with mysql console
$MYSQL_CMD $CLIENTCAL_DATABASE < $LATEST_DUMP || {
   >&2 echo "$ME_NAME: failed to import LATEST_DUMP '$LATEST_DUMP', 'mysql' failed with exit status $?"
   exit 1
}
echo "($ME_NAME) imported latest SQL dump file: $LATEST_DUMP"


text:
<?php

namespace MichaelDzjap\TwoFactorAuth;

use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Model;

class TwoFactorAuth extends Model
{
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'id', 'user_id'
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'id'
    ];

    /**
     * The primary key of the table.
     *
     * @var string
     */
    protected $primaryKey = 'user_id';

    /**
     * Get the user that owns the two-factor auth.
     *
     * @param \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function user() : BelongsTo
    {
        return $this->belongsTo(\App\User::class);
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>

<com.slidinglayersample.NotifyingScrollView
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/scroll_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

        <include
                android:id="@+id/image_header"
                layout="@layout/project_profile_title"
                />

        <View
                android:layout_width="match_parent"
                android:layout_height="50dp"
                android:background="@drawable/gradient"/>

      <!--  <ListView
                android:id="@+id/task_list_view"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                >

        </ListView>-->

        <include
                layout="@layout/task_simple_item"/>
        <include
                layout="@layout/task_simple_item"/>
        <include
                layout="@layout/task_simple_item"/>
        <include
                layout="@layout/task_simple_item"/>
        <include
                layout="@layout/task_simple_item"/>
        <include
                layout="@layout/task_simple_item"/>
        <include
                layout="@layout/task_simple_item"/>
        <include
                layout="@layout/task_simple_item"/>
        <include
                layout="@layout/task_simple_item"/>
        <include
                layout="@layout/task_simple_item"/>
        <include
                layout="@layout/task_simple_item"/>
        <include
                layout="@layout/task_simple_item"/>

    </LinearLayout>
</com.slidinglayersample.NotifyingScrollView>


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
null

#### Original name
Tresanthera thyrsiflora Steyerm.

### Remarks
null


text:
package company.kr.sand.views;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.TextView;

import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.NetworkImageView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;

import company.kr.sand.R;
import company.kr.sand.adapter.PicListAdapter;
import company.kr.sand.controller.AppController;
import company.kr.sand.data.FeedItem;

/**
 * A placeholder fragment containing a simple view.
 */
public class ProfileFragment extends Fragment {

    NetworkImageView img_profile;
    TextView tv_nick,tv_board, tv_follow, tv_follower;
    Button btn_modify;
    GridView grid_myfeed;
    View view;
    private ArrayList<FeedItem> feedItems;
    private PicListAdapter listAdapter;
    String url_profile;
    ImageLoader imageLoader = AppController.getInstance().getImageLoader();
    String nick;

    public ProfileFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        view=inflater.inflate(R.layout.profile_fragment, container, false);
        setView();
        interactionWithWebServer();

        return view;
    }

    private void parseJsonFeed(JSONArray response) {
        try {
            JSONArray feedArray = response;

            for (int i = 0; i < feedArray.length(); i++) {
                JSONObject feedObj = (JSONObject) feedArray.get(i);

                FeedItem item = new FeedItem();
                item.setId(feedObj.getInt("_idx"));
                item.setName(nick);

                // Image might be null sometimes
                String image = feedObj.isNull("b_imagepath") ? null : "http://prattler.azurewebsites.net" + (feedObj
                        .getString("b_imagepath")).substring(1);
                //Log.d("asdf", image);

                if(image == null)
                    continue;
                item.setImge(image);
                item.setStatus(feedObj.getString("body"));
                item.setProfilePic(url_profile);
                item.setTimeStamp(feedObj.getString("dtime"));
                item.setTaste(feedObj.getString("taste"));
                item.setQuantity(feedObj.getString("quantity"));
                item.setPerformance(feedObj.getString("performance"));

                // url might be null sometimes
                String feedUrl = feedObj.isNull("idx") ? null : feedObj
                        .getString("idx");

                feedItems.add(item);

            }

            // notify data changes to list adapater
            listAdapter.notifyDataSetChanged();
        } catch (JSONException e) {
            e.printStackTrace();
        }catch (Exception e){

            e.printStackTrace();
        }
    }

    private void setView(){

        feedItems=new ArrayList<FeedItem>();
        listAdapter=new PicListAdapter(getActivity(),feedItems);

        img_profile=(NetworkImageView)view.findViewById(R.id.img_profile);
        tv_nick=(TextView)view.findViewById(R.id.tv_nick);
        tv_board=(TextView)view.findViewById(R.id.tv_board);
        btn_modify=(Button)view.findViewById(R.id.btn_modify);
        tv_follow=(TextView)view.findViewById(R.id.tv_follow);
        tv_follower=(TextView)view.findViewById(R.id.tv_follower);
        grid_myfeed=(GridView)view.findViewById(R.id.grid_myfeed);
        grid_myfeed.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent i = new Intent(getActivity(), GridImageActivity.class);
                i.putExtra("position", position);
                i.putExtra("imagelist", feedItems);
                startActivity(i);
            }
        });
        grid_myfeed.setAdapter(listAdapter);
    }

    private void interactionWithWebServer() {

        AsyncTask<Void, Void, String> async_interact = new AsyncTask<Void, Void, String>() {

            @Override
            protected void onPreExecute() {
            }

            @Override
            protected String doInBackground(Void... params) {

                String url = null;
                URL urlCon = null;
                String response = null;

                try {

                    url = "http://prattler.azurewebsites.net/profile.php";
                    urlCon = new URL(url);
                    HttpURLConnection httpURLConnection = (HttpURLConnection) urlCon.openConnection();

                    if (httpURLConnection != null) {

                        httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                        httpURLConnection.setRequestMethod("POST");
                        httpURLConnection.setDoOutput(true);
                        httpURLConnection.setDoInput(true);
                        httpURLConnection.setUseCaches(false);
                        httpURLConnection.setDefaultUseCaches(false);

                        OutputStream os = httpURLConnection.getOutputStream();
                        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os, "utf-8"));

                        SharedPreferences mPref=getActivity().getSharedPreferences("ID", Context.MODE_PRIVATE);

                        bw.write("id=" + mPref.getString("remain",null));
                        bw.flush();

                        InputStream is = httpURLConnection.getInputStream();
                        BufferedReader br = new BufferedReader(new InputStreamReader(is, "utf-8"));

                        response = br.readLine();

                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }

                return response;
            }

            @Override
            protected void onPostExecute(String res) {
                System.out.println(res);
                profileSetting(res);
            }
        };
        async_interact.execute();
    }

    private void profileSetting(String res){

        try {
            JSONObject json_profile=new JSONObject(res);
            JSONArray json_info=json_profile.getJSONArray("profileinfo");
            JSONArray json_imgs=json_profile.getJSONArray("boardcontents");

            url_profile=json_info.getString(0);
            nick=json_info.getString(1);
            img_profile.setImageUrl(url_profile,imageLoader);

            // img_profile.setImageUrl(json_info.getString(0),imageLoader);
            //img_profile.setVisibility(View.VISIBLE);
            tv_nick.setText(nick);
            tv_board.setText(json_info.getString(2));
            tv_follow.setText(json_info.getString(3));
            tv_follower.setText(json_info.getString(4));

            parseJsonFeed(json_imgs);

        } catch (JSONException e) {
            e.printStackTrace();
        }

    }
}


text:
var chai = require('chai'),
    expect = chai.expect,
    sql = require('../lib/tsql');

describe('update', function() {
  it('should generate the correct sql statement', function() {
    expect(sql.update('users', { firstName: 'Sally' }).where('firstName = @1', 'Johnny').toQuery())
      .to.deep.equal({text: 'update users set firstName = @1 where firstName = @2', values: ['Sally', 'Johnny']});
  });

  it('should handle multiple columns', function() {
    expect(sql.update('users', { salary: 'billions', house: 'private island' }).where('job = @1', 'CEO').toQuery())
      .to.deep.equal({ text: 'update users set salary = @1, house = @2 where job = @3', values: ['billions', 'private island', 'CEO'] })
  });

  it('should handle output statement', function() {
    expect(sql.update('users', { firstName: 'Sally' }).output().where('firstName = @1', 'Johnny').toQuery())
      .to.deep.equal({text: 'update users set firstName = @1 output inserted.* where firstName = @2', values: ['Sally', 'Johnny']});
  });
});


text:
#ifndef __LM__
#define __LM__

#include "../common/includes.h"
#include "../Encryptions/DES.h"
#include "HashAlg.h"

class LM : public HashAlg{
    private:
        std::string data;

    public:
        LM(const std::string & key = "");
        void run(std::string key);
        std::string hexdigest();
        std::size_t digestsize() const;
};

#endif


text:
package org.diorite;

import org.diorite.utils.SimpleEnum;
import org.diorite.utils.SimpleEnum.ASimpleEnum;

import gnu.trove.map.TIntObjectMap;

@SuppressWarnings("ClassHasNoToStringMethod")
public class GameMode extends ASimpleEnum<GameMode>
{
    static
    {
        init(GameMode.class, 4);
    }

    public static final GameMode SURVIVAL  = new GameMode("SURVIVAL", "survival");
    public static final GameMode CREATIVE  = new GameMode("CREATIVE", "creative");
    public static final GameMode ADVENTURE = new GameMode("ADVENTURE", "adventure");
    public static final GameMode SPECTATOR = new GameMode("SPECTATOR", "spectator");

    private final String name;

    public GameMode(final String enumName, final int enumId, final String name)
    {
        super(enumName, enumId);
        this.name = name;
    }

    public GameMode(final String enumName, final String name)
    {
        super(enumName);
        this.name = name;
    }

    public String getName()
    {
        return this.name;
    }

    /**
     * Register new {@link GameMode} entry in this enum.
     *
     * @param element new element to register.
     */
    public static void register(final GameMode element)
    {
        ASimpleEnum.register(GameMode.class, element);
    }

    /**
     * Get one of {@link GameMode} entry by its ordinal id.
     *
     * @param ordinal ordinal id of entry.
     *
     * @return one of entry or null.
     */
    public static GameMode getByEnumOrdinal(final int ordinal)
    {
        return getByEnumOrdinal(GameMode.class, ordinal);
    }

    /**
     * Get one of GameMode entry by its name.
     *
     * @param name name of entry.
     *
     * @return one of entry or null.
     */
    public static GameMode getByEnumName(final String name)
    {
        return getByEnumName(GameMode.class, name);
    }

    /**
     * @return all values in array.
     */
    public static GameMode[] values()
    {
        final TIntObjectMap<SimpleEnum<?>> map = getByEnumOrdinal(GameMode.class);
        return (GameMode[]) map.values(new GameMode[map.size()]);
    }

    static
    {
        GameMode.register(SURVIVAL);
        GameMode.register(CREATIVE);
        GameMode.register(ADVENTURE);
        GameMode.register(SPECTATOR);
    }
}


text:
<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

class Printer_Model extends Model {

    function __construct() {
        parent::__construct();
    }

    public function ajax_printerShow() {
        $tableName = $_POST['tableName'];
        $statement = $this->database->prepare("SHOW COLUMNS FROM $tableName");
        $statement->setFetchMode(PDO::FETCH_ASSOC);
        $statement->execute();
        $labourtables = $statement->fetchAll();
        $newarr=array();
        foreach ($labourtables as $val) {
            array_push($newarr,$val['Field']);
        }
        $newarr1=array();

        foreach ($newarr as $value) {
            $statement = $this->database->prepare("SELECT $value FROM $tableName");
            $statement->setFetchMode(PDO::FETCH_ASSOC);
            $statement->execute();
            $entries = $statement->fetchAll();

            array_push($newarr1,$value,$entries);
        }
        echo json_encode($newarr1);
    }

    public function ajax_printerAdd() {
        $tableName = $_POST['tableName'];
        $insertString = "INSERT INTO ".$tableName." (";
        foreach ($_POST as $key => $value) {
            if ($key != "tableName") {
                $insertString.="".$key.",";
            }
        }
        $insertString = rtrim($insertString, ",");
        $insertString.=") VALUES (";
        foreach ($_POST as $key => $value) {
            if ($key != "tableName") {
                $insertString.="'".$value."',";
            }
        }
        $insertString = rtrim($insertString, ",");
        $insertString.=");";
        $statement = $this->database->prepare($insertString);
        $statement->execute();
        echo "true";
    }

    public function ajax_printerDelete() {
        $id = $_POST['id'];
        $tableName = $_POST['tableName'];
        $insertString = "DELETE FROM mspCostModel.".$tableName." WHERE (id) ='".$id."';";
        $statement = $this->database->prepare($insertString);
        $statement->execute();
        echo $insertString;
    }

    public function ajax_printerModify() {
        $tableName=$_POST['tableName'];
        $insertString = "UPDATE ".$tableName." SET ";
        foreach ($_POST as $key => $value) {
            if ($key != "lastupdatedby" && $key != "currentupdater" && $key != "id" && $key != "lastupdated" && $key != "tableName") {
                $insertString .= $key."='".$value."',";
            }
        }
        $insertString .= "lastupdatedby='".$_POST['lastupdatedby']."' WHERE (id) ='".$_POST['id']."';";
        $statement = $this->database->prepare($insertString);
        $statement->execute();
        echo "Complete";
    }

    public function ajax_checkForDuplicate() {
        $tableName = $_GET['tableName'];
        $entry = $_GET['entry'];
        $value = $_GET['value'];
        $location = $_GET['location'];
        $locationField = $tableName."_location";

        $statement = $this->database->prepare("SELECT id FROM ".$tableName." WHERE ".$entry."='$value' AND ".$locationField."='$location';");
        $statement->setFetchMode(PDO::FETCH_ASSOC);
        $statement->execute();
        $data = $statement->fetchAll();
        $id=$data[0]['id'];

        if ($id) {
            echo "true";
        } else {
            echo "false";
        }

    }

    public function ajax_getLocation() {
        $statement = $this->database->prepare("SELECT assets_location FROM dcassets;");
        $statement->setFetchMode(PDO::FETCH_ASSOC);
        $statement->execute();
        $data = $statement->fetchAll();
        $newarr1=array();
        foreach ($data as $key => $value) {
            foreach($value as $k => $v) {
                array_push($newarr1, $v);
            }
        }
        $statement = $this->database->prepare("SELECT office_name FROM offices;");
        $statement->setFetchMode(PDO::FETCH_ASSOC);
        $statement->execute();
        $data = $statement->fetchAll();
        foreach ($data as $key => $value) {
            foreach($value as $k => $v) {
                array_push($newarr1, $v);
            }
        }
        echo json_encode($newarr1);
    }

    public function ajax_getCurrency() {
        $statement = $this->database->prepare("SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS where table_name='fx';");
        $statement->setFetchMode(PDO::FETCH_ASSOC);
        $statement->execute();
        $data = $statement->fetchAll();
        $newarr1=array();
        foreach ($data as $key => $value) {
            foreach($value as $k => $v) {
                if ($v != "id" AND $v != "lastupdated" AND $v != "lastupdatedby") {
                   array_push($newarr1, $v);
                }
            }
        }
        echo json_encode($newarr1);
    }

    public function ajax_getAssignment() {
        $tableName = $_GET['tableName'];
        $statement = $this->database->prepare("SELECT assignment_type FROM assignments;");
        $statement->setFetchMode(PDO::FETCH_ASSOC);
        $statement->execute();
        $data = $statement->fetchAll();
        $newarr1=array();
        foreach ($data as $key => $value) {
            foreach($value as $k => $v) {
                array_push($newarr1, $v);
            }
        }
        echo json_encode($newarr1);
    }

}


text:
Begin by declaring your models something like
``` python
from django.db import models

from wagtail.wagtailadmin.edit_handlers import FieldPanel
from wagtail.wagtailcore.models import Page

from wagtailjobs.models import jobIndexMixin, Abstractjob
from wagtailjobs.decorators import jobindex
from wagtailjobs.utils.payments import get_client_key, do_payment

# The decorator registers this model as a job index
@jobindex
class jobIndex(jobIndexMixin, Page):
    # Add extra fields here, as in a normal Wagtail Page class, if required
    job_model = 'job'

class job(Abstractjob):
    # job is a normal Django model, *not* a Wagtail Page.
    # Add any fields required for your page.
    full_name = models.CharField(max_length=255)
    organization = models.CharField(max_length=255)
    phone_number = models.CharField(max_length=255)
    amount = models.DecimalField(
        max_digits=6,
        decimal_places=2,
        help_text='Without dollar sign($)')
    payment_received = models.BooleanField(default=False)

    panels = [
        FieldPanel('full_name', classname='full'),
        FieldPanel('organization'),
        FieldPanel('phone_number')
        FieldPanel('amount'),
        FieldPanel('payment_received'),
    ] + Abstractjob.panels

    def __unicode__(self):
        return self.full_name

    def serve(self, request):
        amount = self.amount
        email = self.email
        # Something like
        if self.payment_received:
            # Bail early and show a thank you for paying message
            return render(request, self.get_template(request), {
                'self': self,
            })
        job_id = self.id
        if request.method == 'POST':
            nonce = request.POST['payment_method_nonce']
            payment_result = do_payment(
                total,
                email,
                nonce,
                job_id)
            if payment_result.is_success:
                # Possibly send a receipt, or get braintree to automatically do it
                self.payment_received = True
                self.save()
                return render(request, self.get_template(request), {
                    'self': self,
                    'result': payment_result,
                })
            else:
                pass
        else:
            payment_result = None

        return render(request, self.get_template(request), {
            "BRAINTREE_CLIENT_KEY": get_client_key(),
            'self': self,
            'result': payment_result,
        })

    preview_modes = [
        ('form', 'Form'),
        ('landing', 'Landing page'),
    ]
```

#Defining settings
Define the following settings where your settings are located

Add `wagtail.contrib.wagtailroutablepage` to your installed apps and add these settings

``` python
ADMIN_EMAIL = '' # Email for admin to receive job notifactions for paid jobs etc
ADMIN_job_MESSAGE_TEMPLATE_PATH = ''`
PDF_TEMPLATE = '' # Template path for job pdf's relative to the templates folder
CLIENT_job_MESSAGE_TEMPLATE_PATH = '' # Path to job email sent out to clients
WAGTAIL_jobS_VALIDATION = ''
BRAINTREE_MERCHANT_ID = ''
BRAINTREE_PUBLIC_KEY = ''
BRAINTREE_PRIVATE_KEY = ''
BRAINTREE_CSE_KEY = ''
BRAINTREE_MODE = '' # Production/Sandbox
```

See [Template Rendering](https://wagtailjobs.readthedocs.org/en/latest/template-rendering/#required-templates) and [Custom validation and overriding](https://wagtailjobs.readthedocs.org/en/latest/advanced/#custom-validation-and-overriding) for more information.

There is future scope to have these settings included with [wagtailsettings](https://bitbucket.org/takeflight/wagtailsettings)