text:
package org.auraframework.impl.visitor;

import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasProperty;
import static org.hamcrest.Matchers.hasSize;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;

import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.auraframework.system.Location;
import org.hamcrest.Matchers;
import org.junit.Test;

import com.google.common.collect.Lists;

/**
 * A visitor class to extract labels from a set of definitions.
 */
public class UsageMapTest {
    @Test
    public void testAddOneEntry() throws Exception {
        String key = "key";
        Location location1 = new Location("file1", 0);
        UsageMap<String> underTest = new UsageMap<>();
        underTest.add(key, location1);
        Set<Map.Entry<String, Set<Location>>> entrySet = underTest.entrySet();
        assertThat("Should have one entry", entrySet, Matchers.iterableWithSize(1));
        assertThat(entrySet, contains(hasProperty("key", equalTo(key))));
        assertThat(entrySet, contains(hasProperty("value", hasSize(1))));
        assertThat(entrySet, contains(hasProperty("value", contains(location1))));
    }

    @Test
    public void testAddTwoEntriesOneKey() throws Exception {
        String key = "key";
        Location location1 = new Location("file1", 0);
        Location location2 = new Location("file2", 0);
        UsageMap<String> underTest = new UsageMap<>();
        underTest.add(key, location1);
        underTest.add(key, location2);
        Set<Map.Entry<String, Set<Location>>> entrySet = underTest.entrySet();
        assertThat(entrySet, hasSize(1));
        assertThat(entrySet, contains(hasProperty("key", equalTo(key))));
        assertThat(entrySet, contains(hasProperty("value", hasSize(2))));
        assertThat(entrySet, contains(hasProperty("value", contains(location1, location2))));
    }

    @Test
    public void testAddTwoEntriesTwoKeys() throws Exception {
        String key = "key";
        String key2 = "keyx";
        Location location1 = new Location("file1", 0);
        Location location2 = new Location("file2", 0);
        UsageMap<String> underTest = new UsageMap<>();
        underTest.add(key, location1);
        underTest.add(key2, location2);
        Set<Map.Entry<String, Set<Location>>> entrySet = underTest.entrySet();
        assertEquals(2, entrySet.size());
        Iterator<Map.Entry<String, Set<Location>>> iterator = entrySet.iterator();
        Map.Entry<String, Set<Location>> entry1 = iterator.next();
        Map.Entry<String, Set<Location>> entry2 = iterator.next();
        // swap
        if (!entry1.getKey().equals(key)) {
            Map.Entry<String, Set<Location>> tmp = entry2;
            entry2 = entry1;
            entry1 = tmp;
        }
        assertThat(entry1.getKey(), equalTo(key));
        assertThat(entry1.getValue(), hasSize(1));
        assertThat(entry1.getValue(), contains(location1));

        assertThat(entry2.getKey(), equalTo(key2));
        assertThat(entry2.getValue(), hasSize(1));
        assertThat(entry2.getValue(), contains(location2));
    }

    @SuppressWarnings("static-method")
    @Test
    public void testAddAllOneEntry() throws Exception {
        String key = "key";
        Location location1 = new Location("file1", 0);
        Location location2 = new Location("file2", 0);
        List<Location> locations = Lists.newArrayList(location1, location2);
        UsageMap<String> underTest = new UsageMap<>();
        underTest.addAll(key, locations);
        Set<Map.Entry<String, Set<Location>>> entrySet = underTest.entrySet();

        assertThat(entrySet, hasSize(1));
        assertThat(entrySet, contains(hasProperty("key", equalTo(key))));

        Set<Location> actualLocation = entrySet.iterator().next().getValue();
        assertThat(actualLocation, hasSize(2));
        assertThat(actualLocation, contains(location1, location2));
    }

    @Test
    public void testAddAllTwoEntriesTwoKeys() throws Exception {
        String key1 = "key1";
        Location location1 = new Location("file1", 0);
        Location location2 = new Location("file2", 0);
        List<Location> locations1 = Lists.newArrayList(location1, location2);

        String key2 = "key2";
        Location location3 = new Location("file3", 0);
        Location location4 = new Location("file4", 0);
        List<Location> locations2 = Lists.newArrayList(location3, location4);

        UsageMap<String> underTest = new UsageMap<>();
        underTest.addAll(key1, locations1);
        underTest.addAll(key2, locations2);

        Set<Location> actualLocations1 = null;
        Set<Location> actualLocations2 = null;

        Set<Map.Entry<String, Set<Location>>> entrySet = underTest.entrySet();
        assertThat(entrySet, hasSize(2));

        for (Map.Entry<String, Set<Location>> entry : entrySet) {
            if (entry.getKey().equals(key1)) {
                actualLocations1 = entry.getValue();
            } else if (entry.getKey().equals(key2)) {
                actualLocations2 = entry.getValue();
            } else {
                fail("unexpected key "+entry.getKey());
            }
        }

        assertThat(actualLocations1, hasSize(2));
        assertThat(actualLocations1, containsInAnyOrder(location1, location2));

        assertThat(actualLocations2, hasSize(2));
        assertThat(actualLocations2, containsInAnyOrder(location3, location4));
    }

    @Test
    public void testAddAllTwoEntriesOneKey() throws Exception {
        String key1 = "key1";
        Location location1 = new Location("file1", 0);
        Location location2 = new Location("file2", 0);
        List<Location> locations1 = Lists.newArrayList(location1, location2);

        Location location3 = new Location("file3", 0);
        Location location4 = new Location("file4", 0);
        List<Location> locations2 = Lists.newArrayList(location3, location4);

        UsageMap<String> underTest = new UsageMap<>();
        underTest.addAll(key1, locations1);
        underTest.addAll(key1, locations2);

        Set<Map.Entry<String, Set<Location>>> entrySet = underTest.entrySet();
        assertThat(entrySet, hasSize(1));
        Map.Entry<String, Set<Location>> entry = entrySet.iterator().next();

        assertThat(entry.getKey(), equalTo(key1));
        assertThat(entry.getValue(), hasSize(4));
        assertThat(entry.getValue(), containsInAnyOrder(location1, location2, location3, location4));
    }

    @Test
    public void testAddAllTwoEntriesOneKeyValueOverlap() throws Exception {
        String key1 = "key1";
        Location location1 = new Location("file1", 0);
        Location location2 = new Location("file2", 0);
        List<Location> locations1 = Lists.newArrayList(location1, location2);

        Location location3 = new Location("file3", 0);
        List<Location> locations2 = Lists.newArrayList(location2, location3);

        UsageMap<String> underTest = new UsageMap<>();
        underTest.addAll(key1, locations1);
        underTest.addAll(key1, locations2);

        Set<Map.Entry<String, Set<Location>>> entrySet = underTest.entrySet();
        assertThat(entrySet, hasSize(1));
        Map.Entry<String, Set<Location>> entry = entrySet.iterator().next();

        assertThat(entry.getKey(), equalTo(key1));
        assertThat(entry.getValue(), hasSize(3));
        assertThat(entry.getValue(), containsInAnyOrder(location1, location2, location3));
    }

    @Test
    public void testAddAllTwoEntriesOneKeyValueEqualsOverlap() throws Exception {
        String key1 = "key1";
        Location location1 = new Location("file1", 0);
        Location location2 = new Location("file2", 0);
        List<Location> locations1 = Lists.newArrayList(location1, location2);

        Location location3 = new Location("file3", 0);
        Location location4 = new Location("file2", 0);
        assertThat(location4, Matchers.samePropertyValuesAs(location2));
        List<Location> locations2 = Lists.newArrayList(location3, location4);

        UsageMap<String> underTest = new UsageMap<>();
        underTest.addAll(key1, locations1);
        underTest.addAll(key1, locations2);

        Set<Map.Entry<String, Set<Location>>> entrySet = underTest.entrySet();
        assertThat(entrySet, hasSize(1));
        Map.Entry<String, Set<Location>> entry = entrySet.iterator().next();

        assertThat(entry.getKey(), equalTo(key1));
        assertThat(entry.getValue(), hasSize(3));
        assertThat(entry.getValue(), containsInAnyOrder(location1, location2, location3));
    }
}


text:
require File.dirname(__FILE__) + '/spec_helper.rb'

describe 'Faker::Weapon' do

  describe '.name' do

    describe 'with no options set' do
      it 'will return just a weapon' do
        expect(Faker::Weapon.name).to match /(Sword|Bow)/
      end
    end

    describe 'with multiple options' do
      it 'applies multiple options to a weapon' do
        (0..20).each do
          expect( Faker::Weapon.name(owned: true,
                                          conditioned: true,
                                          modified: true,
                                          enchanted: true) ).to match /James's (\+|\-)\d Masterful (Sword|Bow) of Testing/
        end
      end
    end

    describe 'with specified weapon' do
      it 'will return the specified weapon' do
        expect( Faker::Weapon.name(weapon: 'Gun') ).to eq 'Gun'
      end
    end

    describe 'with no type set' do
      it 'will return either a ranged or a melee weapon' do
        melee = false
        ranged = false

        (0..20).each do
          weapon = Faker::Weapon.name
          if weapon == 'Bow'
            ranged = true
          elsif weapon == 'Sword'
            melee = true
          end
        end

        expect(melee && ranged).to eq true
      end
    end

    describe 'with the type option set' do

      describe 'to melee' do
        it 'will return a melee weapon' do
          expect(Faker::Weapon.name(type: :melee)).to eq 'Sword'
        end
      end

      describe 'to ranged' do
        it 'will return a melee weapon' do
          expect(Faker::Weapon.name(type: :ranged)).to eq 'Bow'
        end
      end

    end

    describe 'with the material option set' do

      describe 'to true' do
        it 'returns a weapon with a material' do
          expect(Faker::Weapon.name(materialed: true)).to match /Iron./
        end
      end

      describe 'with a material specified' do
        it 'returns a weapon with the given material' do
          expect(Faker::Weapon.name(materialed: { material: 'Jelly'})).to match /Jelly./
        end
      end

    end

    describe 'with the owner option set' do

      describe 'to true' do
        it 'returns a weapon with an owner generated by Faker::Name' do
          expect(Faker::Weapon.name(owned: true)).to match /James's./
        end
      end

      describe 'with an owner specified' do
        it 'returns a weapon wth the specified owner' do
          expect(Faker::Weapon.name(owned: { owner: 'Lockyy'})).to match /Lockyy's./
        end
      end

    end

    describe 'with the enchantment option set' do

      describe 'to true' do
        it 'returns a weapon with a randomised enchantment' do
          expect(Faker::Weapon.name(enchanted: true)).to match /.of Testing/
        end
      end

      describe 'with a specific enchantment' do
        it 'returns a weapon with that specific enchantment' do
          expect(Faker::Weapon.name(enchanted: { enchantment: 'Jellification'})).to match /.of Jellification/
        end
      end

    end

    describe 'with the condition option set' do

      describe 'to true' do
        it 'returns a weapon with a condition' do
          expect(Faker::Weapon.name(conditioned: true)).to match /Masterful ./
        end
      end

      describe 'with a specific condition set' do
        it 'returns a weapon with that condition' do
          expect(Faker::Weapon.name(conditioned: { condition: 'Jellied'})).to match /Jellied ./
        end
      end

    end

    describe 'with the modifier option set' do

      describe 'to true' do
        it 'will return a weapon with a modifier' do
          expect(Faker::Weapon.name(modified: true)).to match /(\+|\-)\d ./
        end
      end

      describe 'with specific modifier' do
        it 'will return a weapon with that modifier' do
          expect(Faker::Weapon.name(modified: { modifier: '+13' })).to match /\+13 ./
        end
      end

      describe 'with a negative range' do
        it 'will return a range with a negative modifier within the given range' do
          (0..20).each do
            expect(Faker::Weapon.name(modified: { min: -5, max: 0 })).to match /\-[1-5] ./
          end
        end
      end

      describe 'with a positive range' do
        it 'will return a range with a positive modifier within the given range' do
          (0..20).each do
            expect(Faker::Weapon.name(modified: { min: 1, max: 5 })).to match /\+[1-5] ./
          end
        end
      end

      describe 'error checking' do

        describe 'that prevents zero value modifiers' do
          it 'will revert to the default -9/+9 range' do
            (0..20).each do
              expect(Faker::Weapon.name(modified: { min: 0, max: 0 })).to match /(\+|\-)[1-9] ./
            end
          end
        end

        describe 'that prevents min from being greater than max' do
          it 'will revert to the default -9/+9 range' do
            (0..20).each do
              expect(Faker::Weapon.name(modified: { min: 100, max: 90 })).to match /(\+|\-)[1-9] ./
            end
          end
        end

      end

    end

  end

end

redpajama_set_name: RedPajamaGithub


text:
module BloomApi

  # A class representing a generic provider. This is a base
  # class for individuals and organizations.
  class Provider

    # Create a new provider
    # @param [Hash]
    #   a hash representation of a json provider
    #   object from the bloom API
    def initialize(raw_provider)
      @raw_provider = raw_provider
    end

    # @return [BloomApi::Address] the provider's business address
    def business_address
      Address.new(@raw_provider['business_address'])
    end

    # @return [Date]
    #   if the provider has been deactivated returns the date of deactivation
    # @return [nil] if the the provider has not been deactivated
    def deactivation_date
      unless @raw_provider['deactivation_date'].nil?
        Time.parse(@raw_provider['deactivation_date']).to_date
      end
    end

    # @return [String] the reason the provider was deactivated
    def deactivation_reason
      @raw_provider['deactivation_reason']
    end

    # @return [String] the provider's national provider identifier
    def npi
      @raw_provider['npi']
    end

    # @return [BloomApi::Address] the provider's practice address
    def practice_address
      Address.new(@raw_provider['practice_address'])
    end

    # @return [Array] A list of alternate identifiers for the provider
    def other_identifiers
      unless @raw_provider['other_identifiers'].nil?
        @raw_provider['other_identifiers'].collect { |i| BloomApi::Identifier.new(i) }
      end
    end

    # @return [String]
    #   a type describing the purpose of the provider's alternate name
    def other_name_type
      @raw_provider['other_name_type']
    end

    # @return [Date]
    #   the reactivation date for the provider if it's been reactivated
    # @return [nil] if the provider has not been reactivated
    def reactivation_date
      unless @raw_provider['reactivation_date'].nil?
        Time.parse(@raw_provider['reactivation_date']).to_date
      end
    end

    # @return [Date]
    #   the date that the provider information was recorded
    def recorded_at
      Time.parse(@raw_provider['enumeration_date']).to_date
    end

    # @return [String]
    #   the provider's replacement npi
    def replacement_npi
      @raw_provider['replacement_npi']
    end

    # @return [boolean] true if the provider is a sole proprietor
    # @return [boolean] false if the provider is not a sole proprietor
    def sole_proprietor?
      case @raw_provider['sole_proprietor']
      when 'yes'
        true
      when 'no'
        false
      else
        nil
      end
    end

    # @return [Array] an array of specialties held by the provider
    def specialties
      unless @raw_provider['provider_details'].nil?
        @raw_provider['provider_details'].collect { |s| Specialty.new(s) }
      end
    end

    # @return [Array] an array of taxonomy groups for the provider
    def taxonomy_groups
      unless @raw_provider['taxonomy_groups'].nil?
        @raw_provider['taxonomy_groups'].collect { |g| g['taxonomy']}
      end
    end

    # @return [String]
    #   The provider type. Possible values are:
    #   * individual
    #   * organization
    def type
      @raw_provider['type']
    end

    # @return [Date] the date that the provider's data was last updated
    def updated_at
      Time.parse(@raw_provider['last_update_date']).to_date
    end
  end
end


text:
using System;

namespace holaMundo
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hola Mundo");
            Console.ReadLine();
        }
    }
}


text:
package tw.com.commandline.actions;

import org.apache.commons.cli.MissingArgumentException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import software.amazon.awssdk.services.cloudformation.model.Parameter;
import tw.com.AwsFacade;
import tw.com.FacadeFactory;
import tw.com.commandline.CommandLineException;
import tw.com.entity.ProjectAndEnv;
import tw.com.exceptions.CfnAssistException;

import java.nio.file.Path;
import java.util.Collection;
import java.util.List;

public class FetchLogsAction extends SharedAction {
	private static final Logger logger = LoggerFactory.getLogger(FetchLogsAction.class);

	@SuppressWarnings("static-access")
	public FetchLogsAction() {
        createOptionWithArgs("logs", "Fetchs logs for project for last N hours", 1);
	}

	public void invoke(FacadeFactory factory, ProjectAndEnv projectAndEnv, Collection<Parameter> unused,
			Collection<Parameter> artifacts, String... args) throws CfnAssistException, MissingArgumentException, InterruptedException {
		logger.info("Invoking get logs for " + projectAndEnv + " and " + args[0]);
		AwsFacade aws = factory.createFacade();
		int hours = Integer.parseInt(args[0]);

		List<Path> filenames = aws.fetchLogs(projectAndEnv, hours);
		System.out.println("Logs for " + projectAndEnv);
		filenames.forEach(filename -> {
		    System.out.println(String.format("Saved file '%s'", filename.toAbsolutePath().toString()));;
        });
        System.out.flush();
    }

	@Override
	public void validate(ProjectAndEnv projectAndEnv, Collection<Parameter> cfnParams,
			Collection<Parameter> artifacts, String... argumentForAction)
			throws CommandLineException {
		guardForProjectAndEnv(projectAndEnv);
	}

	@Override
	public boolean usesProject() {
		return true;
	}

	@Override
	public boolean usesComment() {
		return false;
	}

	@Override
	public boolean usesSNS() {
		return true;
	}

}


text:
require 'optparse'
require 'eventfabric'
require 'ostruct'
require 'json'
require 'pp'

def parse_args(args)
    #parse and return command line arguments
    options = OpenStruct.new
    options.username = ""
    options.password = ""
    options.channel = ""
    options.path = ""
    options.url = ""

    opt_parser = OptionParser.new do |opt|
        opt.banner = "Usage: ruby sendjson.rb [OPTIONS]"
        opt.separator  ""
        opt.separator  "Options"

        opt.on("-u", "--username USERNAME", "Username to authenticate to Event Fabric") do |username|
            options.username << username
        end

        opt.on("-p", "--password PASSWORD", "Password to authenticate to Event Fabric") do |password|
            options.password << password
        end

        opt.on("-c", "--channel CHANNEL", "Channel used in the generated event") do |channel|
            options.channel << channel
        end

        opt.on("-P", "--path PATH", "Path to the JSON file you want to send") do |path|
            options.path << path
        end

        opt.on("-U", "--url URL", "URL for Event Fabric API") do |url|
            options.url = url || "https://event-fabric.com/ef/api/"
        end
        opt.on("-h", "--help", "help") do
            puts opt_parser
            return nil
        end
    end

    opt_parser.parse!(args)

    options
end

def main
    #main program entry point
    args = parse_args(ARGV)

    if args == nil
        return
    end

    pp "Config:", args.username, args.password, args.channel, args.path, args.url

    client = EventFabric::Client.new(args.username, args.password, args.url)
    begin
        login_response = client.login

        if login_response.code != "201"
            pp "Error authenticating", login_response
            return
        end

        begin
            file = open(args.path)
            json = file.read
            value = JSON.parse(json)
        rescue Exception => error
            pp "Error opening file", args.path, error
            return
        end

        event = EventFabric::Event.new(value, args.channel)
        send_response = client.send_event(event)
        pp "Send Event:", event.json

        if send_response.code != "201"
            pp "Error sending event", send_response
            return
        end

        rescue Exception => conn_error
            pp "Error connection to server", args.url, conn_error
            return
        end
    end

$end

if __FILE__ == $PROGRAM_NAME
    main
end


text:
#ifndef QUICKSTEP_UTILITY_LIP_FILTER_BIT_VECTOR_EXACT_FILTER_HPP_
#define QUICKSTEP_UTILITY_LIP_FILTER_BIT_VECTOR_EXACT_FILTER_HPP_

#include <cstddef>
#include <cstdint>
#include <vector>

#include "catalog/CatalogTypedefs.hpp"
#include "storage/StorageBlockInfo.hpp"
#include "storage/ValueAccessor.hpp"
#include "storage/ValueAccessorUtil.hpp"
#include "types/Type.hpp"
#include "utility/BarrieredReadWriteConcurrentBitVector.hpp"
#include "utility/Macros.hpp"
#include "utility/lip_filter/LIPFilter.hpp"

#include "glog/logging.h"

namespace quickstep {

/** \addtogroup Utility
 *  @{
 */

/**
 * @brief A LIP filter that tests the EXACT memberships of elements, i.e. there
 *        will be neither false positives nor false negatives. The implementation
 *        is to simply reinterpret_cast a value's byte stream into the specified
 *        CppType as the underlying bit vector's index. Therefore, to use this
 *        filter, the corresponding LIP attribute's values must be bounded in a
 *        reasonably small integer range.
 */
template <typename CppType, bool is_anti_filter>
class BitVectorExactFilter : public LIPFilter {
 public:
  /**
   * @brief Constructor.
   *
   * @param min_value The minimum possible value for this filter to set.
   * @param max_value The maximum possible value for this filter to set.
   */
  explicit BitVectorExactFilter(const std::int64_t min_value,
                                const std::int64_t max_value)
      : LIPFilter(LIPFilterType::kBitVectorExactFilter),
        min_value_(static_cast<CppType>(min_value)),
        max_value_(static_cast<CppType>(max_value)),
        bit_vector_(max_value - min_value + 1) {
    DCHECK_EQ(min_value, static_cast<std::int64_t>(min_value_));
    DCHECK_EQ(max_value, static_cast<std::int64_t>(max_value_));
    DCHECK_GE(max_value_, min_value_);
  }

  void insertValueAccessor(ValueAccessor *accessor,
                           const attribute_id attr_id,
                           const Type *attr_type) override {
    InvokeOnAnyValueAccessor(
        accessor,
        [&](auto *accessor) -> void {  // NOLINT(build/c++11)
      if (attr_type->isNullable()) {
        this->insertValueAccessorInternal<true>(accessor, attr_id);
      } else {
        this->insertValueAccessorInternal<false>(accessor, attr_id);
      }
    });
  }

  std::size_t filterBatch(ValueAccessor *accessor,
                          const attribute_id attr_id,
                          const bool is_attr_nullable,
                          std::vector<tuple_id> *batch,
                          const std::size_t batch_size) const override {
    DCHECK(batch != nullptr);
    DCHECK_LE(batch_size, batch->size());

    return InvokeOnAnyValueAccessor(
        accessor,
        [&](auto *accessor) -> std::size_t {  // NOLINT(build/c++11)
      if (is_attr_nullable) {
        return this->filterBatchInternal<true>(accessor, attr_id, batch, batch_size);
      } else {
        return this->filterBatchInternal<false>(accessor, attr_id, batch, batch_size);
      }
    });
  }

 private:
  /**
   * @brief Iterate through the accessor and hash values into the internal bit
   *        array.
   */
  template <bool is_attr_nullable, typename ValueAccessorT>
  inline void insertValueAccessorInternal(ValueAccessorT *accessor,
                                          const attribute_id attr_id) {
    accessor->beginIteration();
    while (accessor->next()) {
      const void *value = accessor->template getUntypedValue<is_attr_nullable>(attr_id);
      if (!is_attr_nullable || value != nullptr) {
        insert(value);
      }
    }
  }

  /**
   * @brief Filter the given batch of tuples from a ValueAccessor. Write the
   *        tuple ids which survive in the filtering back to \p batch.
   */
  template <bool is_attr_nullable, typename ValueAccessorT>
  inline std::size_t filterBatchInternal(const ValueAccessorT *accessor,
                                         const attribute_id attr_id,
                                         std::vector<tuple_id> *batch,
                                         const std::size_t batch_size) const {
    std::size_t out_size = 0;
    for (std::size_t i = 0; i < batch_size; ++i) {
      const tuple_id tid = batch->at(i);
      const void *value =
          accessor->template getUntypedValueAtAbsolutePosition(attr_id, tid);
      if (is_attr_nullable && value == nullptr) {
        continue;
      }
      if (contains(value)) {
        batch->at(out_size) = tid;
        ++out_size;
      }
    }
    return out_size;
  }

  /**
   * @brief Inserts a given value into the exact filter.
   */
  inline void insert(const void *key_begin) {
    const CppType value = *reinterpret_cast<const CppType *>(key_begin);
    DCHECK_GE(value, min_value_);
    DCHECK_LE(value, max_value_);

    bit_vector_.setBit(value - min_value_);
  }

  /**
   * @brief Test membership of a given value in the exact filter.
   */
  inline bool contains(const void *key_begin) const {
    const CppType value = *reinterpret_cast<const CppType *>(key_begin);
    if (value < min_value_ || value > max_value_) {
      return is_anti_filter;
    }

    const bool is_bit_set = bit_vector_.getBit(value - min_value_);

    if (is_anti_filter) {
      return !is_bit_set;
    } else {
      return is_bit_set;
    }
  }

  const CppType min_value_;
  const CppType max_value_;
  BarrieredReadWriteConcurrentBitVector bit_vector_;

  DISALLOW_COPY_AND_ASSIGN(BitVectorExactFilter);
};

/** @} */

}  // namespace quickstep

#endif  // QUICKSTEP_UTILITY_LIP_FILTER_BIT_VECTOR_EXACT_FILTER_HPP_


text:
function validateForm(theForm)
 {
var errorStatus = false;
var errorFields ="Please correct the following error(s)\n";

  if(document.agenttofirm.taxId.value == "")
   {
	errorFields+="Tax ID is a required field \n";
	errorStatus = true;
   }
  else
   {
   	checkTaxID(document.agenttofirm.taxId.value);
   }

if(document.agenttofirm.firmName.value == "")
   {
	errorFields+="Firm Name is a required field\n";
	errorStatus	= true;
   }  else
   {
	checkFirmName(document.agenttofirm.firmName.value);
   }
  if(document.agenttofirm.locName.value != "")
   {

   /*
	errorFields+="Location Name is a required field\n";
 	errorStatus = true;
   }
  else
   {
   */

	checkLocName(document.agenttofirm.locName.value);
   }

  if(document.agenttofirm.businessType.value == "")
   {
	errorFields+="Business Type is a required field\n";
 	errorStatus = true;
   }

if ( errorFields == true )
{
	alert(errorFields);
	return false;
}
else
	return true;

function checkTaxID(TaxID)
 {
   var checkOK = "0123456789";
   var checkStr = TaxID;
   var allValid = true;
   var decPoints = 0;
   var allNum = "";
   for (i = 0;  i < checkStr.length;  i++)
    {
     ch = checkStr.charAt(i);
     for (j = 0;  j < checkOK.length;  j++)
     if (ch == checkOK.charAt(j))
     break;
     if (j == checkOK.length)
      {
      	allValid = false;
      	break;
      }
     allNum += ch;
     }
    if (!allValid)
     {
        errorFields+="Tax ID should contain only digits \n";
    	document.agenttofirm.taxId.focus();
    	errorStatus = true;
     }

    if (theForm.taxId.value.length<9)
     {
	errorFields+="Tax ID should be 9 digits \n";
	document.agenttofirm.taxId.focus();
	errorStatus = true;
     }

 }//End of checkTaxID function

function checkFirmName(field)
 {
  var valid = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ ";

for (var i=0; i < field.length; i++)
 {
  temp = "" + field.substring(i, i+1);
  if (valid.indexOf(temp) == "-1")
    {
      errorFields+="Firm Name should contain alphabetic characters only \n";
	document.agenttofirm.firmName.focus();
      break;
    }
 }
 }//End of checkFirstName function

function checkLocName(field)
 {
  var valid = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ ";

for (var i=0; i < field.length; i++)
 {
  temp = "" + field.substring(i, i+1);
  if (valid.indexOf(temp) == "-1")
    {
      errorFields+="Location Name should contain alphabetic characters only \n";
      document.agenttofirm.locName.focus();
	break;
    }
 }
 }//End of checkFirstLast function

}//End of validateForm function
function clearForm(form) {

          document.agenttofirm.taxId.value="";
	  document.agenttofirm.firmName.value ="";
	  document.agenttofirm.locName.value ="";
	  document.agenttofirm.locName.value ="";
          document.agenttofirm.businessType.value =""
          document.agenttofirm.taxId.text ="";
	  document.agenttofirm.firmName.text ="";
	  document.agenttofirm.locName.text ="";
	  document.agenttofirm.locName.text ="";
          document.agenttofirm.businessType.text =""

}


text:
@implementation UIImage (Stretch)

+ (UIImage *)stretchImageName:(NSString *)name isTop:(BOOL)isTop{

    UIImage *image = [UIImage imageNamed:name];
    CGFloat left = image.size.width * 0.5;
    CGFloat top = image.size.height * 0.5;
    if (isTop) {
        [image resizableImageWithCapInsets:UIEdgeInsetsMake(top, 0, top, 0)];
        return image;
    }
    [image resizableImageWithCapInsets:UIEdgeInsetsMake(0, left , 0, left)];

    return image;
}

+ (id)resizeImageToMaxSize:(CGFloat)max sourcePath:(NSString*)path
{
    CGImageSourceRef imageSource = CGImageSourceCreateWithURL((CFURLRef)[NSURL fileURLWithPath:path], NULL);
    if (!imageSource)
        return nil;

    CFDictionaryRef options = (__bridge CFDictionaryRef)[NSDictionary dictionaryWithObjectsAndKeys:
                                                (id)kCFBooleanTrue, (id)kCGImageSourceCreateThumbnailWithTransform,
                                                (id)kCFBooleanTrue, (id)kCGImageSourceCreateThumbnailFromImageAlways,
                                                (id)[NSNumber numberWithFloat:max], (id)kCGImageSourceThumbnailMaxPixelSize,
                                                nil];
    CGImageRef imgRef = CGImageSourceCreateThumbnailAtIndex(imageSource, 0, options);

    UIImage* scaled = [UIImage imageWithCGImage:imgRef];

    CGImageRelease(imgRef);
    CFRelease(imageSource);

    return scaled;
}

- (UIImage *)resizeImageWithNewWidth:(CGFloat)width newHeigh:(CGFloat)height
{
    UIImage *image = nil;

    UIGraphicsBeginImageContextWithOptions(CGSizeMake(width, height), NO, [UIScreen mainScreen].scale);

    [self drawInRect:CGRectMake(0,0,width,height)];

    image = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    return image;
}
+ (UIImage *)compressImg:(UIImage *)img quality:(float)qly {
    NSData *data = UIImageJPEGRepresentation(img, qly);
    UIImage *image = [UIImage imageWithData:data];
    return image;
}
+ (UIImage *)blurrImage:(UIImage *)image scale:(float)scale {
    // Make sure that we have an image to work with
    if (!image)
        return nil;
    // Create context
    CIContext *context = [CIContext contextWithOptions:nil];
    // Create an image
    CIImage *cImage = [CIImage imageWithCGImage:image.CGImage];
    // Set up a Gaussian Blur filter
    CIFilter *blurFilter = [CIFilter filterWithName:@"CIGaussianBlur"];
    [blurFilter setValue:cImage forKey:kCIInputImageKey];
    // Get blurred image out
    CIImage *blurredImage = [blurFilter valueForKey:kCIOutputImageKey];
    // Set up vignette filter
    CIFilter *vignetteFilter = [CIFilter filterWithName:@"CIVignette"];
    [vignetteFilter setValue:blurredImage forKey:kCIInputImageKey];
    [vignetteFilter setValue:@(3.f) forKey:@"InputIntensity"];
    // get vignette & blurred image
    CIImage *vignetteImage = [vignetteFilter valueForKey:kCIOutputImageKey];
    //CGFloat scale = [[UIScreen mainScreen] scale];
    CGSize scaledSize = CGSizeMake(image.size.width * scale, image.size.height * scale);
    CGImageRef imageRef = [context createCGImage:vignetteImage fromRect:(CGRect){CGPointZero, scaledSize}];
    return [UIImage imageWithCGImage:imageRef scale:[[UIScreen mainScreen] scale] orientation:UIImageOrientationUp];
}
- (UIImage *)scaleToSize:(CGSize)scaleSize {
    // Create a graphics image context
    UIGraphicsBeginImageContext(scaleSize);
    // Tell the old image to draw in this new context, with the desired
    // new size
    [self drawInRect:CGRectMake(0,0,scaleSize.width,scaleSize.height)];
    // Get the new image from the context
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    // End the context
    UIGraphicsEndImageContext();
    // Return the new image.
    return newImage;
}
@end


text:
import { Component } from "react";
import { ComponentConstructor, Formatter, Parser, FieldValue, WrappedFieldProps } from "../index";

/**
 * These are the props to give to `Field`.
 * Any others will be passed through to your component.
 */
interface BaseFieldsProps {
    /**
     * An array of strings (or the pseudo-array fields provided by FieldArray),
     * in dot-and-bracket notation, corresponding to form values.
     * They may be as simple as 'firstName' or as complicated as
     * 'contact.billing.address[2].phones[1].areaCode'.
     */
    names: string[];

    /**
     * A Component or stateless function that will be given all the props necessary
     * to render the field inputs.
     */
    component?: ComponentConstructor<any>;

    /**
     * Formats the value from the Redux store to be displayed in the field input.
     * Common use cases are to format Numbers into currencies or Dates into a localized date format.
     *
     * format is called with the field value and name as arguments and should return the new formatted
     * value to be displayed in the field input.
     *
     * To respect React 15 input behavior there is defaultFormat = value => value == null ? '' : value
     * internally used. To disable that you can pass null as format prop.
     */
    format?: Formatter | null;

    /**
     * Don't use.
     */
    props?: any;

    /**
     * Parses the value given from the field input component to the type that you want stored in the Redux store.
     * Common use cases are to parse currencies into Numbers into currencies or localized date formats into Dates.
     *
     * parse is called with the field value and name as arguments and should return the new parsed value to be
     * stored in the Redux store.
     */
    parse?: Parser;

    /**
     * If true, the rendered component will be available with the getRenderedComponent() method.
     * Defaults to false. Cannot be used if your component is a stateless function component.
     */
    withRef?: boolean;
}

/**
 * Declare Fields as this interface to specify the generics.
 */
export interface GenericFields<T, FieldsCustomProps> extends Component<BaseFieldsProps & FieldsCustomProps, {}> {
    /**
     * true if the current value of any of the fields is different from the initialized value, false otherwise.
     */
    dirty: boolean;

    /**
     * The names prop that you passed in.
     */
    names: string[];

    /**
     * true if the all of the current values are the same as the initialized values, false otherwise.
     */
    pristine: boolean;

    /**
     * The current values of the fields. If they are nested, the values will duplicate the structure.
     * For example, if your names are [ 'name.first', 'name.last', 'email' ], the values will be
     * { name: { first: 'John', last: 'Smith' }, email: 'john@email.com' }
     */
    values: { [name: string]: FieldValue };

    getRenderedComponent(): Component<BaseFieldsProps & FieldsCustomProps, any>;
}

/**
 * The Fields Instance API.
 */
export class Fields extends Component<any, {}> implements GenericFields<any, any> {
    /**
     * true if the current value of any of the fields is different from the initialized value, false otherwise.
     */
    dirty: boolean;

    /**
     * The names prop that you passed in.
     */
    names: string[];

    /**
     * true if the all of the current values are the same as the initialized values, false otherwise.
     */
    pristine: boolean;

    /**
     * The current values of the fields. If they are nested, the values will duplicate the structure.
     * For example, if your names are [ 'name.first', 'name.last', 'email' ], the values will be
     * { name: { first: 'John', last: 'Smith' }, email: 'john@email.com' }
     */
    values: { [name: string]: FieldValue };

    getRenderedComponent(): Component<any, any>;
}

interface WrappedFieldsProps<S> {
    [name: string]: WrappedFieldsProps<S> & WrappedFieldProps<S>
}


text:
var React = require('react');
var ReactDOM = require('react-dom');

var ReactClass = React.createClass({
  render: function () {
    return React.createElement('h1', { className: 'header' }, 'React Component');
  }
});

var reactComponentElement = React.createElement(ReactClass);
var reactComponent = ReactDOM.render(reactComponentElement, document.getElementById('react-application'));


text:
namespace ui {
namespace test {

// Test API to access the internal state of the MaterialDesignController class.
// Creating an instance of this class and then destroying it preserves global
// state in MaterialDesignController class.
class MaterialDesignControllerTestAPI {
 public:
  explicit MaterialDesignControllerTestAPI(MaterialDesignController::Mode mode);
  ~MaterialDesignControllerTestAPI();

  // Force the given |value| for IsSecondaryUiMaterial() for the lifetime of the
  // test API.
  void SetSecondaryUiMaterial(bool value);

  // Wrapper functions for MaterialDesignController internal functions.
  static void Uninitialize();

 private:
  const MaterialDesignController::Mode previous_mode_;
  const bool previous_initialized_;
  const bool previous_include_secondary_ui_;

  DISALLOW_COPY_AND_ASSIGN(MaterialDesignControllerTestAPI);
};

}  // namespace test
}  // namespace ui

#endif  // UI_BASE_TEST_MATERIAL_DESIGN_CONTROLLER_TEST_API_H_


text:
<?php

use yii\helpers\Html;

/* @var $this yii\web\View */
/* @var $model backend\models\CmsRecipes */

$this->title = Yii::t('backend', 'Create Recipe');
$this->params['breadcrumbs'][] = ['label' => Yii::t('backend', 'Recipes Categories'), 'url' => ['cms-pages-categories/index']];
if (!empty($categoryModel->title)) {
    $this->params['breadcrumbs'][] = ['label' => $categoryModel->title, 'url' => ['cms-recipes-categories/view', 'category_id' => $categoryModel->id]];
}
$this->params['breadcrumbs'][] = $this->title;
?>

<?= Html::encode($this->title) ?>

    <?= $this->render('_form', [
        'model' => $model,
        'languages' => $languages,
        'languageDefault' => $languageDefault,
        'categoryModel' => $categoryModel,
    ]) ?>


text:
<?php

/**
 * Generated data provider for string cardType unit test
 */
return function(\Faker\Generator $faker){
    return [
        'string cardType'   => [
            \Aedart\Model\Traits\Strings\CardTypeTrait::class,
            \Aedart\Model\Contracts\Strings\CardTypeAware::class,
            $faker->word,
            $faker->word,
        ]
    ];
};


text:
namespace content {

static jlong Init(JNIEnv* env, jobject obj) {
  TracingControllerAndroid* profiler = new TracingControllerAndroid(env, obj);
  return reinterpret_cast<intptr_t>(profiler);
}

TracingControllerAndroid::TracingControllerAndroid(JNIEnv* env, jobject obj)
    : weak_java_object_(env, obj),
      weak_factory_(this) {}

TracingControllerAndroid::~TracingControllerAndroid() {}

void TracingControllerAndroid::Destroy(JNIEnv* env, jobject obj) {
  delete this;
}

bool TracingControllerAndroid::StartTracing(JNIEnv* env,
                                            jobject obj,
                                            jstring jcategories,
                                            jstring jtraceoptions) {
  std::string categories =
      base::android::ConvertJavaStringToUTF8(env, jcategories);
  base::trace_event::TraceOptions trace_options;
  trace_options.SetFromString(
      base::android::ConvertJavaStringToUTF8(env, jtraceoptions));

  // This log is required by adb_profile_chrome.py.
  LOG(WARNING) << "Logging performance trace to file";

  return TracingController::GetInstance()->EnableRecording(
      base::trace_event::CategoryFilter(categories),
      trace_options,
      TracingController::EnableRecordingDoneCallback());
}

void TracingControllerAndroid::StopTracing(JNIEnv* env,
                                           jobject obj,
                                           jstring jfilepath) {
  base::FilePath file_path(
      base::android::ConvertJavaStringToUTF8(env, jfilepath));
  if (!TracingController::GetInstance()->DisableRecording(
          TracingController::CreateFileSink(
              file_path,
              base::Bind(&TracingControllerAndroid::OnTracingStopped,
                         weak_factory_.GetWeakPtr())))) {
    LOG(ERROR) << "EndTracingAsync failed, forcing an immediate stop";
    OnTracingStopped();
  }
}

void TracingControllerAndroid::GenerateTracingFilePath(
    base::FilePath* file_path) {
  JNIEnv* env = base::android::AttachCurrentThread();
  ScopedJavaLocalRef<jstring> jfilename =
      Java_TracingControllerAndroid_generateTracingFilePath(env);
  *file_path = base::FilePath(
      base::android::ConvertJavaStringToUTF8(env, jfilename.obj()));
}

void TracingControllerAndroid::OnTracingStopped() {
  JNIEnv* env = base::android::AttachCurrentThread();
  base::android::ScopedJavaLocalRef<jobject> obj = weak_java_object_.get(env);
  if (obj.obj())
    Java_TracingControllerAndroid_onTracingStopped(env, obj.obj());
}

bool TracingControllerAndroid::GetKnownCategoryGroupsAsync(JNIEnv* env,
                                                           jobject obj) {
  if (!TracingController::GetInstance()->GetCategories(
          base::Bind(&TracingControllerAndroid::OnKnownCategoriesReceived,
                     weak_factory_.GetWeakPtr()))) {
    return false;
  }
  return true;
}

void TracingControllerAndroid::OnKnownCategoriesReceived(
    const std::set<std::string>& categories_received) {
  scoped_ptr<base::ListValue> category_list(new base::ListValue());
  for (std::set<std::string>::const_iterator it = categories_received.begin();
       it != categories_received.end();
       ++it) {
    category_list->AppendString(*it);
  }
  std::string received_category_list;
  base::JSONWriter::Write(category_list.get(), &received_category_list);

  // This log is required by adb_profile_chrome.py.
  LOG(WARNING) << "{\"traceCategoriesList\": " << received_category_list << "}";
}

static jstring GetDefaultCategories(JNIEnv* env, jobject obj) {
  return base::android::ConvertUTF8ToJavaString(
             env,
             base::trace_event::CategoryFilter::kDefaultCategoryFilterString)
      .Release();
}

bool RegisterTracingControllerAndroid(JNIEnv* env) {
  return RegisterNativesImpl(env);
}

}  // namespace content


text:
package be.axxes.bookrental.controllers;

import be.axxes.bookrental.dao.AuthorRepository;
import be.axxes.bookrental.dao.BookDescriptionRepository;
import be.axxes.bookrental.dao.TagRepository;
import be.axxes.bookrental.domain.Author;
import be.axxes.bookrental.domain.BookDescription;
import be.axxes.bookrental.domain.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.rest.webmvc.BasePathAwareController;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

@BasePathAwareController
public class BookDescriptionController {

    @Autowired
    private AuthorRepository authorRepository;

    @Autowired
    private TagRepository tagRepository;

    @Autowired
    private BookDescriptionRepository bookDescriptionRepository;

    @CrossOrigin(origins = "*")
    @RequestMapping(path = "/bookDescriptions", method = RequestMethod.POST)
    @ResponseStatus(HttpStatus.OK)
    public void createBookDescription(@RequestBody BookDescription bookDescription) {
        bookDescription.getAuthors().forEach(a -> {
                    final Author author = authorRepository.findAuthorByFirstnameAndLastname(a.getFirstname(), a.getLastname());
                    if (author == null) {
                        a.setId(authorRepository.save(a).getId());
                    } else {
                        a.setId(author.getId());
                    }
                }
        );

        bookDescription.getTags().forEach(a -> {
                    final Tag tag = tagRepository.findTagByName(a.getName());
                    if (tag == null) {
                        a.setId(tagRepository.save(a).getId());
                    } else {
                        a.setId(tag.getId());
                    }
                }
        );

        bookDescriptionRepository.save(bookDescription);
    }
}


text:
extern NSString * const RKSearchWordPrimaryKeyAttribute;

@interface RKSearchWord : NSManagedObject

@property (nonatomic, retain) NSString *word;
@property (nonatomic, retain) NSSet *searchableManagedObjects;

@end

@interface RKSearchWord (SearchableManagedObjectsAccessors)

- (void)addSearchableManagedObjectsObject:(RKSearchableManagedObject *)searchableManagedObject;
- (void)removeSearchableManagedObjectsObject:(RKSearchableManagedObject *)searchableManagedObject;
- (void)addSearchableManagedObjects:(NSSet *)searchableManagedObjects;
- (void)removeSearchableManagedObjects:(NSSet *)searchableManagedObjects;

@end


text:
#include "2d/CCParticleBatchNode.h"
#include "2d/CCGrid.h"
#include "2d/CCParticleSystem.h"
#include "base/ccUTF8.h"
#include "renderer/CCTextureCache.h"
#include "renderer/CCQuadCommand.h"
#include "renderer/CCRenderer.h"
#include "renderer/CCTextureAtlas.h"

NS_CC_BEGIN

ParticleBatchNode::ParticleBatchNode()
: _textureAtlas(nullptr)
{

}

ParticleBatchNode::~ParticleBatchNode()
{
    CC_SAFE_RELEASE(_textureAtlas);
}
/*
 * creation with Texture2D
 */

ParticleBatchNode* ParticleBatchNode::createWithTexture(Texture2D *tex, int capacity/* = kParticleDefaultCapacity*/)
{
    ParticleBatchNode * p = new (std::nothrow) ParticleBatchNode();
    if( p && p->initWithTexture(tex, capacity))
    {
        p->autorelease();
        return p;
    }
    CC_SAFE_DELETE(p);
    return nullptr;
}

/*
 * creation with File Image
 */

ParticleBatchNode* ParticleBatchNode::create(const std::string& imageFile, int capacity/* = kParticleDefaultCapacity*/)
{
    ParticleBatchNode * p = new (std::nothrow) ParticleBatchNode();
    if( p && p->initWithFile(imageFile, capacity))
    {
        p->autorelease();
        return p;
    }
    CC_SAFE_DELETE(p);
    return nullptr;
}

/*
 * init with Texture2D
 */
bool ParticleBatchNode::initWithTexture(Texture2D *tex, int capacity)
{
    _textureAtlas = new (std::nothrow) TextureAtlas();
    _textureAtlas->initWithTexture(tex, capacity);

    _children.reserve(capacity);

    _blendFunc = BlendFunc::ALPHA_PREMULTIPLIED;

    setGLProgramState(GLProgramState::getOrCreateWithGLProgramName(GLProgram::SHADER_NAME_POSITION_TEXTURE_COLOR));

    return true;
}

/*
 * init with FileImage
 */
bool ParticleBatchNode::initWithFile(const std::string& fileImage, int capacity)
{
    Texture2D *tex = Director::getInstance()->getTextureCache()->addImage(fileImage);
    return initWithTexture(tex, capacity);
}

// ParticleBatchNode - composition

// override visit.
// Don't call visit on it's children
void ParticleBatchNode::visit(Renderer *renderer, const Mat4 &parentTransform, uint32_t parentFlags)
{
    // CAREFUL:
    // This visit is almost identical to Node#visit
    // with the exception that it doesn't call visit on it's children
    //
    // The alternative is to have a void Sprite#visit, but
    // although this is less maintainable, is faster
    //
    if (!_visible || !isVisitableByVisitingCamera())
    {
        return;
    }

    uint32_t flags = processParentFlags(parentTransform, parentFlags);

    // IMPORTANT:
    // To ease the migration to v3.0, we still support the Mat4 stack,
    // but it is deprecated and your code should not rely on it
    Director* director = Director::getInstance();
    director->pushMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW);
    director->loadMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW, _modelViewTransform);

    draw(renderer, _modelViewTransform, flags);

    director->popMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW);
}

// override addChild:
void ParticleBatchNode::addChild(Node * aChild, int zOrder, int tag)
{
    CCASSERT( aChild != nullptr, "Argument must be non-nullptr");
    CCASSERT( dynamic_cast<ParticleSystem*>(aChild) != nullptr, "CCParticleBatchNode only supports QuadParticleSystems as children");
    ParticleSystem* child = static_cast<ParticleSystem*>(aChild);
    CCASSERT( child->getTexture()->getName() == _textureAtlas->getTexture()->getName(), "CCParticleSystem is not using the same texture id");

    addChildByTagOrName(child, zOrder, tag, "", true);
}

void ParticleBatchNode::addChild(Node * aChild, int zOrder, const std::string &name)
{
    CCASSERT( aChild != nullptr, "Argument must be non-nullptr");
    CCASSERT( dynamic_cast<ParticleSystem*>(aChild) != nullptr, "CCParticleBatchNode only supports QuadParticleSystems as children");
    ParticleSystem* child = static_cast<ParticleSystem*>(aChild);
    CCASSERT( child->getTexture()->getName() == _textureAtlas->getTexture()->getName(), "CCParticleSystem is not using the same texture id");

    addChildByTagOrName(child, zOrder, 0, name, false);
}

void ParticleBatchNode::addChildByTagOrName(ParticleSystem* child, int zOrder, int tag, const std::string &name, bool setTag)
{
    // If this is the 1st children, then copy blending function
    if (_children.empty())
    {
        setBlendFunc(child->getBlendFunc());
    }

    CCASSERT( _blendFunc.src  == child->getBlendFunc().src && _blendFunc.dst  == child->getBlendFunc().dst, "Can't add a ParticleSystem that uses a different blending function");

    //no lazy sorting, so don't call super addChild, call helper instead
    int pos = 0;
    if (setTag)
        pos = addChildHelper(child, zOrder, tag, "", true);
    else
        pos = addChildHelper(child, zOrder, 0, name, false);

    //get new atlasIndex
    int atlasIndex = 0;

    if (pos != 0)
    {
        ParticleSystem* p = static_cast<ParticleSystem*>(_children.at(pos-1));
        atlasIndex = p->getAtlasIndex() + p->getTotalParticles();
    }
    else
    {
        atlasIndex = 0;
    }

    insertChild(child, atlasIndex);

    // update quad info
    child->setBatchNode(this);
}

// don't use lazy sorting, reordering the particle systems quads afterwards would be too complex
// FIXME: research whether lazy sorting + freeing current quads and calloc a new block with size of capacity would be faster
// FIXME: or possibly using vertexZ for reordering, that would be fastest
// this helper is almost equivalent to Node's addChild, but doesn't make use of the lazy sorting
int ParticleBatchNode::addChildHelper(ParticleSystem* child, int z, int aTag, const std::string &name, bool setTag)
{
    CCASSERT( child != nullptr, "Argument must be non-nil");
    CCASSERT( child->getParent() == nullptr, "child already added. It can't be added again");

    _children.reserve(4);

    //don't use a lazy insert
    auto pos = searchNewPositionInChildrenForZ(z);

    _children.insert(pos, child);

    if (setTag)
        child->setTag(aTag);
    else
        child->setName(name);

    child->setLocalZOrder(z);

    child->setParent(this);

    if( _running )
    {
        child->onEnter();
        child->onEnterTransitionDidFinish();
    }
    return pos;
}

// Reorder will be done in this function, no "lazy" reorder to particles
void ParticleBatchNode::reorderChild(Node * aChild, int zOrder)
{
    CCASSERT( aChild != nullptr, "Child must be non-nullptr");
    CCASSERT( dynamic_cast<ParticleSystem*>(aChild) != nullptr, "CCParticleBatchNode only supports QuadParticleSystems as children");
    CCASSERT( _children.contains(aChild), "Child doesn't belong to batch" );

    ParticleSystem* child = static_cast<ParticleSystem*>(aChild);

    if( zOrder == child->getLocalZOrder() )
    {
        return;
    }

    // no reordering if only 1 child
    if (!_children.empty())
    {
        int newIndex = 0, oldIndex = 0;

        getCurrentIndex(&oldIndex, &newIndex, child, zOrder);

        if( oldIndex != newIndex )
        {

            // reorder _children->array
            child->retain();
            _children.erase(oldIndex);
            _children.insert(newIndex, child);
            child->release();

            // save old altasIndex
            int oldAtlasIndex = child->getAtlasIndex();

            // update atlas index
            updateAllAtlasIndexes();

            // Find new AtlasIndex
            int newAtlasIndex = 0;
            for( int i=0;i < _children.size();i++)
            {
                ParticleSystem* node = static_cast<ParticleSystem*>(_children.at(i));
                if( node == child )
                {
                    newAtlasIndex = child->getAtlasIndex();
                    break;
                }
            }

            // reorder textureAtlas quads
            _textureAtlas->moveQuadsFromIndex(oldAtlasIndex, child->getTotalParticles(), newAtlasIndex);

            child->updateWithNoTime();
        }
    }

    child->setLocalZOrder(zOrder);
}

void ParticleBatchNode::getCurrentIndex(int* oldIndex, int* newIndex, Node* child, int z)
{
    bool foundCurrentIdx = false;
    bool foundNewIdx = false;

    int  minusOne = 0;
    auto count = _children.size();

    for( int i=0; i < count; i++ )
    {
        Node* pNode = _children.at(i);

        // new index
        if( pNode->getLocalZOrder() > z &&  ! foundNewIdx )
        {
            *newIndex = i;
            foundNewIdx = true;

            if( foundCurrentIdx && foundNewIdx )
            {
                break;
            }
        }

        // current index
        if( child == pNode )
        {
            *oldIndex = i;
            foundCurrentIdx = true;

            if( ! foundNewIdx )
            {
                minusOne = -1;
            }

            if( foundCurrentIdx && foundNewIdx )
            {
                break;
            }
        }

    }

    if( ! foundNewIdx )
    {
        *newIndex = static_cast<int>(count);
    }

    *newIndex += minusOne;
}

int ParticleBatchNode::searchNewPositionInChildrenForZ(int z)
{
    auto count = _children.size();

    for( int i=0; i < count; i++ )
    {
        Node *child = _children.at(i);
        if (child->getLocalZOrder() > z)
        {
            return i;
        }
    }
    return static_cast<int>(count);
}

// override removeChild:
void  ParticleBatchNode::removeChild(Node* aChild, bool cleanup)
{
    // explicit nil handling
    if (aChild == nullptr)
        return;

    CCASSERT( dynamic_cast<ParticleSystem*>(aChild) != nullptr, "CCParticleBatchNode only supports QuadParticleSystems as children");
    CCASSERT(_children.contains(aChild), "CCParticleBatchNode doesn't contain the sprite. Can't remove it");

    ParticleSystem* child = static_cast<ParticleSystem*>(aChild);

    // remove child helper
    _textureAtlas->removeQuadsAtIndex(child->getAtlasIndex(), child->getTotalParticles());

    // after memmove of data, empty the quads at the end of array
    _textureAtlas->fillWithEmptyQuadsFromIndex(_textureAtlas->getTotalQuads(), child->getTotalParticles());

    // particle could be reused for self rendering
    child->setBatchNode(nullptr);
    Node::removeChild(child, cleanup);

    updateAllAtlasIndexes();
}

void ParticleBatchNode::removeChildAtIndex(int index, bool doCleanup)
{
    removeChild(_children.at(index), doCleanup);
}

void ParticleBatchNode::removeAllChildrenWithCleanup(bool doCleanup)
{
    for(const auto &child : _children)
        static_cast<ParticleSystem*>(child)->setBatchNode(nullptr);

    Node::removeAllChildrenWithCleanup(doCleanup);

    _textureAtlas->removeAllQuads();
}

void ParticleBatchNode::draw(Renderer *renderer, const Mat4 &transform, uint32_t flags)
{
    CC_PROFILER_START("CCParticleBatchNode - draw");

    if( _textureAtlas->getTotalQuads() == 0 )
    {
        return;
    }
    _batchCommand.init(_globalZOrder, getGLProgram(), _blendFunc, _textureAtlas, _modelViewTransform, flags);
    renderer->addCommand(&_batchCommand);
    CC_PROFILER_STOP("CCParticleBatchNode - draw");
}

void ParticleBatchNode::increaseAtlasCapacityTo(ssize_t quantity)
{
    CCLOG("cocos2d: ParticleBatchNode: resizing TextureAtlas capacity from [%lu] to [%lu].",
          (long)_textureAtlas->getCapacity(),
          (long)quantity);

    if( ! _textureAtlas->resizeCapacity(quantity) ) {
        // serious problems
        CCLOGWARN("cocos2d: WARNING: Not enough memory to resize the atlas");
        CCASSERT(false,"XXX: ParticleBatchNode #increaseAtlasCapacity SHALL handle this assert");
    }
}

//sets a 0'd quad into the quads array
void ParticleBatchNode::disableParticle(int particleIndex)
{
    V3F_C4B_T2F_Quad* quad = &((_textureAtlas->getQuads())[particleIndex]);
    quad->br.vertices.x = quad->br.vertices.y = quad->tr.vertices.x = quad->tr.vertices.y = quad->tl.vertices.x = quad->tl.vertices.y = quad->bl.vertices.x = quad->bl.vertices.y = 0.0f;
}

// ParticleBatchNode - add / remove / reorder helper methods

// add child helper
void ParticleBatchNode::insertChild(ParticleSystem* system, int index)
{
    system->setAtlasIndex(index);

    if(_textureAtlas->getTotalQuads() + system->getTotalParticles() > _textureAtlas->getCapacity())
    {
        increaseAtlasCapacityTo(_textureAtlas->getTotalQuads() + system->getTotalParticles());

        // after a realloc empty quads of textureAtlas can be filled with gibberish (realloc doesn't perform calloc), insert empty quads to prevent it
        _textureAtlas->fillWithEmptyQuadsFromIndex(_textureAtlas->getCapacity() - system->getTotalParticles(), system->getTotalParticles());
    }

    // make room for quads, not necessary for last child
    if (system->getAtlasIndex() + system->getTotalParticles() != _textureAtlas->getTotalQuads())
    {
        _textureAtlas->moveQuadsFromIndex(index, index+system->getTotalParticles());
    }

    // increase totalParticles here for new particles, update method of particle-system will fill the quads
    _textureAtlas->increaseTotalQuadsWith(system->getTotalParticles());

    updateAllAtlasIndexes();
}

//rebuild atlas indexes
void ParticleBatchNode::updateAllAtlasIndexes()
{
    int index = 0;

    for(const auto &child : _children) {
        ParticleSystem* partiSys = static_cast<ParticleSystem*>(child);
        partiSys->setAtlasIndex(index);
        index += partiSys->getTotalParticles();
    }
}

// ParticleBatchNode - CocosNodeTexture protocol

void ParticleBatchNode::updateBlendFunc()
{
    if( ! _textureAtlas->getTexture()->hasPremultipliedAlpha())
        _blendFunc = BlendFunc::ALPHA_NON_PREMULTIPLIED;
}

void ParticleBatchNode::setTexture(Texture2D* texture)
{
    _textureAtlas->setTexture(texture);

    // If the new texture has No premultiplied alpha, AND the blendFunc hasn't been changed, then update it
    if( texture && ! texture->hasPremultipliedAlpha() && ( _blendFunc.src == CC_BLEND_SRC && _blendFunc.dst == CC_BLEND_DST ) )
    {
        _blendFunc = BlendFunc::ALPHA_NON_PREMULTIPLIED;
    }
}

Texture2D* ParticleBatchNode::getTexture() const
{
    return _textureAtlas->getTexture();
}

void ParticleBatchNode::setBlendFunc(const BlendFunc &blendFunc)
{
    _blendFunc = blendFunc;
}
// returns the blending function used for the texture
const BlendFunc& ParticleBatchNode::getBlendFunc() const
{
    return _blendFunc;
}

NS_CC_END


text:
<!DOCTYPE html>

	<title>Display a GeoTiff on OL3</title>
	<meta name="viewport" content="width=device-width">
	<meta charset="UTF-8" />
	<title>Display a GeoTiff on OL3</title>

	<link rel="stylesheet" href="css/ol.css" type="text/css">

<form name="tiff-parser" method="post" enctype="multipart/form-data" style="margin: 2% auto auto; ">
<input type="file" name="tiff-file" id="tiff-file" accept="image/tiff" required onchange="loadFile();" />
<input type="checkbox" name="MixMaxCb" id="MixMaxCb" value="MixMax">
Min:<input type="number" id="MinValueOfMinMax" name="min" value="0">
Max:<input type="number" id="MaxValueOfMinMax" name="max" value="1000">
</form>


text:
package net.oschina.app.improve.user.adapter;

import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.model.GlideUrl;
import com.bumptech.glide.load.model.LazyHeaders;
import com.bumptech.glide.load.resource.drawable.GlideDrawable;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;

import net.oschina.app.AppContext;
import net.oschina.app.R;
import net.oschina.app.api.ApiHttpClient;
import net.oschina.app.improve.base.adapter.BaseGeneralRecyclerAdapter;
import net.oschina.app.improve.bean.Message;
import net.oschina.app.util.StringUtils;
import net.oschina.app.widget.TweetTextView;
import net.qiujuer.genius.ui.widget.Loading;

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

/**
 * Created by huanghaibin_dev
 * on 2016/8/18.
 */
public class UserSendMessageAdapter extends BaseGeneralRecyclerAdapter<Message> {
    private static final int SENDER = 1;
    private static final int SENDER_PICTURE = 2;
    private static final int RECEIVER = 3;
    private static final int RECEIVER_PICTURE = 4;
    private long authorId;

    public UserSendMessageAdapter(Callback callback) {
        super(callback, NEITHER);
        authorId = AppContext.getInstance().getLoginId();
    }

    @Override
    public int getItemViewType(int position) {
        Message item = getItem(position);
        if (item.getSender().getId() == authorId) {//如果是个人发送的私信
            if (Message.TYPE_IMAGE == item.getType())
                return SENDER_PICTURE;
            return SENDER;
        } else {
            if (Message.TYPE_IMAGE == item.getType())
                return RECEIVER_PICTURE;
            return RECEIVER;
        }
    }

    public ImageView getTargetImageView(int position, RecyclerView recyclerView) {
        RecyclerView.ViewHolder holder = recyclerView.findViewHolderForAdapterPosition(position);
        if (holder != null) {
            if (holder instanceof SenderPictureViewHolder)
                return ((SenderPictureViewHolder) holder).iv_sender_picture;
            if (holder instanceof ReceiverPictureViewHolder)
                return ((ReceiverPictureViewHolder) holder).iv_receiver_picture;
        }
        return null;
    }

    @Override
    protected RecyclerView.ViewHolder onCreateDefaultViewHolder(ViewGroup parent, int type) {
        if (type == SENDER)
            return new SenderViewHolder(mInflater.inflate(R.layout.item_list_user_send_message, parent, false));
        else if (type == SENDER_PICTURE)
            return new SenderPictureViewHolder(mInflater.inflate(R.layout.item_list_user_send_message_picture, parent, false));
        else if (type == RECEIVER)
            return new ReceiverViewHolder(mInflater.inflate(R.layout.item_list_receiver_message, parent, false));
        else
            return new ReceiverPictureViewHolder(mInflater.inflate(R.layout.item_list_receiver_message_picture, parent, false));
    }

    @Override
    protected void onBindDefaultViewHolder(RecyclerView.ViewHolder holder, final Message item, int position) {
        Message preMessage = position != 0 ? getItem(position - 1) : null;
        switch (getItemViewType(position)) {
            case SENDER:
                SenderViewHolder senderViewHolder = (SenderViewHolder) holder;
                parseAtUserContent(senderViewHolder.tv_sender, item.getContent());
                formatTime(preMessage, item, senderViewHolder.tv_send_time);
                break;
            case SENDER_PICTURE:
                final SenderPictureViewHolder senderPictureViewHolder = (SenderPictureViewHolder) holder;
                if (item.getId() == 0) {
                    mCallBack.getImgLoader()
                            .load(item.getResource())
                            .diskCacheStrategy(DiskCacheStrategy.ALL)
                            .error(R.mipmap.ic_split_graph)
                            .into(senderPictureViewHolder.iv_sender_picture);
                    senderPictureViewHolder.loading.setVisibility(View.VISIBLE);
                    senderPictureViewHolder.loading.start();
                    senderPictureViewHolder.iv_resend.setVisibility(View.INVISIBLE);
                } else if (item.getId() == -1) {
                    mCallBack.getImgLoader()
                            .load(item.getResource())
                            .diskCacheStrategy(DiskCacheStrategy.ALL)
                            .error(R.mipmap.ic_split_graph)
                            .into(senderPictureViewHolder.iv_sender_picture);
                    senderPictureViewHolder.loading.setVisibility(View.GONE);
                    senderPictureViewHolder.loading.stop();
                    senderPictureViewHolder.iv_resend.setVisibility(View.VISIBLE);
                } else {
                    senderPictureViewHolder.loading.setVisibility(View.VISIBLE);
                    senderPictureViewHolder.loading.start();
                    senderPictureViewHolder.iv_resend.setVisibility(View.INVISIBLE);
                    Glide.clear(senderPictureViewHolder.iv_sender_picture);
                    mCallBack.getImgLoader()
                            .load(getGlideUrl(item.getResource()))
                            .listener(new RequestListener<GlideUrl, GlideDrawable>() {
                                @Override
                                public boolean onException(Exception e, GlideUrl model, Target<GlideDrawable> target, boolean isFirstResource) {
                                    senderPictureViewHolder.loading.setVisibility(View.GONE);
                                    senderPictureViewHolder.loading.stop();
                                    return false;
                                }

                                @Override
                                public boolean onResourceReady(GlideDrawable resource, GlideUrl model, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
                                    senderPictureViewHolder.loading.setVisibility(View.GONE);
                                    senderPictureViewHolder.loading.stop();
                                    return false;
                                }
                            })
                            .placeholder(R.color.list_divider_color)
                            .error(R.mipmap.ic_split_graph)
                            .into(senderPictureViewHolder.iv_sender_picture);

                }
                formatTime(preMessage, item, senderPictureViewHolder.tv_send_time);
                break;
            case RECEIVER:
                ReceiverViewHolder receiverViewHolder = (ReceiverViewHolder) holder;
                parseAtUserContent(receiverViewHolder.tv_receiver, item.getContent());
                formatTime(preMessage, item, receiverViewHolder.tv_send_time);
                break;
            case RECEIVER_PICTURE:
                final ReceiverPictureViewHolder receiverPictureViewHolder = (ReceiverPictureViewHolder) holder;
                receiverPictureViewHolder.loading.setVisibility(View.VISIBLE);
                receiverPictureViewHolder.loading.start();
                mCallBack.getImgLoader()
                        .load(getGlideUrl(item.getResource()))
                        .listener(new RequestListener<GlideUrl, GlideDrawable>() {
                            @Override
                            public boolean onException(Exception e, GlideUrl model, Target<GlideDrawable> target, boolean isFirstResource) {
                                receiverPictureViewHolder.loading.setVisibility(View.GONE);
                                receiverPictureViewHolder.loading.stop();
                                return false;
                            }

                            @Override
                            public boolean onResourceReady(GlideDrawable resource, GlideUrl model, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
                                receiverPictureViewHolder.loading.setVisibility(View.GONE);
                                receiverPictureViewHolder.loading.stop();
                                return false;
                            }
                        })
                        .placeholder(R.color.list_divider_color)
                        .error(R.mipmap.ic_split_graph)
                        .into(receiverPictureViewHolder.iv_receiver_picture);
                formatTime(preMessage, item, receiverPictureViewHolder.tv_send_time);
                break;
        }
    }

    public GlideUrl getGlideUrl(String url) {
        return new GlideUrl(url, new LazyHeaders.Builder().addHeader("Cookie", ApiHttpClient.getCookie(AppContext.getInstance())).build());
    }

    private void formatTime(Message preMessage, Message item, TextView tv_time) {
        tv_time.setVisibility(View.GONE);
        if (preMessage == null) {
            formatTime(tv_time, item.getPubDate());
            tv_time.setVisibility(View.VISIBLE);
        } else {
            if (checkTime(preMessage.getPubDate(), item.getPubDate())) {
                formatTime(tv_time, item.getPubDate());
                tv_time.setVisibility(View.VISIBLE);
            }
        }
    }

    private boolean checkTime(String firstTime, String secondTime) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        try {
            long first = format.parse(firstTime).getTime();
            long second = format.parse(secondTime).getTime();
            return second - first > 300000;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    private String formatWeek(Date date) {
        SimpleDateFormat format = new SimpleDateFormat("EEEE");
        return format.format(date);
    }

    private String formatDate(Date date) {
        SimpleDateFormat format = new SimpleDateFormat("MM月dd日");
        return format.format(date);
    }

    private void formatTime(TextView tv_time, String time) {
        if (TextUtils.isEmpty(time)) return;
        SimpleDateFormat timeFormat = new SimpleDateFormat("hh:mm");
        Date date = StringUtils.toDate(time);
        tv_time.setText(formatWeek(date) + ", " + formatDate(date) + ", " + timeFormat.format(date));
    }

    /**
     * 倒序
     *
     * @param items items
     */
    @Override
    public void addAll(List<Message> items) {
        if (items != null) {
            mItems.addAll(0, items);
            notifyDataSetChanged();
        }

    }

    private static class SenderViewHolder extends RecyclerView.ViewHolder {
        TweetTextView tv_sender;
        TextView tv_send_time;

        public SenderViewHolder(View itemView) {
            super(itemView);
            tv_sender = (TweetTextView) itemView.findViewById(R.id.tv_sender);
            tv_send_time = (TextView) itemView.findViewById(R.id.tv_send_time);
        }
    }

    private static class SenderPictureViewHolder extends RecyclerView.ViewHolder {
        ImageView iv_sender_picture, iv_resend;
        TextView tv_send_time;
        Loading loading;

        public SenderPictureViewHolder(View itemView) {
            super(itemView);
            iv_sender_picture = (ImageView) itemView.findViewById(R.id.iv_sender_picture);
            iv_resend = (ImageView) itemView.findViewById(R.id.iv_resend);
            tv_send_time = (TextView) itemView.findViewById(R.id.tv_send_time);
            loading = (Loading) itemView.findViewById(R.id.loading);
        }
    }

    private static class ReceiverViewHolder extends RecyclerView.ViewHolder {
        TweetTextView tv_receiver;
        TextView tv_send_time;

        public ReceiverViewHolder(View itemView) {
            super(itemView);
            tv_receiver = (TweetTextView) itemView.findViewById(R.id.tv_receiver);
            tv_send_time = (TextView) itemView.findViewById(R.id.tv_send_time);

        }
    }

    private static class ReceiverPictureViewHolder extends RecyclerView.ViewHolder {
        ImageView iv_receiver_picture;
        TextView tv_send_time;
        Loading loading;

        public ReceiverPictureViewHolder(View itemView) {
            super(itemView);
            iv_receiver_picture = (ImageView) itemView.findViewById(R.id.iv_receiver_picture);
            tv_send_time = (TextView) itemView.findViewById(R.id.tv_send_time);
            loading = (Loading) itemView.findViewById(R.id.loading);
        }
    }
}


text:
{{--
 * @author      Archie Disono (webmonsph@gmail.com)
 * @link        https://github.com/disono/Laravel-Template
 * @license     https://github.com/disono/Laravel-Template/blob/master/LICENSE
 * @copyright   Webmons Development Studio
--}}

@extends('admin.layouts.master')

@section('content')

{{ $view_title }}

                        @include('admin.settings.menu')

                        <form action="{{ route('admin.role.update') }}" method="post"
                              v-on:submit.prevent="onFormUpload">
                            {{ csrf_field() }}
                            <input type="hidden" value="{{ $role->id }}" name="id">

                                Name *

                                <input id="name" type="text"
                                       class="form-control{{ hasInputError($errors, 'name') }}"
                                       name="name" value="{{ old('name', $role->name) }}" data-validate="required">

                                @if ($errors->has('name'))

{{ $errors->first('name') }}

                                @endif

                                Slug *

                                <input id="slug" type="text"
                                       class="form-control{{ hasInputError($errors, 'slug') }}"
                                       name="slug" value="{{ old('slug', $role->slug) }}" data-validate="required">

                                @if ($errors->has('slug'))

{{ $errors->first('slug') }}

                                @endif

                                Description

                                <input id="description" type="text"
                                       class="form-control{{ hasInputError($errors, 'description') }}"
                                       name="description" value="{{ old('description', $role->description) }}">

                                @if ($errors->has('description'))

{{ $errors->first('description') }}

                                @endif

                            <button type="submit" class="btn btn-raised btn-primary">Submit</button>
                        </form>

@endsection


text:
@interface SASUploadObject()

@property (assign, nonatomic) BOOL deviceHasBeenSet;

@end

@implementation SASUploadObject

@synthesize timeStamp;
@synthesize associatedDevice = _associatedDevice;
@synthesize coordinates;
@synthesize image = _image;
@synthesize caption;
@synthesize identifier;
@synthesize UUID;

- (instancetype)initWithImage:(UIImage *)imageToUpload {

    if (self = [super init]) {
        // @Discussion:
        // See UIImage+SASNormalizeImage.h
        // for reason on why we need to normalize
        // the image property.
        _image = [imageToUpload normalizedImage];

        _associatedDevice = [[SASDevice alloc] init];

        // This will be set to All as we need to check
        // if its been set. If .type is not All
        // then we know it has been set.
        _associatedDevice.type = All;
    }
    return self;
}

#pragma mark SASVerifiedUploadObject Protocol
- (BOOL)captionHasBeenSet {

    if ([self.caption isEqualToString:@""] ||
        [self.caption isEqualToString:@"Add Location Information"] ||
        self.caption == nil) {

        return NO;

    } else {
        return YES;
    }
}

- (BOOL)deviceHasBeenSet {
    if (self.associatedDevice.type != All) {
        return YES;
    } else {
        return NO;
    }
}

@end


text:
import { Component, OnInit } from '@angular/core';
import { InventoryService } from 'api-client';
import { Router, ActivatedRoute } from '@angular/router';
import { FormGroup, FormControl } from '@angular/forms';

@Component({
  selector: 'app-location-editor',
  templateUrl: './location-editor.component.html',
  styleUrls: ['./location-editor.component.scss']
})
export class LocationEditorComponent implements OnInit {
  isNew = true;
  loading = false;
  submitting = false;
  locationId: string | null = null;

  locationForm = new FormGroup({
    name: new FormControl(''),
    warehouse: new FormControl(''),
    id: new FormControl(''),
  });

  constructor(
    private route: ActivatedRoute,
    private router: Router,
    private inventoryService: InventoryService,
  ) { }

  ngOnInit() {
    this.route.paramMap.subscribe(pmap => {
      this.locationId = pmap.get('id');
      if (this.locationId) {
        this.isNew = false;
        this.loading = true;
        this.inventoryService.getLocation(this.locationId).subscribe(location => {
          this.locationForm.setValue(
            Object.assign({
              name: '',
              warehouse: '',
            }, location)
          );
          this.loading = false;
        }, () => {
          this.loading = false;
        });
      }
    });
  }

  onSubmit() {
    const location = this.locationForm.value;
    this.submitting = true;
    if (this.isNew) {
      this.inventoryService.newLocation(location).subscribe((newLocation) => {
        this.router.navigate(['/locations', newLocation.id]);
        this.submitting = false;
      }, () => {
        this.submitting = false;
      });
    } else {
      this.inventoryService.updateLocation(location.id, location).subscribe((newLocation) => {
        this.router.navigate(['/locations', newLocation.id]);
        this.submitting = false;
      }, () => {
        this.submitting = false;
      });
    }
  }

  onCancel() {
    if (this.isNew) {
      this.router.navigate(['/locations']);
    } else {
      this.router.navigate(['/locations', this.locationId]);
    }
  }

}


text:
require 'spec_helper'

describe Initiative do
  it "should require a name" do
    Initiative.new(:name => "").should_not be_valid
  end
end


text:
Design Patterns
=====

## Table of contents

- [Quick start](#quick-start)
- [Documentation](#documentation)
- [Next step](#next-step)
- [Creator](#creator)
- [Copyright and license](#copyright-and-license)

## Quick start

- Download the last release
- Run the each console App from Visual Studio with F5 or Debug.

## Documentation

These are just some design patterns. I have tried to illustrate them with real life examples like :

  - **Builder** : a waiter gives orders to the cook for making a burger
  - **Proxy** : adds a controller of wind speed to up or down the rolling shutters
  - **Singleton thread-safe** : saves content into a file in a multithreaded environment
  - **State** : illustrates the skill level who changes when you kill enemies on Counter Strike
  - **Strategy** : the behaviour of the backup service is changing depending on the strategy used
  - ...

You can see the links below to learn more about design patterns :

- [Builder](http://en.wikipedia.org/wiki/Builder_pattern)
- [Chain of Responsability](http://en.wikipedia.org/wiki/Chain-of-responsibility_pattern)
- [Composite](http://en.wikipedia.org/wiki/Composite_pattern)
- [Command](https://en.wikipedia.org/wiki/Command_pattern)
- [Decorator](http://en.wikipedia.org/wiki/Decorator_pattern)
- [Facade](https://en.wikipedia.org/wiki/Facade_pattern)
- [Factory](https://en.wikipedia.org/wiki/Factory_method_pattern)
- [Observer](http://en.wikipedia.org/wiki/Observer_pattern)
- [Proxy](http://en.wikipedia.org/wiki/Proxy_pattern)
- [Singleton](http://en.wikipedia.org/wiki/Singleton_pattern)
- [State](http://en.wikipedia.org/wiki/State_pattern)
- [Strategy](http://en.wikipedia.org/wiki/Strategy_pattern)
- [Template Method](http://en.wikipedia.org/wiki/Template_method_pattern)

## Next step

- Add all remaining design patterns (when I will have some time)

## Creator

Lionel Repellin

## Copyright and license

Code released under [the MIT license](https://github.com/twbs/bootstrap/blob/master/LICENSE).


text:
TESTING = True

MASTER_DATABASE_URI = 'postgresql://localhost/postgres'
TEST_DATABASE_NAME = 'navigator_test'

SQLALCHEMY_DATABASE_URI = 'postgresql://localhost/{}'.format(TEST_DATABASE_NAME)
SQLALCHEMY_POOL_SIZE = 1


text:
ALTER TABLE "${schema}"."${table}" DROP COLUMN "version_rank";
ALTER TABLE "${schema}"."${table}" DROP CONSTRAINT "${table}_pk";
ALTER TABLE "${schema}"."${table}" ADD COLUMN "version_temp" VARCHAR(50) NULL;
UPDATE "${schema}"."${table}" SET "version_temp"="version";
ALTER TABLE "${schema}"."${table}" DROP COLUMN "version";
ALTER TABLE "${schema}"."${table}" ADD COLUMN "version" VARCHAR(50) NULL;
UPDATE "${schema}"."${table}" SET "version"="version_temp";
ALTER TABLE "${schema}"."${table}" DROP COLUMN "version_temp";
ALTER TABLE "${schema}"."${table}" ADD CONSTRAINT "${table}_pk" PRIMARY KEY ("installed_rank");
UPDATE "${schema}"."${table}" SET "type"='BASELINE' WHERE "type"='INIT';


text:
<?php

namespace Kora\DataProvider\OperatorDefinition\Filter;

use Kora\DataProvider\OperatorDefinition\FilterOperatorDefinitionInterface;

/**
 * Class AbstractValueDefinition
 * @author Paweł Gierlasiński <gierlasinski.pawel@gmail.com>
 */
abstract class AbstractValueDefinition extends AbstractNameDefinition
{
	/**
	 * @var bool
	 */
	protected $allowEmpty;

	/**
	 * @var int
	 */
	protected $filterType;

	/**
	 * @var mixed
	 */
	protected $value;

	/**
	 * AbstractValueDefinition constructor.
	 * @param string   $name
	 * @param int|null $filterType
	 * @param bool     $allowUseEmpty
	 */
	public function __construct(string $name, bool $allowUseEmpty = false, $filterType = FILTER_SANITIZE_STRING)
	{
		parent::__construct($name);
		$this->allowEmpty = $allowUseEmpty;
		$this->filterType = $filterType;
	}

	/**
	 * Init value
	 * @param array $params
	 */
	public function initData(array $params)
	{
		if (!empty($params[$this->name])) {
			$this->value = $this->filterType
				? filter_var($params[$this->name], $this->filterType) : $params[$this->name];
		}
	}

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

	/**
	 * @return array|null
	 */
	public function getParamValue()
	{
		return $this->shouldApply() ? [$this->name => $this->value] : null;
	}

	/**
	 * @return bool
	 */
	public function allowUseEmpty(): bool
	{
		return $this->allowEmpty;
	}

	/**
	 * @return bool
	 */
	public function shouldApply(): bool
	{
		return $this->allowEmpty || !empty($this->value);
	}
}


text:
package org.apache.tools.ant.util;

import java.io.File;
import junit.framework.TestCase;

/**
 * @since Ant 1.6
 */
public class LoaderUtilsTest extends TestCase {

    public LoaderUtilsTest(String name) {
        super(name);
    }

    public void testGetXyzSource() {
        File f1 = LoaderUtils.getClassSource(LoaderUtils.class);
        assertNotNull(f1);

        File f2 = LoaderUtils.getResourceSource(null,
                                                "org/apache/tools/ant/taskdefs/defaults.properties");
        assertNotNull(f2);

        assertEquals(f1.getAbsolutePath(), f2.getAbsolutePath());
    }

}


text:
class CoderDojoSakuraCLI
  require './ruby_scripts/sakura_server_user_agent.rb'
  require 'csv'
  INSTANCE_CSV = "servers.csv".freeze
  RESULT_INSTANCE_CSV = "instances.csv".freeze

  #jsではproductionの方を特別にしていたが、たぶんprodocutionの方を頻繁に叩くので...
  def initialize(argv)
    if /sandbox/ =~ argv[0]
      @isSandbox = true
    end
  end

  def update_startup_scripts
    startup_file_name = "./startup-scripts/112900928939"
    text = File.open(startup_file_name,'r').read
    @ssua.update_startup_scripts(text)
  end

  def run()
    request_params = perform_init_params()
    @ssua = SakuraServerUserAgent.new(request_params)

    #update_startup_scripts() unless @isSandbox

    @ssua.archive_id = initial_archive_id()

    #serverのリストを取得
    puts 'Get a list of existing servers.'
    sakura_servers = (@ssua.get_servers())['Servers']
    sakura_server_names = []

    sakura_servers.each do |s|
      sakura_server_names.push(s['Name'])
    end

    CSV.read(INSTANCE_CSV,headers: true).each do |line|
      next if sakura_server_names.include?(line['name']) #すでに登録されているものは飛ばす
      @ssua.create(name:line['name'], description:line['description'],pubkey:line['pubkey'], tag:line['branch'])
    end

    result_csv_elements = []
    result_sakura_servers = (@ssua.get_servers())['Servers']
    result_sakura_servers.each do |s|
      result_csv_elements.push([s['Name'], s['Interfaces'].first['IPAddress'], s['Description']])
    end

    CSV.open(RESULT_INSTANCE_CSV, 'wb') do |csv|
      csv << ['Name', 'IP Address', 'Description']
      result_csv_elements.map{ |r| csv << r }
    end

    puts "the #{RESULT_INSTANCE_CSV} was saved!"
  end

  private

  def perform_init_params
    if @isSandbox
      {
       zone: "29001", # サンドボックス
       zone_id: "tk1v",
       packet_filter_id: '112900927419', # See https://secure.sakura.ad.jp/cloud/iaas/#!/network/packetfilter/.
      }
    else
      {
       zone: "31002", # 石狩第二
       zone_id: "is1b", # 石狩第二
       packet_filter_id: '112900922505', # See https://secure.sakura.ad.jp/cloud/iaas/#!/network/packetfilter/.
      }
    end
  end

  def initial_archive_id
    archiveid = nil
    archives = @ssua.get_archives()
    puts "List of Archives:"
    archives['Archives'].each do |arch|
      # MEMO: Ubuntuの対象バージョンの提供が終了した場合は、バージョンを上げる
      puts "- Name: #{arch['Name']}"
      if /ubuntu/i =~ arch['Name'] && /20\.04/i =~ arch['Name'] then
        archiveid = arch['ID']
      end
    end

    if archiveid then
      puts "Archive ID: #{archiveid}"
    else
      puts "Can't get archive id"
      exit
    end
    archiveid
  end
end

CoderDojoSakuraCLI.new(ARGV).run()


text:
using System;
using Sparrow.Domain.Models;

namespace Sparrow.Domain.Events
{
    public class OfferLostEvent
    {
        public Offer Offer { get; set; }
    }
}


text:
.fileuploader {
    background: #1e1e1e;
}

.fileuploader .upload-label {
    background-color: #292929 !important;
}

.fileuploader .upload-label i {
    background: #ffffff !important;
    color: #1e1e1e !important;
}

.fileuploader.active {
    background: #1e1e1e !important;
}

.fileuploader.active .upload-label {
    color: #fff !important;
}

.preview-container {
    background-color: #1e1e1e;
}

.preview-container .previews .zdrop-info .preview-icon {
    color: #1e1e1e !important;
}

.preview-container .header {
    background-color: #1e1e1e !important;
}

.preview-container .previews .zdrop-info .preview-icon {
    background: #393939;
}

.preview-container .previews .collection-item {
    border-bottom: 1px solid #393939;
}

.preview-container .previews .zdrop-info .preview-icon {
    color: #ffffff !important;
}


text:
package trello

//Auth type to hold authentication data for trello API
type Auth struct {
	Key   string
	Token string
}

type trelloData struct {
	List struct {
		Id   string
		Name string
	} `json:"list"`
	Board struct {
		Id        string
		Name      string
		ShortLink string
	} `json:"board"`
	Card struct {
		Id        string
		Name      string
		ShortLink string
		IdShort   int
	} `json:"card"`
	Text string `json:"text"`
}

type trelloAction struct {
	Id            string
	Data          *trelloData
	MemberCreator *trelloMemberCreator
}

type trelloMemberCreator struct {
	Id       string
	FullName string
	Username string
}

type trelloCard struct {
	IdF               string `json:"id"`
	DateLastActivityF string `json:"dateLastActivity"`
	DescF             string `json:"desc"`
	IdBoardF          string `json:"idBoard"`
	IdListF           string `json:"idList"`
	NameF             string `json:"name"`
	ShortUrlF         string `json:"shortUrl"`
}

//Comment represents a minimal Trello Action of type comment
type Comment interface {
	Text() string
	Author() string
}

func (a trelloAction) Author() string {
	if a.MemberCreator == nil {
		return ""
	} else {
		return a.MemberCreator.FullName
	}
}

func (a trelloAction) Text() string {
	if a.Data == nil {
		return ""
	} else {
		return a.Data.Text
	}
}

//Card represents a minimal Trello Card
type Card interface {
	Id() string
	DateLastActivity() string
	IdBoard() string
	IdList() string
	Name() string
	Desc() string
	ShortUrl() string
}

func (i trelloCard) Id() string {
	return i.IdF
}

func (i trelloCard) IdList() string {
	return i.IdListF
}

func (i trelloCard) Name() string {
	return i.NameF
}

func (i trelloCard) Desc() string {
	return i.DescF
}

func (i trelloCard) IdBoard() string {
	return i.IdBoardF
}
func (i trelloCard) DateLastActivity() string {
	return i.DateLastActivityF
}

func (i trelloCard) ShortUrl() string {
	return i.ShortUrlF
}

//Board represents a minimal Trello Board
type Board interface {
	Name() string
	Id() string
}

type trelloBoard struct {
	IdF   string `json:"id"`
	NameF string `json:"name"`
}

func (i trelloBoard) Id() string {
	return i.IdF
}

func (i trelloBoard) Name() string {
	return i.NameF
}

//List represents a minimal Trello List
type List interface {
	Name() string
	Id() string
	Closed() bool
}

type trelloList struct {
	IdF         string `json:"id"`
	NameF       string `json:"name"`
	ClosedF     bool   `json:"closed"`
	IdBoardF    string `json:"idBoard"`
	SubscribedF bool   `json:"subscribed"`
	PosF        int    `json:"pos"`
}

func (i trelloList) Id() string {
	return i.IdF
}

func (i trelloList) Name() string {
	return i.NameF
}

func (i trelloList) Closed() bool {
	return i.ClosedF
}