text:
require 'json'
require 'net/http'
require 'open-uri'
require 'uri'
require 'ostruct'

module DismalTony # :nodoc:
  # Umbrella module for all mixins for Directives
  module DirectiveHelpers
    # Basic template , adds the inheritence methods through metaprogramming so
    # that n-children inherit class methods and instance methods apropriately.
    module HelperTemplate
      # Special case, only includes the class methods here.
      def self.included(base)
        base.extend(ClassMethods)
      end

      # Contains the Class methods of the helper, which are added on inclusion
      module ClassMethods
        # Adds the inclusion method to the class this class is included on,
        # So that its n-children inherit class methods
        def included(base)
          base.send(:include, const_get(:InstanceMethods))
          base.extend const_get(:ClassMethods)
        end
      end
    end

    # Basic helpers that make the Directives function
    module CoreHelpers
      include HelperTemplate

      # Basic helpers that make the Directives function
      # Contains the Class methods of the helper, which are added on inclusion
      module ClassMethods
        # DSL function, sets the Directives +name+ to +param+
        def set_name(param)
          @name = param
        end

        # DSL function, sets the Directives +group+ to +param+
        def set_group(param)
          @group = param
        end

        # DSL function, adds a new entry to the +parameters+ hash keyed by +param+ and given a value of +initial+.
        def add_param(param, initial = nil)
          @default_params ||= {}
          @default_params[param.to_sym] = initial
        end

        # DSL function, takes each key-value pair in +inputpar+ and adds a new entry to
        # the +parameters+ hash keyed by +param+ and given a value of +initial+.
        def add_params(inputpar)
          inputpar.each do |ki, va|
            @default_params[ki] = va
          end
        end

        # Yields the +criteria+ array, and uses the +block+ to add its results to
        # +match_criteria+ afterwards, allowing you to add new MatchLogic objects using the DSL.
        def add_criteria
          crit = []
          yield crit
          @match_criteria ||= []
          @match_criteria += crit
        end

        # Returns an Errored directive, using +qry+ and +vi+ to construct the new Directive
        def error(qry, vi)
          me = new(qry, vi)
          me.query.complete(self, HandledResponse.error)
        end
      end

      # Basic helpers that make the Directives function
      # Contains the Instance methods of the helper, which are added on inclusion
      module InstanceMethods
      end
    end

    # Utility functions to help construct responses easier.
    module ConversationHelpers
      include HelperTemplate

      # Utility functions to help construct responses easier.
      # Contains the Class methods of the helper, which are added on inclusion
      module ClassMethods
        # Takes in Hash<Regexp, Array<String>> and adds them to the synonyms
        def add_synonyms # :yields: synonyms
          new_syns = {}
          yield new_syns
          synonyms.merge!(new_syns)
        end

        # The array of synonyms available for using #synonym_for
        def synonyms
          @synonyms ||= {
            /^awesome$/i => %w[great excellent cool awesome splendid],
            /^okay$/i => %w[okay great alright],
            /^hello$/i => %w[hello hi greetings],
            /^yes$/i => %w[yes affirmative definitely correct certainly],
            /^no$/i => %w[no negative incorrect false],
            /^update$/i => %w[update change modify revise alter edit adjust],
            /^updated$/i => %w[updated changed modified revised altered edited adjusted],
            /^add$/i => %w[add create],
            /^added$/i => %w[added created],
            /^what|how$/i => %w[how what]
          }
        end
      end

      # Utility functions to help construct responses easier.
      # Contains the Instance methods of the helper, which are added on inclusion
      module InstanceMethods
        # Given a string, scans through the synonym array for any potential synonyms.
        def synonym_for(word)
          resp = nil
          synonyms.each do |reg, syns|
            resp = word =~ reg ? syns.sample : nil
            return resp if resp
          end
          word
        end

        # Instance hook for the class method
        def synonyms
          @synonyms ||= self.class.synonyms
          @synonyms
        end
      end
    end

    # Assists with emoji selection
    module EmojiHelpers
      include HelperTemplate

      # Assists with emoji selection
      # Contains the Instance methods of the helper, which are added on inclusion
      module InstanceMethods
        # Chooses randomly from +moj+, or if no arguments are passed randomly from all emoji.
        def random_emoji(*moj)
          if moj.length.zero?
            DismalTony::EmojiDictionary.emoji_table.keys.sample
          else
            moj.sample
          end
        end

        # Returns randomly from a predefined set of positiveemoji
        def positive_emoji
          %w[100 checkbox star thumbsup rocket].sample
        end

        # Returns randomly from a predefined set of negative emoji
        def negative_emoji
          %w[cancel caution frown thumbsdown siren].sample
        end

        # Returns randomly from a predefined set of face emoji
        def random_face_emoji
          %w[cool goofy monocle sly smile think].sample
        end

        # Returns randomly from a predefined set of time emoji
        def time_emoji
          %w[clockface hourglass alarmclock stopwatch watch].sample
        end
      end
    end

    # Mixin for JSON-based web APIs.
    module JSONAPIHelpers
      include HelperTemplate

      # Mixin for JSON-based web APIs.
      # Contains the Class methods of the helper, which are added on inclusion
      module ClassMethods
        # Takes in a block +blk+ and calculates it later to ensure late ENV access
        def set_api_defaults(&blk)
          @api_defaults_proc = blk
        end

        # Retrieves the block from #set_api_defaults and calls it.
        def get_api_defaults
          res = {}
          @api_defaults_proc.call(res)
          res
        end

        # Gets the api_defaults
        def api_defaults
          @api_defaults ||= get_api_defaults
        end

        # Sets the api_defaults
        def api_defaults=(newval)
          @api_defaults = newval
        end

        # Gets the api_url
        def api_url
          @api_url
        end

        # Sets the api_url
        def api_url=(newval)
          @api_url = newval
        end

        # DSL method for setting the api_url
        def set_api_url(url)
          @api_url = url
        end
      end

      # Mixin for JSON-based web APIs.
      # Contains the Instance methods of the helper, which are added on inclusion
      module InstanceMethods
        # Instance hook for the api_url
        def api_url
          @api_url ||= self.class.api_url
          @api_url
        end

        # Sets the api_url
        def api_url=(new_value)
          @api_url = new_value
        end

        # Generates an API request from the provided data to this mixin.
        # Parses and returns the JSON body of a request, intelligently merging
        # given arguments in +input_args+ and the #api_defaults
        def api_request(input_args)
          addr = URI(api_url)
          parms = input_args.clone
          parms = api_defaults.merge(parms)
          addr.query = URI.encode_www_form(parms)
          JSON.parse(Net::HTTP.get(addr))
        end

        # Instance hook for api_defaults
        def api_defaults
          @api_defaults ||= self.class.api_defaults
          @api_defaults
        end

        # Sets api_defaults
        def api_defaults=(new_value)
          @api_defaults = new_value
        end
      end
    end

    # Provides simpler access to DataStore#directive_data, and streamlines
    # defining and creating structs to put in it.
    module DataStructHelpers
      include HelperTemplate

      # Provides simpler access to DataStore#directive_data, and streamlines
      # defining and creating structs to put in it.
      # Contains the Class methods of the helper, which are added on inclusion
      module ClassMethods
        # Takes in a block returning a Struct, where user schema is defined.
        def define_data_struct
          @data_struct_template = yield
        end

        # Gets data_struct_template
        def data_struct_template
          @data_struct_template
        end

        # Sets data_struct_template
        def data_struct_template=(newval)
          @data_struct_template = newval
        end
      end

      # Provides simpler access to DataStore#directive_data, and streamlines
      # defining and creating structs to put in it.
      # Contains the Instance methods of the helper, which are added on inclusion
      module InstanceMethods
        # Uses the Directive's name, and any passed values to dig into the directive data
        def get_stored_data(*ky)
          vi.data_store.read_data(name, *ky)
        end

        # In this Directive's storage, stores +ky+ with a value of +v+.
        # If a block is given, passes it to #data_struct and uses that as the value.
        def store_data(ky, v = nil, &block)
          if block_given?
            vi.data_store.store_data(directive: name, key: ky, value: data_struct(&block))
          else
            vi.data_store.store_data(directive: name, key: ky, value: v)
          end
        end

        # Takes in arguments to create a new struct. If no #data_struct_template is defined,
        # It creates an OpenStruct instead. Otherwise, correctly maps values to the struct.
        def data_struct # :yields: arguments
          ud_args = {}
          yield ud_args
          if data_struct_template.nil?
            OpenStruct.new(ud_args)
          else
            args_list = data_struct_template.members.map { |a| ud_args[a] }
            data_struct_template.new(*args_list)
          end
        end

        # Instance hook for the data struct template
        def data_struct_template
          @data_struct_template ||= self.class.data_struct_template
          @data_struct_template
        end

        # Sets the data struct template
        def data_struct_template=(newval)
          @data_struct_template = newval
        end
      end
    end

    # Provides a mechanism to return rich values from responses
    module DataRepresentationHelpers
      include HelperTemplate

      # Provides a mechanism to return rich values from responses
      # Contains the Class methods of the helper, which are added on inclusion
      module ClassMethods
        # Defines a default data representation
        def define_data_representation
          @data_representation = yield
        end

        # Gets data_representation
        def data_representation
          @data_representation
        end

        # Sets data_representation to +new_val+
        def data_representation=(new_val)
          @data_representation = new_val
        end
      end

      # Provides a mechanism to return rich values from responses
      # Contains the Instance methods of the helper, which are added on inclusion
      module InstanceMethods
        # Instance hook for data_representation
        def data_representation
          @data_representation ||= self.class.data_representation
          @data_representation ||= parameters
          @data_representation ||= OpenStruct.new
          @data_representation
        end

        # Sets data_representation to +new_val+
        def data_representation=(new_val)
          @data_representation = new_val
        end

        # DSL method, overwrites data representation
        def return_data(data)
          @data_representation = data
        end
      end
    end
  end
end


text:
function no_ss = nosamplesets(ds)

% NOSAMPLESETS number of samplesets in dataset(s).
% ------------------------
% no_ss = nosamplesets(ds)
% ------------------------
% Description: number of samplesets in the dataset(s).
% Input:       {ds} dataset instance(s).
% Output:      {no_grps} array of the same dimension as {ds}, holding the
%                   number of samplesets in each dataset instance.

% © Liran Carmel
% Classification: SET/GET functions
% Last revision date: 22-Sep-2004

% parse input
error(nargchk(1,1,nargin));

% substitute values
no_ss = zeros(size(ds));
for ii = 1:numel(ds)
    no_ss(ii) = ds(ii).no_samplesets;
end

redpajama_set_name: RedPajamaGithub


text:
require 'spec_helper'

module Omnibus
  describe Packager::DEB do
    let(:project) do
      Project.new.tap do |project|
        project.name('project')
        project.homepage('https://example.com')
        project.install_dir('/opt/project')
        project.build_version('1.2.3')
        project.build_iteration('2')
        project.maintainer('Chef Software')
      end
    end

    subject { described_class.new(project) }

    let(:project_root) { "#{tmp_path}/project/root" }
    let(:package_dir)  { "#{tmp_path}/package/dir" }
    let(:staging_dir)  { "#{tmp_path}/staging/dir" }

    before do
      Config.project_root(project_root)
      Config.package_dir(package_dir)

      allow(subject).to receive(:staging_dir).and_return(staging_dir)
      create_directory(staging_dir)
      create_directory("#{staging_dir}/DEBIAN")
    end

    describe '#vendor' do
      it 'is a DSL method' do
        expect(subject).to have_exposed_method(:vendor)
      end

      it 'has a default value' do
        expect(subject.vendor).to eq('Omnibus <omnibus@getchef.com>')
      end

      it 'must be a string' do
        expect { subject.vendor(Object.new) }.to raise_error(InvalidValue)
      end
    end

    describe '#license' do
      it 'is a DSL method' do
        expect(subject).to have_exposed_method(:license)
      end

      it 'has a default value' do
        expect(subject.license).to eq('unknown')
      end

      it 'must be a string' do
        expect { subject.license(Object.new) }.to raise_error(InvalidValue)
      end
    end

    describe '#priority' do
      it 'is a DSL method' do
        expect(subject).to have_exposed_method(:priority)
      end

      it 'has a default value' do
        expect(subject.priority).to eq('extra')
      end

      it 'must be a string' do
        expect { subject.priority(Object.new) }.to raise_error(InvalidValue)
      end
    end

    describe '#section' do
      it 'is a DSL method' do
        expect(subject).to have_exposed_method(:section)
      end

      it 'has a default value' do
        expect(subject.section).to eq('misc')
      end

      it 'must be a string' do
        expect { subject.section(Object.new) }.to raise_error(InvalidValue)
      end
    end

    describe '#id' do
      it 'is :deb' do
        expect(subject.id).to eq(:deb)
      end
    end

    describe '#package_name' do
      before do
        allow(subject).to receive(:safe_architecture).and_return('amd64')
      end

      it 'includes the name, version, and build iteration' do
        expect(subject.package_name).to eq('project_1.2.3-2_amd64.deb')
      end
    end

    describe '#debian_dir' do
      it 'is nested inside the staging_dir' do
        expect(subject.debian_dir).to eq("#{staging_dir}/DEBIAN")
      end
    end

    describe '#write_control_file' do
      it 'generates the file' do
        subject.write_control_file
        expect("#{staging_dir}/DEBIAN/control").to be_a_file
      end

      it 'has the correct content' do
        subject.write_control_file
        contents = File.read("#{staging_dir}/DEBIAN/control")

        expect(contents).to include("Package: project")
        expect(contents).to include("Version: 1.2.3")
        expect(contents).to include("License: unknown")
        expect(contents).to include("Vendor: Omnibus <omnibus@getchef.com>")
        expect(contents).to include("Architecture: amd64")
        expect(contents).to include("Maintainer: Chef Software")
        expect(contents).to include("Installed-Size: 0")
        expect(contents).to include("Section: misc")
        expect(contents).to include("Priority: extra")
        expect(contents).to include("Homepage: https://example.com")
        expect(contents).to include("Description: The full stack of project")
      end
    end

    describe '#write_conffiles_file' do
      before do
        project.config_file('/opt/project/file1')
        project.config_file('/opt/project/file2')
      end

      context 'when there are no files' do
        before { project.config_files.clear }

        it 'does not render the file' do
          subject.write_conffiles_file
          expect("#{staging_dir}/DEBIAN/conffiles").to_not be_a_file
        end
      end

      it 'generates the file' do
        subject.write_conffiles_file
        expect("#{staging_dir}/DEBIAN/conffiles").to be_a_file
      end

      it 'has the correct content' do
        subject.write_conffiles_file
        contents = File.read("#{staging_dir}/DEBIAN/conffiles")

        expect(contents).to include("/opt/project/file1")
        expect(contents).to include("/opt/project/file2")
      end
    end

    describe '#write_scripts' do
      before do
        create_file("#{project_root}/package-scripts/project/preinst") { "preinst" }
        create_file("#{project_root}/package-scripts/project/postinst") { "postinst" }
        create_file("#{project_root}/package-scripts/project/prerm") { "prerm" }
        create_file("#{project_root}/package-scripts/project/postrm") { "postrm" }
      end

      it 'copies the scripts into the DEBIAN dir' do
        subject.write_scripts

        expect("#{staging_dir}/DEBIAN/preinst").to be_a_file
        expect("#{staging_dir}/DEBIAN/postinst").to be_a_file
        expect("#{staging_dir}/DEBIAN/prerm").to be_a_file
        expect("#{staging_dir}/DEBIAN/postrm").to be_a_file
      end

      it 'logs a message' do
        output = capture_logging do
          subject.write_scripts
        end

        expect(output).to include("Adding script `preinst'")
        expect(output).to include("Adding script `postinst'")
        expect(output).to include("Adding script `prerm'")
        expect(output).to include("Adding script `postrm'")
      end
    end

    describe '#write_md5_sums' do
      before do
        create_file("#{staging_dir}/.filea") { ".filea" }
        create_file("#{staging_dir}/file1") { "file1" }
        create_file("#{staging_dir}/file2") { "file2" }
      end

      it 'generates the file' do
        subject.write_md5_sums
        expect("#{staging_dir}/DEBIAN/md5sums").to be_a_file
      end

      it 'has the correct content' do
        subject.write_md5_sums
        contents = File.read("#{staging_dir}/DEBIAN/md5sums")

         expect(contents).to include("9334770d184092f998009806af702c8c .filea")
         expect(contents).to include("826e8142e6baabe8af779f5f490cf5f5 file1")
         expect(contents).to include("1c1c96fd2cf8330db0bfa936ce82f3b9 file2")
      end
    end

    describe '#create_deb_file' do
      before do
        allow(subject).to receive(:shellout!)
        allow(Dir).to receive(:chdir) { |_, &b| b.call }
      end

      it 'logs a message' do
        output = capture_logging { subject.create_deb_file }
        expect(output).to include('Creating .deb file')
      end

      it 'executes the command using `fakeroot`' do
        expect(subject).to receive(:shellout!)
          .with(/\Afakeroot/)
        subject.create_deb_file
      end

      it 'uses the correct command' do
        expect(subject).to receive(:shellout!)
          .with(/dpkg-deb -z9 -Zgzip -D --build/)
        subject.create_deb_file
      end
    end

    describe '#package_size' do
      before do
        project.install_dir(staging_dir)

        create_file("#{staging_dir}/file1") { "1"*10_000 }
        create_file("#{staging_dir}/file2") { "2"*20_000 }
      end

      it 'stats all the files in the install_dir' do
        expect(subject.package_size).to eq(29)
      end
    end

    describe '#safe_base_package_name' do
      context 'when the project name is "safe"' do
        it 'returns the value without logging a message' do
          expect(subject.safe_base_package_name).to eq('project')
          expect(subject).to_not receive(:log)
        end
      end

      context 'when the project name has invalid characters' do
        before { project.name("Pro$ject123.for-realz_2") }

        it 'returns the value while logging a message' do
          output = capture_logging do
            expect(subject.safe_base_package_name).to eq('pro-ject123.for-realz-2')
          end

          expect(output).to include("The `name' compontent of Debian package names can only include")
        end
      end
    end

    describe '#safe_build_iteration' do
      it 'returns the build iteration' do
        expect(subject.safe_build_iteration).to eq(project.build_iteration)
      end
    end

    describe '#safe_version' do
      context 'when the project build_version is "safe"' do
        it 'returns the value without logging a message' do
          expect(subject.safe_version).to eq('1.2.3')
          expect(subject).to_not receive(:log)
        end
      end

      context 'when the project build_version has invalid characters' do
        before { project.build_version("1.2$alpha.~##__2") }

        it 'returns the value while logging a message' do
          output = capture_logging do
            expect(subject.safe_version).to eq('1.2-alpha.~-2')
          end

          expect(output).to include("The `version' compontent of Debian package names can only include")
        end
      end
    end

    describe '#safe_architecture' do
      context 'when 64-bit' do
        before do
          stub_ohai(platform: 'ubuntu', version: '12.04') do |data|
            data['kernel']['machine'] = 'x86_64'
          end
        end

        it 'returns amd64' do
          expect(subject.safe_architecture).to eq('amd64')
        end
      end

      context 'when not 64-bit' do
        before do
          stub_ohai(platform: 'ubuntu', version: '12.04') do |data|
            data['kernel']['machine'] = 'i386'
          end
        end

        it 'returns the value' do
          expect(subject.safe_architecture).to eq('i386')
        end
      end

      context 'when i686' do
        before do
          stub_ohai(platform: 'ubuntu', version: '12.04') do |data|
            data['kernel']['machine'] = 'i686'
          end
        end

        it 'returns i386' do
          expect(subject.safe_architecture).to eq('i386')
        end
      end

      context 'on Raspbian' do
        before do
          # There's no Raspbian in Fauxhai :(
          stub_ohai(platform: 'debian', version: '7.6') do |data|
            data['platform'] = 'raspbian'
            data['platform_version'] = '7.6'
            data['kernel']['machine'] = 'armv6l'
          end
        end

        it 'returns armhf' do
          expect(subject.safe_architecture).to eq('armhf')
        end
      end
    end
  end
end


text:
package edu.mines.jtk.dsp;

import junit.framework.TestCase;
import junit.framework.TestSuite;

import static edu.mines.jtk.util.ArrayMath.*;

/**
 * Tests {@link edu.mines.jtk.dsp.HilbertTransformFilter}.
 * @author Dave Hale, Colorado School of Mines
 * @version 2010.06.01
 */
public class HilbertTransformFilterTest extends TestCase {
  public static void main(String[] args) {
    TestSuite suite = new TestSuite(HilbertTransformFilterTest.class);
    junit.textui.TestRunner.run(suite);
  }

  public void testApply() {
    int[] nmax_test   = {NMAX_DEFAULT,100000,100000,100000,100000};
    float[] emax_test = {EMAX_DEFAULT,0.010f,0.010f,0.001f,0.001f};
    float[] fmin_test = {FMIN_DEFAULT,0.050f,0.025f,0.100f,0.010f};
    float[] fmax_test = {FMAX_DEFAULT,0.475f,0.450f,0.400f,0.490f};
    int ntest = emax_test.length;

    // Loop over tests.
    for (int itest=0; itest<ntest; ++itest) {

      // Construct transformer.
      int nmax = nmax_test[itest];
      float emax = emax_test[itest];
      float fmin = fmin_test[itest];
      float fmax = fmax_test[itest];
      HilbertTransformFilter htf =
        new HilbertTransformFilter(nmax,emax,fmin,fmax);
      int lhtf = htf.length();

      // Apply it to get impulse response.
      int nxy = lhtf;
      float[] x = new float[nxy];
      x[(lhtf-1)/2] = 1.0f;
      float[] y = new float[nxy];
      htf.apply(nxy,x,y);

      // Check amplitude spectrum.
      int nfft = FftReal.nfftSmall(16*nxy);
      FftReal fft = new FftReal(nfft);
      int mfft = nfft/2+1;
      float[] hfft = new float[2*mfft];
      for (int i=0; i<nxy; ++i) hfft[i] = y[i];
      fft.realToComplex(1,hfft,hfft);
      int jfmin = 1+(int)(fmin*nfft);
      int jfmax = (int)(fmax*nfft);
      float[] afft = abs(sub(cabs(hfft),1.0f));
      float error = max(copy(1+jfmax-jfmin,jfmin,afft));
      /*
      System.out.println(" emax="+emax +
                         " fmin="+fmin +
                         " fmax="+fmax +
                         " length="+lhtf +
                         " error="+error);
      */
      assertTrue("actual error less than maximum expected error",error<=emax);
    }
  }

  private static final int NMAX_DEFAULT = 100000; // default max length.
  private static final float EMAX_DEFAULT = 0.010f; // default max error.
  private static final float FMIN_DEFAULT = 0.025f; // default min frequency.
  private static final float FMAX_DEFAULT = 0.475f; // default max frequency.
}


text:
from __future__ import print_function

import sys
import time

import h5py
import numpy as np
import tensorflow as tf

from basenji import batcher
from basenji import params
from basenji import seqnn
from basenji import shared_flags

FLAGS = tf.app.flags.FLAGS

################################################################################
# main
################################################################################
def main(_):
  np.random.seed(FLAGS.seed)

  run(params_file=FLAGS.params,
      data_file=FLAGS.data,
      train_epochs=FLAGS.train_epochs,
      train_epoch_batches=FLAGS.train_epoch_batches,
      test_epoch_batches=FLAGS.test_epoch_batches)

def run(params_file, data_file, train_epochs, train_epoch_batches, test_epoch_batches):

  #######################################################
  # load data
  #######################################################
  data_open = h5py.File(data_file)

  train_seqs = data_open['train_in']
  train_targets = data_open['train_out']
  train_na = None
  if 'train_na' in data_open:
    train_na = data_open['train_na']

  valid_seqs = data_open['valid_in']
  valid_targets = data_open['valid_out']
  valid_na = None
  if 'valid_na' in data_open:
    valid_na = data_open['valid_na']

  #######################################################
  # model parameters and placeholders
  #######################################################
  job = params.read_job_params(params_file)

  job['seq_length'] = train_seqs.shape[1]
  job['seq_depth'] = train_seqs.shape[2]
  job['num_targets'] = train_targets.shape[2]
  job['target_pool'] = int(np.array(data_open.get('pool_width', 1)))

  augment_shifts = [int(shift) for shift in FLAGS.augment_shifts.split(',')]
  ensemble_shifts = [int(shift) for shift in FLAGS.ensemble_shifts.split(',')]

  t0 = time.time()
  model = seqnn.SeqNN()
  model.build_feed(job, augment_rc=FLAGS.augment_rc, augment_shifts=augment_shifts,
     ensemble_rc=FLAGS.ensemble_rc, ensemble_shifts=ensemble_shifts)

  print('Model building time %f' % (time.time() - t0))

  # adjust for fourier
  job['fourier'] = 'train_out_imag' in data_open
  if job['fourier']:
    train_targets_imag = data_open['train_out_imag']
    valid_targets_imag = data_open['valid_out_imag']

  #######################################################
  # prepare batcher
  #######################################################
  if job['fourier']:
    batcher_train = batcher.BatcherF(
        train_seqs,
        train_targets,
        train_targets_imag,
        train_na,
        model.hp.batch_size,
        model.hp.target_pool,
        shuffle=True)
    batcher_valid = batcher.BatcherF(valid_seqs, valid_targets,
                                     valid_targets_imag, valid_na,
                                     model.batch_size, model.target_pool)
  else:
    batcher_train = batcher.Batcher(
        train_seqs,
        train_targets,
        train_na,
        model.hp.batch_size,
        model.hp.target_pool,
        shuffle=True)
    batcher_valid = batcher.Batcher(valid_seqs, valid_targets, valid_na,
                                    model.hp.batch_size, model.hp.target_pool)
  print('Batcher initialized')

  #######################################################
  # train
  #######################################################

  # checkpoints
  saver = tf.train.Saver()

  config = tf.ConfigProto()
  if FLAGS.log_device_placement:
    config.log_device_placement = True
  with tf.Session(config=config) as sess:
    t0 = time.time()

    # set seed
    tf.set_random_seed(FLAGS.seed)

    if FLAGS.logdir:
      train_writer = tf.summary.FileWriter(FLAGS.logdir + '/train', sess.graph)
    else:
      train_writer = None

    if FLAGS.restart:
      # load variables into session
      saver.restore(sess, FLAGS.restart)
    else:
      # initialize variables
      print('Initializing...')
      sess.run(tf.global_variables_initializer())
      print('Initialization time %f' % (time.time() - t0))

    train_loss = None
    best_loss = None
    early_stop_i = 0

    epoch = 0
    while (train_epochs is None or epoch < train_epochs) and early_stop_i < FLAGS.early_stop:
      t0 = time.time()

      # train
      train_loss, steps = model.train_epoch_h5(sess, batcher_train,
                                               sum_writer=train_writer,
                                               epoch_batches=train_epoch_batches,
                                               no_steps=FLAGS.no_steps)

      # validate
      valid_acc = model.test_h5(sess, batcher_valid, test_batches=test_epoch_batches)
      valid_loss = valid_acc.loss
      valid_r2 = valid_acc.r2().mean()
      del valid_acc

      best_str = ''
      if best_loss is None or valid_loss < best_loss:
        best_loss = valid_loss
        best_str = ', best!'
        early_stop_i = 0
        saver.save(sess, '%s/model_best.tf' % FLAGS.logdir)
      else:
        early_stop_i += 1

      # measure time
      et = time.time() - t0
      if et < 600:
        time_str = '%3ds' % et
      elif et < 6000:
        time_str = '%3dm' % (et / 60)
      else:
        time_str = '%3.1fh' % (et / 3600)

      # print update
      print(
          'Epoch: %3d,  Steps: %7d,  Train loss: %7.5f,  Valid loss: %7.5f,  Valid R2: %7.5f,  Time: %s%s'
          % (epoch + 1, steps, train_loss, valid_loss, valid_r2, time_str, best_str))
      sys.stdout.flush()

      if FLAGS.check_all:
        saver.save(sess, '%s/model_check%d.tf' % (FLAGS.logdir, epoch))

      # update epoch
      epoch += 1

    if FLAGS.logdir:
      train_writer.close()

################################################################################
# __main__
################################################################################
if __name__ == '__main__':
  tf.app.run(main)


text:
<?php

namespace Loconox\EntityRoutingBundle\Tests\Generator;

use Loconox\EntityRoutingBundle\Entity\Slug;
use Loconox\EntityRoutingBundle\Generator\UrlGenerator;
use Loconox\EntityRoutingBundle\Slug\Service\SlugServiceInterface;
use Loconox\EntityRoutingBundle\Slug\SlugServiceManager;
use Symfony\Component\Routing\Exception\InvalidParameterException;
use Symfony\Component\Routing\Exception\MissingMandatoryParametersException;
use Symfony\Component\Routing\Exception\RouteNotFoundException;
use Symfony\Component\Routing\RequestContext;
use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\RouteCollection;
use Symfony\Component\Validator\ConstraintViolation;
use Symfony\Component\Validator\ConstraintViolationInterface;
use Symfony\Component\Validator\ConstraintViolationList;

class UrlGeneratorTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @param $name
     * @param $parameters
     * @param $routes
     * @param $expected
     *
     * @dataProvider routeProviders
     */
    public function testGenerate($name, $parameters, $routes, $slugData, $expected)
    {
        $routeCollection = new RouteCollection();
        $context         = $this->getMockBuilder(RequestContext::class)
                                ->getMock();
        $context->expects($this->any())
                ->method('getHost')
                ->willReturn(null);
        $context->expects($this->any())
                ->method('getParameters')
                ->willReturn([]);

        // Init slugs
        $slugServiceManager = $this->getMockBuilder(SlugServiceManager::class)
                                   ->getMock();

        $slugServices = [];
        foreach ($slugData as $type => $slugs) {
            // Slug service
            $slugService = $this->getMockBuilder(SlugServiceInterface::class)
                                ->getMock();

            $slugServices[] = [$type, $slugService];
            foreach ($slugs as $id => $slugValue) {
                $slug = new Slug();
                $slug->setType($type);
                $slug->setSlug($slugValue);
                $slugService->expects($this->any())
                            ->method('findSlug')
                            ->with($this->equalTo($id))
                            ->willReturn($slug);
                $slugService->expects($this->any())
                            ->method('validate')
                            ->with($this->equalTo($id))
                            ->willReturn(new RouteCollection());
            }
        }
        $slugServiceManager->expects($this->any())
                           ->method('get')
                           ->willReturnMap($slugServices);

        $generator = new UrlGenerator($routeCollection, $context, null, $slugServiceManager);

        // Init route collection
        foreach ($routes as $routeName => $route) {
            $routeCollection->add($routeName, $route);
        }

        $this->assertEquals($expected, $generator->generate($name, $parameters));
    }

    public function routeProviders()
    {
        return [
            [
                'foo',
                [],
                [
                    'foo' => new Route('/foo'),
                    'bar' => new Route('/bar'),
                ],
                [],
                '/foo',
            ],
            [
                'foo',
                ['baz' => 42],
                [
                    'foo' => new Route('/foo/{baz}'),
                    'bar' => new Route('/bar'),
                ],
                [],
                '/foo/42',
            ],
            [
                'foo',
                ['baz' => 42],
                [
                    'foo' => new Route('/foo/{baz}'),
                    'bar' => new Route('/bar'),
                ],
                [
                    'baz' => [
                        42 => 'toto',
                    ],
                    'bar' => [
                        1 => 'titi',
                    ],
                ],
                '/foo/toto',
            ],
            [
                'foo',
                ['baz' => 42, 'bar' => 1],
                [
                    'foo' => new Route('/{bar}/{baz}'),
                    'bar' => new Route('/{baz}/{bar}'),
                ],
                [
                    'baz' => [
                        42 => 'toto',
                    ],
                    'bar' => [
                        1 => 'titi',
                    ],
                ],
                '/titi/toto',
            ],
            [
                'foo',
                ['baz' => 42, 'bar' => 1],
                [
                    'foo' => new Route('/{bar}/{baz}'),
                    'bar' => new Route('/{baz}/{bar}'),
                ],
                [
                    'baz' => [
                        42 => 'toto',
                    ],
                    'bar' => [
                        1 => 'titi',
                    ],
                ],
                '/titi/toto',
            ],
        ];
    }

    public function testGenerateMissingParameters()
    {
        $type      = 'bar';
        $id        = 42;
        $slugValue = 'toto';
        $routeName = 'foo';
        $route     = new Route('/{bar}');

        $routeCollection = new RouteCollection();
        $context         = $this->getMockBuilder(RequestContext::class)
                                ->getMock();
        $context->expects($this->any())
                ->method('getHost')
                ->willReturn(null);
        $context->expects($this->any())
                ->method('getParameters')
                ->willReturn([]);

        // Init slugs
        $slugServiceManager = $this->getMockBuilder(SlugServiceManager::class)
                                   ->getMock();

        $slugService = $this->getMockBuilder(SlugServiceInterface::class)
                            ->getMock();
        $slug        = new Slug();
        $slug->setType($type);
        $slug->setSlug($slugValue);
        $slugService->expects($this->never())
                    ->method('findSlug');

        $slugServiceManager->expects($this->never())
                           ->method('get');

        $generator = new UrlGenerator($routeCollection, $context, null, $slugServiceManager);

        $routeCollection->add($routeName, $route);

        $this->expectException(MissingMandatoryParametersException::class);
        $generator->generate($routeName, []);
    }

    public function testGenerateRouteNotFound()
    {
        $type      = 'bar';
        $id        = 42;
        $slugValue = 'toto';
        $routeName = 'baz';
        $route     = new Route('/{bar}');

        $routeCollection = new RouteCollection();
        $context         = $this->getMockBuilder(RequestContext::class)
                                ->getMock();
        $context->expects($this->any())
                ->method('getHost')
                ->willReturn(null);
        $context->expects($this->any())
                ->method('getParameters')
                ->willReturn([]);

        // Init slugs
        $slugServiceManager = $this->getMockBuilder(SlugServiceManager::class)
                                   ->getMock();

        $slugService = $this->getMockBuilder(SlugServiceInterface::class)
                            ->getMock();
        $slug        = new Slug();
        $slug->setType($type);
        $slug->setSlug($slugValue);
        $slugService->expects($this->never())
                    ->method('findSlug');

        $slugServiceManager->expects($this->never())
                           ->method('get');

        $generator = new UrlGenerator($routeCollection, $context, null, $slugServiceManager);

        $routeCollection->add($routeName, $route);

        $this->expectException(RouteNotFoundException::class);
        $generator->generate('foo', []);
    }

    public function testGenerateWithObject()
    {
        $type      = 'bar';
        $entity    = new \stdClass();
        $slugValue = 'toto';
        $routeName = 'foo';
        $route     = new Route('/{bar}');

        $routeCollection = new RouteCollection();
        $context         = $this->getMockBuilder(RequestContext::class)
                                ->getMock();
        $context->expects($this->any())
                ->method('getHost')
                ->willReturn(null);
        $context->expects($this->any())
                ->method('getParameters')
                ->willReturn([]);

        // Init slugs
        $slugServiceManager = $this->getMockBuilder(SlugServiceManager::class)
                                   ->getMock();

        $slugService = $this->getMockBuilder(SlugServiceInterface::class)
                            ->getMock();
        $slug        = new Slug();
        $slug->setType($type);
        $slug->setSlug($slugValue);
        $slugService->expects($this->atLeastOnce())
                    ->method('findSlug')
                    ->with($this->equalTo($entity))
                    ->willReturn($slug);
        $slugService->expects($this->atLeastOnce())
                    ->method('validate')
                    ->with($this->equalTo($entity))
                    ->willReturn(new RouteCollection());

        $slugServiceManager->expects($this->any())
                           ->method('get')
                           ->with($this->equalTo($type))
                           ->willReturn($slugService);

        $generator = new UrlGenerator($routeCollection, $context, null, $slugServiceManager);

        $routeCollection->add($routeName, $route);

        $this->assertEquals('/'.$slugValue, $generator->generate($routeName, ['bar' => $entity]));
    }

    public function testGenerateWithWrongParameterType()
    {
        $type      = 'bar';
        $entity    = new \stdClass();
        $slugValue = 'toto';
        $routeName = 'foo';
        $route     = new Route('/{bar}');

        $routeCollection = new RouteCollection();
        $context         = $this->getMockBuilder(RequestContext::class)
                                ->getMock();
        $context->expects($this->any())
                ->method('getHost')
                ->willReturn(null);
        $context->expects($this->any())
                ->method('getParameters')
                ->willReturn([]);

        // Init slugs
        $slugServiceManager = $this->getMockBuilder(SlugServiceManager::class)
                                   ->getMock();

        $constraint = $this->getMockBuilder(ConstraintViolationInterface::class)
            ->getMock();
        $violationList = new ConstraintViolationList();
        $violationList->add($constraint);
        $slugService = $this->getMockBuilder(SlugServiceInterface::class)
                            ->getMock();
        $slug        = new Slug();
        $slug->setType($type);
        $slug->setSlug($slugValue);
        $slugService->expects($this->never())
                    ->method('findSlug');
        $slugService->expects($this->atLeastOnce())
                    ->method('validate')
                    ->with($this->equalTo($entity))
                    ->willReturn($violationList);

        $slugServiceManager->expects($this->any())
                           ->method('get')
                           ->with($this->equalTo($type))
                           ->willReturn($slugService);

        $generator = new UrlGenerator($routeCollection, $context, null, $slugServiceManager);

        $routeCollection->add($routeName, $route);

        $this->expectException(InvalidParameterException::class);
        $generator->generate($routeName, ['bar' => $entity]);
    }
}


text:
@interface PRAction : GrowlActionPlugin <GrowlDispatchNotificationProtocol, GrowlUpgradePluginPrefsProtocol>

@end


text:
package test.tld.customtags.classic;

import java.io.IOException;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;

public class ClassicWithBodyLoopTagHandler extends TagSupport {
	private static final long serialVersionUID = 7001753720984057928L;
	private int i = 1;
	public int doStartTag() throws JspException {
		i = 1; // we should reset the counter because the Container can reuse the instance of the custom tag
		try {
			pageContext.getOut().print("In ugly doStartTag().
About to print the body
");
		} catch(IOException e) {
			e.printStackTrace();
		}
		return EVAL_BODY_INCLUDE; // evaluate the body and go to the doAfterBody()
	}

	public int doAfterBody() {
		try {
			pageContext.getOut().print("In ugly doAfterBody() for the " + i + " time(s).
");
		} catch(IOException e) {
			e.printStackTrace();
		}
		if(i < 4) {
			i++;
			return EVAL_BODY_AGAIN; // evaluate the body again and go to doAfterBody() again
		}
		return SKIP_BODY; // skip the body to don't evaluate again and go to doEndTag()
	}

	public int doEndTag() throws JspException {
		try {
			pageContext.getOut().print("In ugly doEndTag().
");
		} catch(IOException e) {
			e.printStackTrace();
		}
		return EVAL_PAGE; // evaluate the rest of the page (SKIP_PAGE is exactly like throwing a SkipPageException)
	}
}


text:
const { fatal } = require('../helpers/logger')

module.exports = function (mode) {
  if (!['pwa', 'cordova', 'capacitor', 'electron', 'ssr', 'bex'].includes(mode)) {
    fatal(`Unknown mode specified: ${mode}`)
  }

  const QuasarMode = require(`./mode-${mode}`)
  return new QuasarMode()
}


text:
git checkout -B include_css
git rebase master
sass public/stylesheets/style.sass --update
git add -f public/stylesheets/style.css
git add -f public/stylesheets/style.css.map
git commit --amend -m "Add stylesheets"
git push -f heroku include_css:master
git checkout master
git branch -D include_css


text:
Ext.define('gov.va.hmp.team.PersonSelector', {
    extend: 'gov.va.hmp.ux.PopUpButton',
    requires: [
        'gov.va.hmp.team.PersonPicker'
    ],
    mixins: [
        'Ext.form.field.Field'
    ],
    alias: 'widget.personselector',
    ui: 'link',
    value: null,
    menu: {
        cls: 'hmp-popupbutton-menu',
        width: 300,
        height: 360,
        plain: true,
        allowOtherMenus: true,
        enableKeyNav: false,
        layout: 'fit',
        items: [{
            xtype: 'personpicker'
        }]
    },
    initComponent: function () {
        this.callParent(arguments);
        this.initField();
        this.addEvents(
            /**
             * @event select
             * Fires when at least one list item is selected.
             * @param {gov.va.hmp.ptselect.PatientSelector} combo This SearchableList
             * @param {Array} records The selected persons
             */
            'select'
        );
    },
    initEvents: function () {
        this.callParent(arguments);
        this.mon(this.menu.down('personpicker'), 'selectionchange', this.onSelectPerson, this);
    },
    onSelectPerson: function (picker, records) {
        if (records && records.length > 0) {
            this.setValue(records[0].getId());
            this.resetOriginalValue();

            this.hideMenu();
            if (this.ownerCt && this.ownerCt.editing) {
                this.ownerCt.completeEdit();
            }
        }
        this.fireEvent('select', this, records);
    },
    getValue: function () {
        return this.value;
    },
    getRawValue: function () {
        return this.value;
    },
    setValue: function (value) {
        var me = this,
            personpicker = this.menu.down('personpicker'),
            selectionModel = personpicker.getSelectionModel(),
            personStore = personpicker.getStore();
        me.value = value;
        me.checkChange();
        if (me.value) {
            var person = personStore.getById(me.value);
            if (person) {
                selectionModel.select(person, false, true);
            } else {
                selectionModel.deselectAll(true);
            }
        } else {
            selectionModel.deselectAll(true);
        }
        if (!this.hasVisibleMenu() && this.ownerCt && !this.ownerCt.editing) {
            this.showMenu();
            // TODO: scroll to selected item
        }
        return me;
    },
    // @protected
    onMenuHide: function () {
        this.callParent(arguments);
        if (this.isDirty()) {
            this.ownerCt.cancelEdit(false);
        }
    }
});


text:
/**
* Contains: DelayedEvent
*/
#ifndef DELAYED_EVENT_H
#define DELAYED_EVENT_H
#include "mud.h"
#include "event.h"

/**
* These are used to make events go off on a certain amount of time, rather than
* When the invoke method is called once per pulse.
*/
class DelayedEvent:public Event
{
    timeval _fireTime; //how much time before we fire?
    timeval _lastTime; //when was the last time this event was fired?
public:
    /**
    * constructs a DelayedEvent.
    *
    * @param sec [in] The number of seconds between each fire.
    * @param msec [in] The number of milliseconds between each fire.
    */
    DelayedEvent(int sec,int msec);
    DelayedEvent();
    ~DelayedEvent() = default;

    /**
    * Sets the delay for the event.
    *
    * @param [in] sec The number of seconds between each fire.
    * @param [in] msec The number of milliseconds between each fire.
    */
    void SetDelay(int sec,int msec);
    /**
        * Trigger all events in the callback list, passing args.
    *
    * @params [in] args EventArgs specific to this event.
    * @param [in] caller A pointer to the caller object (if any).
    */
    void Invoke(EventArgs *args,void* caller);
};
#endif


text:
'use strcit';

var BatMobil =  BatMobil || {};
 var mergeMeshes = function (meshName, arrayObj, scene) {
    var arrayPos = [];
    var arrayNormal = [];
    var arrayUv = [];
    var arrayUv2 = [];
    var arrayColor = [];
    var arrayMatricesIndices = [];
    var arrayMatricesWeights = [];
    var arrayIndice = [];
    var savedPosition = [];
    var savedNormal = [];
    var newMesh = new BABYLON.Mesh(meshName, scene);
    var UVKind = true;
    var UV2Kind = true;
    var ColorKind = true;
    var MatricesIndicesKind = true;
    var MatricesWeightsKind = true;

    for (var i = 0; i != arrayObj.length ; i++) {
        if (!arrayObj[i].isVerticesDataPresent([BABYLON.VertexBuffer.UVKind]))
            UVKind = false;
        if (!arrayObj[i].isVerticesDataPresent([BABYLON.VertexBuffer.UV2Kind]))
            UV2Kind = false;
        if (!arrayObj[i].isVerticesDataPresent([BABYLON.VertexBuffer.ColorKind]))
            ColorKind = false;
        if (!arrayObj[i].isVerticesDataPresent([BABYLON.VertexBuffer.MatricesIndicesKind]))
            MatricesIndicesKind = false;
        if (!arrayObj[i].isVerticesDataPresent([BABYLON.VertexBuffer.MatricesWeightsKind]))
            MatricesWeightsKind = false;
    }

    for (i = 0; i != arrayObj.length ; i++) {
        var ite = 0;
        var iter = 0;
        arrayPos[i] = arrayObj[i].getVerticesData(BABYLON.VertexBuffer.PositionKind);
        arrayNormal[i] = arrayObj[i].getVerticesData(BABYLON.VertexBuffer.NormalKind);
        if (UVKind)
            arrayUv = arrayUv.concat(arrayObj[i].getVerticesData(BABYLON.VertexBuffer.UVKind));
        if (UV2Kind)
            arrayUv2 = arrayUv2.concat(arrayObj[i].getVerticesData(BABYLON.VertexBuffer.UV2Kind));
        if (ColorKind)
            arrayColor = arrayColor.concat(arrayObj[i].getVerticesData(BABYLON.VertexBuffer.ColorKind));
        if (MatricesIndicesKind)
            arrayMatricesIndices = arrayMatricesIndices.concat(arrayObj[i].getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
        if (MatricesWeightsKind)
            arrayMatricesWeights = arrayMatricesWeights.concat(arrayObj[i].getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));

        var maxValue = savedPosition.length / 3;

        arrayObj[i].computeWorldMatrix(true);
        var worldMatrix = arrayObj[i].getWorldMatrix();

        for (var ite = 0 ; ite != arrayPos[i].length; ite += 3) {
            var vertex = new BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(arrayPos[i][ite], arrayPos[i][ite + 1], arrayPos[i][ite + 2]), worldMatrix);
            savedPosition.push(vertex.x);
            savedPosition.push(vertex.y);
            savedPosition.push(vertex.z);
        }

        for (var iter = 0 ; iter != arrayNormal[i].length; iter += 3) {
            var vertex = new BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(arrayNormal[i][iter], arrayNormal[i][iter + 1], arrayNormal[i][iter + 2]), worldMatrix);
            savedNormal.push(vertex.x);
            savedNormal.push(vertex.y);
            savedNormal.push(vertex.z);
        }

        var tmp = arrayObj[i].getIndices();
        for (it = 0 ; it != tmp.length; it++) {
            arrayIndice.push(tmp[it] + maxValue);
        }
        arrayIndice = arrayIndice.concat(tmp);

        arrayObj[i].dispose(false);
    }

    newMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, savedPosition, false);
    newMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, savedNormal, false);
    if (arrayUv.length > 0)
        newMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, arrayUv, false);
    if (arrayUv2.length > 0)
        newMesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, arrayUv, false);
    if (arrayColor.length > 0)
        newMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, arrayUv, false);
    if (arrayMatricesIndices.length > 0)
        newMesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, arrayUv, false);
    if (arrayMatricesWeights.length > 0)
        newMesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, arrayUv, false);

    newMesh.setIndices(arrayIndice);
    return newMesh;
    };
BatMobil.game = (function () {

    'use strict';
    var createScene, canvas, engine, scene, fpsBox;

    var Skybox = require('./skybox');
    var Camera = require('./camera');
    var Tree = require('./elements/tree');

    fpsBox = document.getElementById('fps');
    canvas = document.getElementById('renderCanvas');
    engine = new BABYLON.Engine(canvas, true);

    var treeCollection = [];
    createScene = function () {
        var scene, camera, light, tree, treeClone, ground, skybox, shadowGenerator;

        scene = new BABYLON.Scene(engine);
        scene.clearColor = new BABYLON.Color3(0, 0.2, 0.2);
        scene.gravity = new BABYLON.Vector3(0, -9.81, 0);
        scene.collisionsEnabled = true;
        scene.ambientColor = new BABYLON.Color3(.3, 1, .3);

        scene.fogMode = BABYLON.Scene.FOGMODE_EXP;
        scene.fogDensity = 0.05;
        scene.fogStart = 20.0;
        scene.fogEnd = 60.0;
        scene.fogColor = new BABYLON.Color3(0.1, 0.1, 0.1);

        camera = new Camera(scene, canvas);
        skybox = new Skybox(scene);

        light = new BABYLON.DirectionalLight("dir01", new BABYLON.Vector3(-1, -1, -2), scene);
        light.intensity = .21;
        light.position = new BABYLON.Vector3(-300,300,600);
        shadowGenerator = new BABYLON.ShadowGenerator(2048, light);

        tree = new Tree(scene);
        for(var i = 0; i < 70; i++) {
            treeClone = tree.clone('clonedTree'+i);
            treeClone.position = new BABYLON.Vector3(-50 + Math.random() * 100, 7.5, -50 + Math.random() * 100);
            shadowGenerator.getShadowMap().renderList.push(treeClone);
        }

        ground = BABYLON.Mesh.CreateGround("ground1", 100, 100, 1, scene);
        ground.checkCollisions = true;
        ground.receiveShadows = true;
        ground.material = new BABYLON.StandardMaterial("ground", scene);
        ground.material.diffuseTexture = new BABYLON.Texture("assets/images/floor.jpg", scene);
        ground.material.diffuseTexture.uScale = 60;
        ground.material.diffuseTexture.vScale = 60;

        return scene;
    };
    scene = createScene();

    engine.runRenderLoop(function () {
        //var cylinder = scene.getMeshByName('cylinder');
        // cylinder.rotation.y += 0.005;

        scene.render();
    });

    window.addEventListener("resize", function () {
        engine.resize();
    });
})();


text:
package com.yahoo.dtf.junit;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

import junit.framework.JUnit4TestAdapter;

import org.junit.Test;

import com.yahoo.dtf.exception.DTFException;
import com.yahoo.dtf.util.Counter;
import com.yahoo.dtf.util.streams.ThrottledOutputStream;

/**
 *
 * @author rlgomes
 */
public class ThrottledStreamSuite extends DTFJUnitTest {

    @Test(timeout=600000)
    public void bufferedRead() throws DTFException {
        byte[] data = new byte[10*1024];

        int dbps = 2*1024;
        ByteArrayInputStream bais = new ByteArrayInputStream(data);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ThrottledOutputStream tos = new ThrottledOutputStream(baos,dbps);
        try {
            Counter cnt = new Counter();
            cnt.start();
            byte[] buffer = new byte[1024];
	        int read = 0;
	        while ( (read = bais.read(buffer)) != -1) {
	            tos.write(buffer,0,read);
	        }
	        cnt.stop();
	        double duration = cnt.getDurationInSeconds();
	        double bps = data.length / duration;
	        double diff = (dbps > bps ? dbps-bps : bps-dbps);
	        int offby = (int) (100.0*(diff/dbps));
	        getLogger().info("bps: " + bps + " off by " + offby + "%");
        } catch (IOException e) {
            throw new DTFException("Error using ThrottledOutputStream.",e);
        }
    }

    public static junit.framework.Test suite() {
        return new JUnit4TestAdapter(ThrottledStreamSuite.class);
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/guide2"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    <ImageView
        android:id="@+id/iv_two"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scaleType="fitXY" />
</LinearLayout>


text:
@implementation UIImage (Material)

- (UIImage *)imageWithSaturation:(float)saturation andGamma:(float)gamma
{
    GPUImagePicture *source = [[GPUImagePicture alloc] initWithImage:self];
    GPUImageGammaFilter *gammaFilter = [[GPUImageGammaFilter alloc] init];
    gammaFilter.gamma = gamma;
    [gammaFilter useNextFrameForImageCapture];

    GPUImageSaturationFilter *saturationFilter = [[GPUImageSaturationFilter alloc] init];
    saturationFilter.saturation = saturation;
    [saturationFilter useNextFrameForImageCapture];
    [gammaFilter addTarget:saturationFilter];

    [source addTarget:gammaFilter];
    [source useNextFrameForImageCapture];
    [source processImage];

    return [saturationFilter imageFromCurrentFramebuffer];
}

@end


text:
<?php

/*# declare(strict_types=1); */

namespace Phossa\Di\Definition\Reference;

/**
 * ServiceReference
 *
 * @abstract
 * @package Phossa\Di
 * @author  Hong Zhang <phossa@126.com>
 * @see     ReferenceAbstract
 * @version 1.0.6
 * @since   1.0.1 added
 */
class ServiceReference extends ReferenceAbstract
{
}


text:
ACCEPTED

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

#### Published in
Mem. Amer. Acad. Arts ser. 2, 6:385. 1858-1859

#### Original name
null

### Remarks
null


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<meta name="copyright" content="(C) Copyright 2005" />
<meta name="DC.rights.owner" content="(C) Copyright 2005" />
<meta content="public" name="security" />
<meta content="index,follow" name="Robots" />
<meta http-equiv="PICS-Label" content='(PICS-1.1 "http://www.icra.org/ratingsv02.html" l gen true r (cz 1 lz 1 nz 1 oz 1 vz 1) "http://www.rsac.org/ratingsv01.html" l gen true r (n 0 s 0 v 0 l 0) "http://www.classify.org/safesurf/" l gen true r (SS~~000 1))' />
<meta content="reference" name="DC.Type" />
<meta name="DC.Title" content="MONTH" />
<meta content="Função MONTH" name="DC.subject" />
<meta content="Função MONTH" name="keywords" />
<meta scheme="URI" name="DC.Relation" content="rrefsqlj29026.html" />
<meta content="XHTML" name="DC.Format" />
<meta content="rrefmonthfunc" name="DC.Identifier" />
<meta content="pt-br" name="DC.Language" />
<link href="commonltr.css" type="text/css" rel="stylesheet" />
<title>MONTH</title>

MONTH

A função MONTH retorna a parte relativa ao mês do valor.
O argumento deve ser uma data, carimbo do tempo, ou a representação cadeia de
caracteres válida de uma data ou carimbo do tempo, que não seja CLOB nem
LONG VARCHAR.
O resultado da função é um inteiro.
Se o argumento puder ser nulo, o resultado poderá ser nulo;
se o argumento for nulo, o resultado será o valor nulo.

As outras regras dependem do tipo de dado do argumento especificado:

Se o argumento for uma data, carimbo do tempo, ou a representação
cadeia de caracteres válida de uma data ou carimbo do tempo:
O resultado será a parte relativa ao mês do valor, que é um inteiro entre
1 e 12.

Se o argumento for uma duração de data ou duração de carimbo do tempo:
O resultado será a parte relativa ao mês do valor, que é um inteiro entre
-99 e 99.
Um resultado diferente de zero possui o mesmo sinal do argumento.

Sintaxe

MONTH ( expressão )

Selecionar todas as linhas da tabela EMPREGADOS para as pessoas nascidas
(DATA_NASC) em dezembro.

SELECT * FROM EMPREGADOS
WHERE MONTH(DATA_NASC) = 12

Tópico pai: Funções nativas


text:
import os
from urllib.request import urlretrieve

from django.core.management.base import BaseCommand, CommandError

our_statics = {
    'jquery-2.1.1.min.js': "https://code.jquery.com/jquery-2.1.1.min.js",
    'underscore-min.js': (
        "https://cdnjs.cloudflare.com/ajax/libs/"
        "underscore.js/1.7.0/underscore-min.js"),
    os.path.join('css', "bootstrap.min.css"): (
        "https://netdna.bootstrapcdn.com/bootstrap/3.2.0/css/"
        "bootstrap.min.css"),
    os.path.join('fonts', "glyphicons-halflings-regular.woff"): (
        "https://netdna.bootstrapcdn.com/bootstrap/3.2.0/fonts/"
        "glyphicons-halflings-regular.woff"),
    os.path.join('fonts', "glyphicons-halflings-regular.ttf"): (
        "https://netdna.bootstrapcdn.com/bootstrap/3.2.0/fonts/"
        "glyphicons-halflings-regular.ttf"),
    'words': "http://www.cs.duke.edu/~ola/ap/linuxwords"
}

class Command(BaseCommand):

    def handle(self, *args, **options):
        for static, upstream in our_statics.items():
            destination = os.path.join('static', 'libs', static)
            if not os.path.exists(destination):
                self.stdout.write("downloading {} from {} ...".format(
                    destination, upstream))
                urlretrieve(upstream, destination)
            else:
                self.stdout.write("we already have {}".format(static))


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AbstractDevelop.machines.turing
{
    /// <summary>
    /// Кодирует направления движения читающей/пишущей головки мишины Тьюринга.
    /// </summary>
    public enum TuringPenDir : byte
    {
        /// <summary>
        /// Остаться на месте.
        /// </summary>
        Stay,
        /// <summary>
        /// Сдвиг вправо.
        /// </summary>
        Right,
        /// <summary>
        /// Сдвиг влево.
        /// </summary>
        Left
    }
}


text:
package com.ohmdb.api;

public enum SearchCriteriaKind {

	CRITERION, CONJUNCTION, DISJUNCTION;

}


text:
package zyf.inspur.com.coolweather.util;

import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.util.Log;

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

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import zyf.inspur.com.coolweather.db.CoolWeatherDB;
import zyf.inspur.com.coolweather.model.City;
import zyf.inspur.com.coolweather.model.County;
import zyf.inspur.com.coolweather.model.Province;

public class Utility {
    /**
     * Mehtod: handleProvincesResponse

     * Description: 解析和处理服务器返回的省级数据

     * Creator: zyf

     * Date: 2016/8/29 10:24
     */
    public synchronized static boolean handleProvincesResponse(
            CoolWeatherDB coolWeatherDB, String response) {
        LogUtil.log(LogUtil.TAG,"Utility handleProvincesResponse and response is "+response);
        if (!TextUtils.isEmpty(response)) {
            String[] allProvinces = response.split(",");
            if (allProvinces != null && allProvinces.length > 0) {
                for (String p : allProvinces) {
                    String[] array = p.split("\\|");
                    Province province = new Province();
                    province.setProvinceCode(array[0]);
                    province.setProvinceName(array[1]);
                    // 将解析出来的数据存储到Province表
                    coolWeatherDB.saveProvince(province);
                }
                return true;
            }
        }
        return false;
    }

    /**
     * Mehtod: handleCitiesResponse

     * Description: 解析和处理服务器返回的市级数据

     * Creator: zyf

     * Date: 2016/8/29 10:26
     */
    public static boolean handleCitiesResponse(CoolWeatherDB coolWeatherDB,
                                               String response, int provinceId) {
        if (!TextUtils.isEmpty(response)) {
            String[] allCities = response.split(",");
            if (allCities != null && allCities.length > 0) {
                for (String c : allCities) {
                    String[] array = c.split("\\|");
                    City city = new City();
                    city.setCityCode(array[0]);
                    city.setCityName(array[1]);
                    city.setProvinceId(provinceId);
                    // 将解析出来的数据存储到City表
                    coolWeatherDB.saveCity(city);
                }
                return true;
            }
        }
        return false;
    }

    /**
     * Mehtod: handleCountiesResponse

     * Description: 解析和处理服务器返回的县级数据

     * Creator: zyf

     * Date: 2016/8/29 10:28
     */
    public static boolean handleCountiesResponse(CoolWeatherDB coolWeatherDB,
                                                 String response, int cityId) {
        if (!TextUtils.isEmpty(response)) {
            String[] allCounties = response.split(",");
            if (allCounties != null && allCounties.length > 0) {
                for (String c : allCounties) {
                    String[] array = c.split("\\|");
                    County county = new County();
                    county.setCountyCode(array[0]);
                    county.setCountyName(array[1]);
                    county.setCityId(cityId);
                    // 将解析出来的数据存储到County表
                    coolWeatherDB.saveCounty(county);
                }
                return true;
            }
        }
        return false;
    }

    /**
     * Mehtod: handleWeatherResponse

     * Description: 解析服务器返回的JSON数据,并将解析出的数据保存到本地

     * Creator: zyf

     * Date: 2016/8/29 10:29
     */
    public static void handleWeatherResponse(Context context, String response) {
        LogUtil.log(LogUtil.TAG,"Utility handleWeatherResponse() response is\n"+response);
        try {
            JSONObject jsonObject = new JSONObject(response);
            JSONObject weatherInfo = jsonObject.getJSONObject("weatherinfo");
            String cityName = weatherInfo.getString("city");
            String weatherCode = weatherInfo.getString("cityid");
            String temp1 = weatherInfo.getString("temp1");
            String temp2 = weatherInfo.getString("temp2");
            String weatherDesp = weatherInfo.getString("weather");
            String publishTime = weatherInfo.getString("ptime");
            saveWeatherInfo(context, cityName, weatherCode, temp1, temp2,
                    weatherDesp, publishTime);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /**
     * Mehtod: saveWeatherInfo

     * Description: 将服务器返回的所有天气信息存储到SharePreferences文件中

     * Creator: zyf

     * Date: 2016/8/29 10:31
     */
    public static void saveWeatherInfo(Context context, String cityName,
                                       String weatherCode, String temp1, String temp2, String weatherDesp,
                                       String publishTime) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年M月d日", Locale.CHINA);
        SharedPreferences.Editor editor = PreferenceManager
                .getDefaultSharedPreferences(context).edit();
        LogUtil.log(LogUtil.TAG,"Utility saveWeatherInfo() cityName="+cityName+"temp1="+temp1,LogUtil.DEBUG);
        editor.putBoolean("city_selected", true);
        editor.putString("city_name", cityName);
        editor.putString("weather_code", weatherCode);
        editor.putString("temp1", temp1);
        editor.putString("temp2", temp2);
        editor.putString("weather_desp", weatherDesp);
        editor.putString("publish_time", publishTime);
        editor.putString("current_date", sdf.format(new Date()));
        editor.commit();
    }

}


text:
log = function(s) { console.log(s)}

goToPath = function(path) {
  window.location.href = path;
}

nicePrompt = function(title,cb) {
  swal({
    title: title,
    html: '<p><input id="swal-prompt-input-field">',
  },
  function() {
    var val = $('#swal-prompt-input-field').val();
    if (val && cb) { cb(val); }
  });
}

$.fn.serializeObject = function()
{
    var o = {};
    var a = this.serializeArray();
    $.each(a, function() {
        if (o[this.name] !== undefined) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
};

window.gulp = function getUrlParameter(sParam) {
    var sPageURL = decodeURIComponent(window.location.search.substring(1)),
        sURLVariables = sPageURL.split('&'),
        sParameterName,
        i;

    for (i = 0; i < sURLVariables.length; i++) {
        sParameterName = sURLVariables[i].split('=');

        if (sParameterName[0] === sParam) {
            return sParameterName[1] === undefined ? true : sParameterName[1];
        }
    }
};


text:
package com.qf.tgp.plamtv;

import android.app.Application;

import org.xutils.x;

/**
 * Created by 朱雨桐 on 2016/9/19.
 */
public class TVApp extends Application {

    @Override
    public void onCreate() {
        super.onCreate();
        x.Ext.init(this);
        x.Ext.setDebug(true);
    }
}


text:
require 'uri'
require 'cgi'
require 'date'
require 'json'
require 'base64'
require 'erb'
require 'securerandom'
require 'time'
require 'timeliness'
require 'faraday'
require 'faraday-cookie_jar'
require 'concurrent'
require 'ms_rest'
require '2019-05-01/generated/azure_mgmt_netapp/module_definition'
require 'ms_rest_azure'

module Azure::NetApp::Mgmt::V2019_05_01
  autoload :Operations,                                         '2019-05-01/generated/azure_mgmt_netapp/operations.rb'
  autoload :Accounts,                                           '2019-05-01/generated/azure_mgmt_netapp/accounts.rb'
  autoload :Pools,                                              '2019-05-01/generated/azure_mgmt_netapp/pools.rb'
  autoload :Volumes,                                            '2019-05-01/generated/azure_mgmt_netapp/volumes.rb'
  autoload :MountTargets,                                       '2019-05-01/generated/azure_mgmt_netapp/mount_targets.rb'
  autoload :Snapshots,                                          '2019-05-01/generated/azure_mgmt_netapp/snapshots.rb'
  autoload :AzureNetAppFilesManagementClient,                   '2019-05-01/generated/azure_mgmt_netapp/azure_net_app_files_management_client.rb'

  module Models
    autoload :CapacityPoolList,                                   '2019-05-01/generated/azure_mgmt_netapp/models/capacity_pool_list.rb'
    autoload :OperationDisplay,                                   '2019-05-01/generated/azure_mgmt_netapp/models/operation_display.rb'
    autoload :CapacityPoolPatch,                                  '2019-05-01/generated/azure_mgmt_netapp/models/capacity_pool_patch.rb'
    autoload :MetricSpecification,                                '2019-05-01/generated/azure_mgmt_netapp/models/metric_specification.rb'
    autoload :ExportPolicyRule,                                   '2019-05-01/generated/azure_mgmt_netapp/models/export_policy_rule.rb'
    autoload :Operation,                                          '2019-05-01/generated/azure_mgmt_netapp/models/operation.rb'
    autoload :VolumePropertiesExportPolicy,                       '2019-05-01/generated/azure_mgmt_netapp/models/volume_properties_export_policy.rb'
    autoload :ResourceNameAvailability,                           '2019-05-01/generated/azure_mgmt_netapp/models/resource_name_availability.rb'
    autoload :Volume,                                             '2019-05-01/generated/azure_mgmt_netapp/models/volume.rb'
    autoload :ActiveDirectory,                                    '2019-05-01/generated/azure_mgmt_netapp/models/active_directory.rb'
    autoload :VolumeList,                                         '2019-05-01/generated/azure_mgmt_netapp/models/volume_list.rb'
    autoload :NetAppAccountList,                                  '2019-05-01/generated/azure_mgmt_netapp/models/net_app_account_list.rb'
    autoload :VolumePatchPropertiesExportPolicy,                  '2019-05-01/generated/azure_mgmt_netapp/models/volume_patch_properties_export_policy.rb'
    autoload :CapacityPool,                                       '2019-05-01/generated/azure_mgmt_netapp/models/capacity_pool.rb'
    autoload :VolumePatch,                                        '2019-05-01/generated/azure_mgmt_netapp/models/volume_patch.rb'
    autoload :ServiceSpecification,                               '2019-05-01/generated/azure_mgmt_netapp/models/service_specification.rb'
    autoload :MountTarget,                                        '2019-05-01/generated/azure_mgmt_netapp/models/mount_target.rb'
    autoload :ResourceNameAvailabilityRequest,                    '2019-05-01/generated/azure_mgmt_netapp/models/resource_name_availability_request.rb'
    autoload :MountTargetList,                                    '2019-05-01/generated/azure_mgmt_netapp/models/mount_target_list.rb'
    autoload :NetAppAccountPatch,                                 '2019-05-01/generated/azure_mgmt_netapp/models/net_app_account_patch.rb'
    autoload :Snapshot,                                           '2019-05-01/generated/azure_mgmt_netapp/models/snapshot.rb'
    autoload :OperationListResult,                                '2019-05-01/generated/azure_mgmt_netapp/models/operation_list_result.rb'
    autoload :SnapshotsList,                                      '2019-05-01/generated/azure_mgmt_netapp/models/snapshots_list.rb'
    autoload :Dimension,                                          '2019-05-01/generated/azure_mgmt_netapp/models/dimension.rb'
    autoload :SnapshotPatch,                                      '2019-05-01/generated/azure_mgmt_netapp/models/snapshot_patch.rb'
    autoload :NetAppAccount,                                      '2019-05-01/generated/azure_mgmt_netapp/models/net_app_account.rb'
    autoload :InAvailabilityReasonType,                           '2019-05-01/generated/azure_mgmt_netapp/models/in_availability_reason_type.rb'
    autoload :CheckNameResourceTypes,                             '2019-05-01/generated/azure_mgmt_netapp/models/check_name_resource_types.rb'
    autoload :ServiceLevel,                                       '2019-05-01/generated/azure_mgmt_netapp/models/service_level.rb'
  end
end


text:
require 'faker'

User.delete_all
Tag.delete_all

users = 10.times.map do
  User.create!( :username 		=> Faker::Name.name,
                :email      	=> Faker::Internet.email,
                :password   	=> 'password')
end

questions = 10.times.map do
	Question.create!(:title      => Faker::Lorem.sentence,
                  :body        => Faker::Lorem.paragraph,
                  :user_id		=> rand(1..10)  )

end

answers = 10.times.map do
	Answer.create!(:body					=> Faker::Hacker.say_something_smart,
								 :user_id				=> rand(1..10),
								 :question_id		=> rand(1..10)  )
end

tags = [%w(salty sweet savory umami yum gross bleh morning afternoon midnight diet gluten )].map do |tag|
		Tag.create!(:category 			=> tag)
	end


text:
<?php if(!defined('UC_ROOT')) exit('Access Denied');?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=<?php echo UC_CHARSET;?>" />
<title>UCenter Administrator's Control Panel</title>
<link rel="stylesheet" href="images/admincp.css" type="text/css" media="all" />
<meta content="Comsenz Inc." name="Copyright" />

<?php if(!empty($iframe) && !empty($user)) { ?>
	菜单

首页

		<?php if($user['allowadminsetting'] || $user['isfounder']) { ?>
基本设置
<?php } ?>
		<?php if($user['allowadminsetting'] || $user['isfounder']) { ?>
注册设置
<?php } ?>
		<?php if($user['allowadminsetting'] || $user['isfounder']) { ?>
邮件设置
<?php } ?>
		<?php if($user['allowadminapp'] || $user['isfounder']) { ?>
应用管理
<?php } ?>
		<?php if($user['allowadminuser'] || $user['isfounder']) { ?>
用户管理
<?php } ?>
		<?php if($user['isfounder']) { ?>
管理员
<?php } ?>
		<?php if($user['allowadminpm'] || $user['isfounder']) { ?>
短消息
<?php } ?>
		<?php if($user['allowadmincredits'] || $user['isfounder']) { ?>
积分兑换
<?php } ?>
		<?php if($user['allowadminbadword'] || $user['isfounder']) { ?>
词语过滤
<?php } ?>
		<?php if($user['allowadmindomain'] || $user['isfounder']) { ?>
域名解析
<?php } ?>
		<?php if($user['allowadmindb'] || $user['isfounder']) { ?>
数据备份
<?php } ?>
		<?php if($user['isfounder']) { ?>
数据列表
<?php } ?>
		<?php if($user['allowadmincache'] || $user['isfounder']) { ?>
更新缓存
<?php } ?>
		<?php if($user['isfounder']) { ?>
校验文件
<?php } ?>
		退出

<?php } ?>


text:
CoreOS-Vagrant Kubernetes Solo for OS X
============================
NEWS: This App is not maintained anymore and is replaced by [Kube-Solo for OS X](https://github.com/TheNewNormal/kube-solo-osx)

![k8s-solo](k8s-singlenode.png)

`CoreOS-Vagrant Kubernetes Solo GUI for Mac OS X` is a Mac Status bar App which works like a wrapper around [coreos-vagrant](https://github.com/coreos/coreos-vagrant) command line tool and bootstraps Kubernetes on one standalone  machine.

Fully supports etcd2 in all CoresOS channels.

[CoreOS](https://coreos.com) is a Linux distribution made specifically to run [Docker](https://www.docker.io/) containers.
[CoreOS-Vagrant](https://github.com/coreos/coreos-vagrant) is made to run on VirtualBox and VMWare VMs.

![CoreOS-Vagrant-Kubernetes-Solo](coreos-vagrant-k8s-solo-gui.png "CoreOS-Vagrant-Kubernetes-Solo-GUI")

Download
--------
Head over to the [Releases Page](https://github.com/rimusz/coreos-osx-gui-kubernetes-solo/releases) to grab the latest release.

How to install
----------

Required software:
* [VirtualBox](https://www.virtualbox.org/wiki/Downloads), [Vagrant](http://www.vagrantup.com/downloads.html) and [iTerm 2](http://www.iterm2.com/#/section/downloads)
* Open downloaded App dmg file and drag it e.g. to your Desktop.
* Start the `CoreOS k8s Solo` App and from menu `Setup` and choose: `Initial setup of CoreOS-Vagrant k8s Solo`

The install will do the following:

* All dependent files/folders will be put under `coreos-k8s-solo` folder in the user's home folder
* It will clone latest coreos-vagrant from git
* user-data files will have fleet, etcd and flannel set
* VM machine will be set with IP `172.19.17.99`
* It will download latest vagrant VBox and run `vagrant up` to initialise VM
* When you first time install or do 'Up' after destroying k8s Solo setup, k8s binary files (with the version which was available when the App was built) get copied to CoreOS VM, this speeds up Kubernetes setup. To update Kubernetes just run from menu 'Updates' - Update Kubernetes and OS X kubectl.
* It will install `fleetctl, etcdctl and kubectl` to `~/coreos-k8s-solo/bin/`
* Kubernetes services will be installed with fleet units which are placed in `~/coreos-k8s-solo/fleet`, this allows very easy updates to fleet units if needed.
* Also [DNS Add On](https://github.com/GoogleCloudPlatform/kubernetes/tree/master/cluster/addons/dns) will be installed

How it works
------------

Just start `CoreOS k8s Solo` application and you will find a small icon with the Kubernetes logo with (S) which means for Kubernetes Solo in the Status Bar.

* There you can `Up`, `Suspend`, `Halt`, `Reload` CoreOS vagrant VM
* Under `Up` (first does 'vagrant up') and `OS Shell` OS Shell (terminal) will have such environment set:
````
1) kubernetes master - export KUBERNETES_MASTER=http://172.19.17.99:8080
2) etcd endpoint - export ETCDCTL_PEERS=http://172.19.17.99:2379
3) fleetctl endpoint - export FLEETCTL_ENDPOINT=http://172.19.17.99:2379
4) fleetctl driver - export FLEETCTL_DRIVER=etcd
5) Path to ~/coreos-osx-solo/bin where etcdctl, fleetctl and kubernetes binaries are stored
````

* `Updates/Update Kubernetes and OS X kubectl` will update to latest version of Kubernetes.
* `Updates/Update OS X fleetctl, etcdclt and fleet units` will update fleetctl, etcdclt clients to the same versions as CoreOS VM run and to latest fleet units if the new version of App is used.
* `Updates/Force CoreOS update` will be run `sudo update_engine_client -update` on CoreOS VM.
* `Updates/Check updates for CoreOS vbox` will update CoreOS VM vagrant box.
*
* `SSH to k8solo-01` menu option will open VM shell
* `k8solo-01 cAdvisor` will open cAdvisor URL in default browser
* [Fleet-UI](http://fleetui.com) dashboard will show running fleet units and etc
* [Kubernetes-UI](https://github.com/GoogleCloudPlatform/kubernetes/tree/master/www) (contributed by [Kismatic.io](http://kismatic.io/)) will show nice Kubernetes Dashboard, where you can check Node, Pods, Replication Controllers and etc.

Example ouput of succesfull CoreOS + Kubernetes Solo install:

````
etcd cluster:
/coreos.com
/registry

fleetctl list-machines:
MACHINE		IP		METADATA
c576b883...	172.19.17.99	role=kube

fleetctl list-units:
UNIT									MACHINE				ACTIVE	SUB
fleet-ui.service				c576b883.../172.19.17.99	active	running
kube-apiserver.service			c576b883.../172.19.17.99	active	running
kube-controller-manager.service	c576b883.../172.19.17.99	active	running
kube-kubelet.service			c576b883.../172.19.17.99	active	running
kube-proxy.service				c576b883.../172.19.17.99	active	running
kube-scheduler.service			c576b883.../172.19.17.99	active	running

kubectl get nodes:
NAME           LABELS         STATUS
172.19.17.99   node=worker1   Ready

````

Usage
------------

You're now ready to use Kubernetes cluster.

Some examples to start with [Kubernetes examples](https://github.com/GoogleCloudPlatform/kubernetes/blob/master/examples/).

Other Apps
-----------
* Kubernetes Solo cluster CoreOS VM App based on [xhyve](https://github.com/coreos/coreos-xhyve) can be found here [Kubernetes Solo cluster for OS X](https://github.com/rimusz/kube-solo-osx).

* Cluster one with Kubernetes CoreOS VM App can be found here [CoreOS-Vagrant Kubernetes Cluster for OS X](https://github.com/rimusz/coreos-osx-kubernetes-cluster).

* A standalone CoreOS VM version App can be found here [CoreOS VM for OS X](https://github.com/rimusz/coreos-osx).

* Cluster one without Kubernetes CoreOS VM App can be found here [CoreOS-Vagrant Cluster](https://github.com/rimusz/coreos-osx-cluster).


text:
Imports System.IO
Imports System.Runtime.InteropServices

Module Example
    <STAThread()> _
    Sub Main()
        Dim objApplication As SolidEdgeFramework.Application = Nothing
        Dim objDraftDocument As SolidEdgeDraft.DraftDocument = Nothing
        Dim objSheet As SolidEdgeDraft.Sheet = Nothing
        Dim objDrawingViews As SolidEdgeDraft.DrawingViews = Nothing
        Dim objDrawingView As SolidEdgeDraft.DrawingView = Nothing
        Dim objModelMembers As SolidEdgeDraft.ModelMembers = Nothing
        Dim objModelMember As SolidEdgeDraft.ModelMember = Nothing

        Try
            OleMessageFilter.Register()

            objApplication = Marshal.GetActiveObject("SolidEdge.Application")
            objDraftDocument = objApplication.ActiveDocument
            objSheet = objDraftDocument.ActiveSheet
            objDrawingViews = objSheet.DrawingViews

            ' Loop through all drawing views in current sheet.
            For Each objDrawingView In objDrawingViews
                objModelMembers = objDrawingView.ModelMembers
                ' Walk the ModelTree recursively and set the settings on leaf nodes.
                For Each objModelMember In objModelMembers
                    UpdateModelMember(objModelMember)
                Next
            Next
        Catch ex As Exception
            Console.WriteLine(ex.Message)
        Finally
            OleMessageFilter.Revoke()
        End Try
    End Sub

    Sub UpdateModelMember(ByVal objParentModelMember As SolidEdgeDraft.ModelMember)
        Dim objChildModelMembers As SolidEdgeDraft.ModelMembers = Nothing
        Dim objChildModelMember As SolidEdgeDraft.ModelMember = Nothing

        objChildModelMembers = objParentModelMember.ModelMembers
        For Each objChildModelMember In objChildModelMembers
            UpdateModelMember(objChildModelMember)
        Next

        If objChildModelMembers.Count = 0 Then
            objParentModelMember.ShowEdgesHiddenByOtherParts = True
            objParentModelMember.ShowEdgesHiddenTangentEdgesHiddenByOtherParts = True
        End If
    End Sub
End Module


text:
FBPhysicalPropertiesImplementation( MOPlayerPhysProperties );
FBRegisterPhysicalProperties( "MOPlayerPhysProperties",
								MOPlayerPhysProperties,
								"Phys Player",
								"Phys Player Desc",
								FB_DEFAULT_SDK_ICON );

///////////////////////////////////////////////////////////////////////////////////////////////////////////
//

//
bool MOPlayerPhysProperties::FBCreate()
{
	//
	mOnline = false;

	//
	// information properties

	FBPropertyPublish( this, Active, "Active", nullptr, nullptr );
	Active = true;

	return true;
}

void MOPlayerPhysProperties::FBDestroy()
{
}

void AddPropertyViewForPlayerPhysics(const char* pPropertyName, const char* pHierarchy, bool pIsFolder=false)
{
	FBPropertyViewManager::TheOne().AddPropertyView(MOPLAYERPHYSPROPERTIES__CLASSSTR, pPropertyName, pHierarchy);
}

void MOPlayerPhysProperties::AddPropertiesToPropertyViewManager()
{

	AddPropertyViewForPlayerPhysics("Active", "");
}


text:
"""The group type & group type specs controller."""

from oslo_utils import strutils
import six
import webob
from webob import exc

from cinder.api import common
from cinder.api.openstack import wsgi
from cinder.api.v3.views import group_types as views_types
from cinder import exception
from cinder.i18n import _
from cinder import policy
from cinder import rpc
from cinder import utils
from cinder.volume import group_types

class GroupTypesController(wsgi.Controller):
    """The group types API controller for the OpenStack API."""

    _view_builder_class = views_types.ViewBuilder

    def _check_policy(self, context):
        target = {
            'project_id': context.project_id,
            'user_id': context.user_id,
        }
        policy.enforce(context, 'group:group_types_manage', target)

    @utils.if_notifications_enabled
    def _notify_group_type_error(self, context, method, err,
                                 group_type=None, id=None, name=None):
        payload = dict(
            group_types=group_type, name=name, id=id, error_message=err)
        rpc.get_notifier('groupType').error(context, method, payload)

    @utils.if_notifications_enabled
    def _notify_group_type_info(self, context, method, group_type):
        payload = dict(group_types=group_type)
        rpc.get_notifier('groupType').info(context, method, payload)

    @wsgi.Controller.api_version('3.11')
    @wsgi.response(202)
    def create(self, req, body):
        """Creates a new group type."""
        context = req.environ['cinder.context']
        self._check_policy(context)

        self.assert_valid_body(body, 'group_type')

        grp_type = body['group_type']
        name = grp_type.get('name', None)
        description = grp_type.get('description')
        specs = grp_type.get('group_specs', {})
        is_public = grp_type.get('is_public', True)

        if name is None or len(name.strip()) == 0:
            msg = _("Group type name can not be empty.")
            raise webob.exc.HTTPBadRequest(explanation=msg)

        utils.check_string_length(name, 'Type name',
                                  min_length=1, max_length=255)

        if description is not None:
            utils.check_string_length(description, 'Type description',
                                      min_length=0, max_length=255)

        try:
            group_types.create(context,
                               name,
                               specs,
                               is_public,
                               description=description)
            grp_type = group_types.get_group_type_by_name(context, name)
            req.cache_resource(grp_type, name='group_types')
            self._notify_group_type_info(
                context, 'group_type.create', grp_type)

        except exception.GroupTypeExists as err:
            self._notify_group_type_error(
                context, 'group_type.create', err, group_type=grp_type)
            raise webob.exc.HTTPConflict(explanation=six.text_type(err))
        except exception.GroupTypeNotFoundByName as err:
            self._notify_group_type_error(
                context, 'group_type.create', err, name=name)
            raise webob.exc.HTTPNotFound(explanation=err.msg)

        return self._view_builder.show(req, grp_type)

    @wsgi.Controller.api_version('3.11')
    def update(self, req, id, body):
        # Update description for a given group type.
        context = req.environ['cinder.context']
        self._check_policy(context)

        self.assert_valid_body(body, 'group_type')

        grp_type = body['group_type']
        description = grp_type.get('description')
        name = grp_type.get('name')
        is_public = grp_type.get('is_public')

        # Name and description can not be both None.
        # If name specified, name can not be empty.
        if name and len(name.strip()) == 0:
            msg = _("Group type name can not be empty.")
            raise webob.exc.HTTPBadRequest(explanation=msg)

        if name is None and description is None and is_public is None:
            msg = _("Specify group type name, description or "
                    "a combination thereof.")
            raise webob.exc.HTTPBadRequest(explanation=msg)

        if is_public is not None and not strutils.is_valid_boolstr(is_public):
            msg = _("Invalid value '%s' for is_public. Accepted values: "
                    "True or False.") % is_public
            raise webob.exc.HTTPBadRequest(explanation=msg)

        if name:
            utils.check_string_length(name, 'Type name',
                                      min_length=1, max_length=255)

        if description is not None:
            utils.check_string_length(description, 'Type description',
                                      min_length=0, max_length=255)

        try:
            group_types.update(context, id, name, description,
                               is_public=is_public)
            # Get the updated
            grp_type = group_types.get_group_type(context, id)
            req.cache_resource(grp_type, name='group_types')
            self._notify_group_type_info(
                context, 'group_type.update', grp_type)

        except exception.GroupTypeNotFound as err:
            self._notify_group_type_error(
                context, 'group_type.update', err, id=id)
            raise webob.exc.HTTPNotFound(explanation=six.text_type(err))
        except exception.GroupTypeExists as err:
            self._notify_group_type_error(
                context, 'group_type.update', err, group_type=grp_type)
            raise webob.exc.HTTPConflict(explanation=six.text_type(err))
        except exception.GroupTypeUpdateFailed as err:
            self._notify_group_type_error(
                context, 'group_type.update', err, group_type=grp_type)
            raise webob.exc.HTTPInternalServerError(
                explanation=six.text_type(err))

        return self._view_builder.show(req, grp_type)

    @wsgi.Controller.api_version('3.11')
    def delete(self, req, id):
        """Deletes an existing group type."""
        context = req.environ['cinder.context']
        self._check_policy(context)

        try:
            grp_type = group_types.get_group_type(context, id)
            group_types.destroy(context, grp_type['id'])
            self._notify_group_type_info(
                context, 'group_type.delete', grp_type)
        except exception.GroupTypeInUse as err:
            self._notify_group_type_error(
                context, 'group_type.delete', err, group_type=grp_type)
            msg = _('Target group type is still in use.')
            raise webob.exc.HTTPBadRequest(explanation=msg)
        except exception.GroupTypeNotFound as err:
            self._notify_group_type_error(
                context, 'group_type.delete', err, id=id)
            raise webob.exc.HTTPNotFound(explanation=err.msg)

        return webob.Response(status_int=202)

    @wsgi.Controller.api_version('3.11')
    def index(self, req):
        """Returns the list of group types."""
        limited_types = self._get_group_types(req)
        req.cache_resource(limited_types, name='group_types')
        return self._view_builder.index(req, limited_types)

    @wsgi.Controller.api_version('3.11')
    def show(self, req, id):
        """Return a single group type item."""
        context = req.environ['cinder.context']

        # get default group type
        if id is not None and id == 'default':
            grp_type = group_types.get_default_group_type()
            if not grp_type:
                msg = _("Default group type can not be found.")
                raise exc.HTTPNotFound(explanation=msg)
            req.cache_resource(grp_type, name='group_types')
        else:
            try:
                grp_type = group_types.get_group_type(context, id)
                req.cache_resource(grp_type, name='group_types')
            except exception.GroupTypeNotFound as error:
                raise exc.HTTPNotFound(explanation=error.msg)

        return self._view_builder.show(req, grp_type)

    def _parse_is_public(self, is_public):
        """Parse is_public into something usable.

        * True: List public group types only
        * False: List private group types only
        * None: List both public and private group types
        """

        if is_public is None:
            # preserve default value of showing only public types
            return True
        elif utils.is_none_string(is_public):
            return None
        else:
            try:
                return strutils.bool_from_string(is_public, strict=True)
            except ValueError:
                msg = _('Invalid is_public filter [%s]') % is_public
                raise exc.HTTPBadRequest(explanation=msg)

    def _get_group_types(self, req):
        """Helper function that returns a list of type dicts."""
        params = req.params.copy()
        marker, limit, offset = common.get_pagination_params(params)
        sort_keys, sort_dirs = common.get_sort_params(params)
        filters = {}
        context = req.environ['cinder.context']
        if context.is_admin:
            # Only admin has query access to all group types
            filters['is_public'] = self._parse_is_public(
                req.params.get('is_public', None))
        else:
            filters['is_public'] = True
        utils.remove_invalid_filter_options(context,
                                            filters,
                                            self._get_grp_type_filter_options()
                                            )
        limited_types = group_types.get_all_group_types(context,
                                                        filters=filters,
                                                        marker=marker,
                                                        limit=limit,
                                                        sort_keys=sort_keys,
                                                        sort_dirs=sort_dirs,
                                                        offset=offset,
                                                        list_result=True)
        return limited_types

    def _get_grp_type_filter_options(self):
        """Return group type search options allowed by non-admin."""
        return ['is_public']

def create_resource():
    return wsgi.Resource(GroupTypesController())


text:
package org.apache.fineract.portfolio.collectionsheet.service;

import org.apache.fineract.infrastructure.core.api.JsonQuery;
import org.apache.fineract.portfolio.collectionsheet.data.IndividualCollectionSheetData;
import org.apache.fineract.portfolio.collectionsheet.data.JLGCollectionSheetData;

public interface CollectionSheetReadPlatformService {

    JLGCollectionSheetData generateGroupCollectionSheet(final Long groupId, final JsonQuery query);

    JLGCollectionSheetData generateCenterCollectionSheet(final Long groupId, final JsonQuery query);

    IndividualCollectionSheetData generateIndividualCollectionSheet(final JsonQuery query);

}


text:
#region Copyright

#endregion

#region

using Autodesk.DesignScript.Runtime;
using Dynamo.Models;
using System.Collections.Generic;
using Dynamo.Nodes;
using Dynamo.Graph.Nodes;

#endregion

namespace Analysis.Beam
{

    [IsDesignScriptCompatible]
    public partial class Torsion
    {

         //[IsVisibleInDynamoLibrary(false)]
        internal Torsion(double L, double X, double P, double M, double w, double a_load, double b_load, double c_load, double P1, double P2, double M1, double M2)
        {

        }
        [IsVisibleInDynamoLibrary(false)]
         public static Torsion ByInputParameters(double L, double X, double P, double M, double w, double a_load, double b_load, double c_load, double P1, double P2, double M1, double M2)
        {
            return new Torsion(L, X, P, M, w, a_load, b_load, c_load, P1, P2, M1, M2);
        }

    }
}


text:
package org.kohsuke.github;

import java.util.Locale;

/**
 * Permission for a user in a repository.
 * @see API
 */
/*package*/ class GHPermission {

    private String permission;
    private GHUser user;

    /**
     * @return one of {@code admin}, {@code write}, {@code read}, or {@code none}
     */
    public String getPermission() {
        return permission;
    }

    public GHPermissionType getPermissionType() {
        return Enum.valueOf(GHPermissionType.class, permission.toUpperCase(Locale.ENGLISH));
    }

    public GHUser getUser() {
        return user;
    }

    void wrapUp(GitHub root) {
        if (user != null) {
            user.root = root;
        }
    }

}


text:
namespace NewWave.Core
{
	public interface IParameterList { }
}