text:
<?php

namespace Black\Bundle\ArticleBundle\DependencyInjection;

use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\Builder\ArrayNodeDefinition;
use Symfony\Component\Config\Definition\ConfigurationInterface;

/**
 * Class Configuration
 *
 * @package Black\Bundle\ArticleBundle\DependencyInjection
 * @author  Alexandre Balmes <albalmes@gmail.com>
 * @license http://opensource.org/licenses/mit-license.php MIT
 */
class Configuration implements ConfigurationInterface
{
    /**
     * {@inheritDoc}
     */
    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder();
        $rootNode = $treeBuilder->root('black_article');

        $supportedDrivers = array('mongodb', 'orm');

        $rootNode
            ->children()

            ->scalarNode('db_driver')
                ->isRequired()
                ->validate()
                    ->ifNotInArray($supportedDrivers)
                        ->thenInvalid('The database driver must be either \'mongodb\', \'orm\'.')
                    ->end()
                ->end()

                ->scalarNode('article_class')->isRequired()->cannotBeEmpty()->end()
                ->scalarNode('item_class')->isRequired()->cannotBeEmpty()->end()
                ->scalarNode('category_class')->isRequired()->cannotBeEmpty()->end()
                ->scalarNode('article_manager')->defaultValue('Black\\Bundle\\ArticleBundle\\Doctrine\\ArticleManager')->end()
                ->scalarNode('category_manager')->defaultValue('Black\\Bundle\\ArticleBundle\\Doctrine\\CategoryManager')->end()

            ->end();

        $this->addArticleSection($rootNode);
        $this->addProxySection($rootNode);
        $this->addCategorySection($rootNode);
        $this->addConfigSection($rootNode);

        return $treeBuilder;
    }

    /**
     * @param ArrayNodeDefinition $node
     */
    private function addArticleSection(ArrayNodeDefinition $node)
    {
        $node
            ->children()
                ->arrayNode('article')
                    ->addDefaultsIfNotSet()
                    ->canBeUnset()
                        ->children()
                        ->arrayNode('form')
                        ->addDefaultsIfNotSet()
                            ->children()
                                ->scalarNode('name')
                                    ->defaultValue('black_article_article_form')
                                ->end()
                                ->scalarNode('type')
                                    ->defaultValue('Black\\Bundle\\ArticleBundle\\Form\\Type\\ArticleType')
                                ->end()
                                ->scalarNode('item_type')
                                    ->defaultValue('Black\\Bundle\\ArticleBundle\\Form\\Type\\ItemType')
                                ->end()
                                ->scalarNode('handler')
                                    ->defaultValue('Black\\Bundle\\ArticleBundle\\Form\\Handler\\ArticleFormHandler')
                                ->end()
                                ->scalarNode('enabled_list')
                                    ->defaultValue('Black\\Bundle\\ArticleBundle\\Form\\ChoiceList\\EnabledList')
                                ->end()
                                ->scalarNode('status_list')
                                    ->defaultValue('Black\\Bundle\\ArticleBundle\\Form\\ChoiceList\\StatusList')
                                ->end()
                            ->end()
                        ->end()

                    ->end()
                ->end()
            ->end();
    }

    /**
     * @param ArrayNodeDefinition $node
     */
    private function addProxySection(ArrayNodeDefinition $node)
    {
        $node
            ->children()
                ->arrayNode('proxy')
                    ->addDefaultsIfNotSet()
                    ->canBeUnset()
                        ->children()
                            ->scalarNode('class')->defaultValue('Black\\Bundle\\PageBundle\\Proxy\\PageProxy')->end()
                        ->end()
                    ->end()
                ->end()
            ->end()
        ;
    }

    /**
     * @param ArrayNodeDefinition $node
     */
    private function addCategorySection(ArrayNodeDefinition $node)
    {
        $node
            ->children()
                ->arrayNode('category')
                    ->addDefaultsIfNotSet()
                    ->canBeUnset()
                        ->children()
                            ->arrayNode('form')
                            ->addDefaultsIfNotSet()
                            ->children()
                                ->scalarNode('name')
                                    ->defaultValue('black_category_form')
                                ->end()
                                    ->scalarNode('type')
                                ->defaultValue('Black\\Bundle\\ArticleBundle\\Form\\Type\\CategoryType')
                                    ->end()
                                ->scalarNode('handler')
                                    ->defaultValue('Black\\Bundle\\ArticleBundle\\Form\\Handler\\CategoryFormHandler')
                                ->end()
                            ->end()
                        ->end()

                    ->end()
                ->end()
            ->end();
    }

    /**
     * @param ArrayNodeDefinition $node
     */
    private function addConfigSection(ArrayNodeDefinition $node)
    {
        $node
            ->children()
                ->arrayNode('config')
                    ->addDefaultsIfNotSet()
                    ->canBeUnset()
                        ->children()
                        ->arrayNode('form')
                        ->addDefaultsIfNotSet()
                            ->children()
                                ->scalarNode('article_config_name')
                                    ->defaultValue('black_article_config')
                                ->end()
                                ->scalarNode('article_config_type')
                                    ->defaultValue('Black\\Bundle\\ArticleBundle\\Form\\Type\\ArticleConfigType')
                                ->end()
                                ->scalarNode('article_config_handler')
                                    ->defaultValue('Black\\Bundle\\ConfigBundle\\Form\\Handler\\ConfigFormHandler')
                                ->end()
                            ->end()
                        ->end()
                    ->end()
                ->end()
            ->end();
    }
}


text:
require_relative 'src_encoding'
require_relative 'magic-file'
require_relative 'completion'
require 'reline'

module IRB
  STDIN_FILE_NAME = "(line)" # :nodoc:
  class InputMethod

    # Creates a new input method object
    def initialize(file = STDIN_FILE_NAME)
      @file_name = file
    end
    # The file name of this input method, usually given during initialization.
    attr_reader :file_name

    # The irb prompt associated with this input method
    attr_accessor :prompt

    # Reads the next line from this input method.
    #
    # See IO#gets for more information.
    def gets
      fail NotImplementedError, "gets"
    end
    public :gets

    # Whether this input method is still readable when there is no more data to
    # read.
    #
    # See IO#eof for more information.
    def readable_after_eof?
      false
    end
  end

  class StdioInputMethod < InputMethod
    # Creates a new input method object
    def initialize
      super
      @line_no = 0
      @line = []
      @stdin = IO.open(STDIN.to_i, :external_encoding => IRB.conf[:LC_MESSAGES].encoding, :internal_encoding => "-")
      @stdout = IO.open(STDOUT.to_i, 'w', :external_encoding => IRB.conf[:LC_MESSAGES].encoding, :internal_encoding => "-")
    end

    # Reads the next line from this input method.
    #
    # See IO#gets for more information.
    def gets
      print @prompt
      line = @stdin.gets
      @line[@line_no += 1] = line
    end

    # Whether the end of this input method has been reached, returns +true+ if
    # there is no more data to read.
    #
    # See IO#eof? for more information.
    def eof?
      @stdin.eof?
    end

    # Whether this input method is still readable when there is no more data to
    # read.
    #
    # See IO#eof for more information.
    def readable_after_eof?
      true
    end

    # Returns the current line number for #io.
    #
    # #line counts the number of times #gets is called.
    #
    # See IO#lineno for more information.
    def line(line_no)
      @line[line_no]
    end

    # The external encoding for standard input.
    def encoding
      @stdin.external_encoding
    end
  end

  # Use a File for IO with irb, see InputMethod
  class FileInputMethod < InputMethod
    # Creates a new input method object
    def initialize(file)
      super
      @io = IRB::MagicFile.open(file)
    end
    # The file name of this input method, usually given during initialization.
    attr_reader :file_name

    # Whether the end of this input method has been reached, returns +true+ if
    # there is no more data to read.
    #
    # See IO#eof? for more information.
    def eof?
      @io.eof?
    end

    # Reads the next line from this input method.
    #
    # See IO#gets for more information.
    def gets
      print @prompt
      @io.gets
    end

    # The external encoding for standard input.
    def encoding
      @io.external_encoding
    end
  end

  begin
    require "readline"
    class ReadlineInputMethod < InputMethod
      include Readline
      # Creates a new input method object using Readline
      def initialize
        if Readline.respond_to?(:encoding_system_needs)
          IRB.__send__(:set_encoding, Readline.encoding_system_needs.name, override: false)
        end
        super

        @line_no = 0
        @line = []
        @eof = false

        @stdin = IO.open(STDIN.to_i, :external_encoding => IRB.conf[:LC_MESSAGES].encoding, :internal_encoding => "-")
        @stdout = IO.open(STDOUT.to_i, 'w', :external_encoding => IRB.conf[:LC_MESSAGES].encoding, :internal_encoding => "-")

        if Readline.respond_to?("basic_word_break_characters=")
          Readline.basic_word_break_characters = IRB::InputCompletor::BASIC_WORD_BREAK_CHARACTERS
        end
        Readline.completion_append_character = nil
        Readline.completion_proc = IRB::InputCompletor::CompletionProc
      end

      # Reads the next line from this input method.
      #
      # See IO#gets for more information.
      def gets
        Readline.input = @stdin
        Readline.output = @stdout
        if l = readline(@prompt, false)
          HISTORY.push(l) if !l.empty?
          @line[@line_no += 1] = l + "\n"
        else
          @eof = true
          l
        end
      end

      # Whether the end of this input method has been reached, returns +true+
      # if there is no more data to read.
      #
      # See IO#eof? for more information.
      def eof?
        @eof
      end

      # Whether this input method is still readable when there is no more data to
      # read.
      #
      # See IO#eof for more information.
      def readable_after_eof?
        true
      end

      # Returns the current line number for #io.
      #
      # #line counts the number of times #gets is called.
      #
      # See IO#lineno for more information.
      def line(line_no)
        @line[line_no]
      end

      # The external encoding for standard input.
      def encoding
        @stdin.external_encoding
      end

      if Readline.respond_to?("basic_word_break_characters=")
        Readline.basic_word_break_characters = IRB::InputCompletor::BASIC_WORD_BREAK_CHARACTERS
      end
      Readline.completion_append_character = nil
      Readline.completion_proc = IRB::InputCompletor::CompletionProc
    end
  rescue LoadError
  end

  class ReidlineInputMethod < InputMethod
    include Reline
    # Creates a new input method object using Readline
    def initialize
      IRB.__send__(:set_encoding, Reline.encoding_system_needs.name, override: false)
      super

      @line_no = 0
      @line = []
      @eof = false

      @stdin = ::IO.open(STDIN.to_i, :external_encoding => IRB.conf[:LC_MESSAGES].encoding, :internal_encoding => "-")
      @stdout = ::IO.open(STDOUT.to_i, 'w', :external_encoding => IRB.conf[:LC_MESSAGES].encoding, :internal_encoding => "-")

      if Reline.respond_to?("basic_word_break_characters=")
        Reline.basic_word_break_characters = IRB::InputCompletor::BASIC_WORD_BREAK_CHARACTERS
      end
      Reline.completion_append_character = nil
      Reline.completion_proc = IRB::InputCompletor::CompletionProc
      Reline.output_modifier_proc =
        if IRB.conf[:USE_COLORIZE]
          proc do |output, complete:|
            next unless IRB::Color.colorable?
            IRB::Color.colorize_code(output, complete: complete)
          end
        else
          proc do |output|
            Reline::Unicode.escape_for_print(output)
          end
        end
      Reline.dig_perfect_match_proc = IRB::InputCompletor::PerfectMatchedProc
    end

    def check_termination(&block)
      @check_termination_proc = block
    end

    def dynamic_prompt(&block)
      @prompt_proc = block
    end

    def auto_indent(&block)
      @auto_indent_proc = block
    end

    # Reads the next line from this input method.
    #
    # See IO#gets for more information.
    def gets
      Reline.input = @stdin
      Reline.output = @stdout
      Reline.prompt_proc = @prompt_proc
      Reline.auto_indent_proc = @auto_indent_proc if @auto_indent_proc
      if l = readmultiline(@prompt, false, &@check_termination_proc)
        HISTORY.push(l) if !l.empty?
        @line[@line_no += 1] = l + "\n"
      else
        @eof = true
        l
      end
    end

    # Whether the end of this input method has been reached, returns +true+
    # if there is no more data to read.
    #
    # See IO#eof? for more information.
    def eof?
      @eof
    end

    # Whether this input method is still readable when there is no more data to
    # read.
    #
    # See IO#eof for more information.
    def readable_after_eof?
      true
    end

    # Returns the current line number for #io.
    #
    # #line counts the number of times #gets is called.
    #
    # See IO#lineno for more information.
    def line(line_no)
      @line[line_no]
    end

    # The external encoding for standard input.
    def encoding
      @stdin.external_encoding
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
from lng_abstract_tag import AbstractTag

class lng_stream_tag(AbstractTag):

  def __init__(self, app, **args):
    if args.has_key("fields"):
      AbstractTag.__init__(self, app, "lng_stream_tag", args["fields"])
    else:
      AbstractTag.__init__(self, app, "lng_stream_tag", args)

from dbobj.dbobj import dbTable

class lng_stream_tags(dbTable):
  """
    Collection class for all stream_tag data.
  """
  def __init__(self, app):
    dbTable.__init__(self, app, "lng_stream_tag", lng_stream_tag)

__copyright__="""

"""


text:
import angular from 'angular';
import uiRouter from 'angular-ui-router';
import mainContentComponent from './mainContent.component';

let mainContentModule = angular.module('mainContent', [
    uiRouter
  ])
  .config(($stateProvider) => {
    "ngInject";
    $stateProvider.state('mainContent',{
      parent:'content',
      url:'/main-content',
      component:'mainContent'
    })
  })
  .component('mainContent', mainContentComponent)

  .name;

export default mainContentModule;


text:
package com.connectsdk.smarthomesampler;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;

import com.connectsdk.smarthomesampler.adapter.BeaconAdapter;

public class BluetoothService extends Service implements BeaconAdapter.BeaconUpdate {
    public static final String ACTION_NEW_BEACON = "com.connectsdk.com.connectsdk.smarthomesampler.BluetoothService.action_new_beacon";
    public static final String ACTION_PAUSE_SCANNING = "com.connectsdk.com.connectsdk.smarthomesampler.BluetoothService.action_pause_scanning";

    BeaconAdapter beaconAdapter;

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        beaconAdapter = new BeaconAdapter(getApplicationContext());
        beaconAdapter.setListener(this);
        beaconAdapter.startScan();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (ACTION_PAUSE_SCANNING.equals(intent.getAction())) {
            beaconAdapter.stopScanForPeriod(1000);
        }
        return START_NOT_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        beaconAdapter.stopScan();
    }

    @Override
    public void onClosestBeacon(BeaconAdapter.ScannedBleDevice ble) {
        if (ble != null) {
            Intent intent = new Intent();
            intent.setAction(ACTION_NEW_BEACON);
            intent.putExtra("beacon", ble.macAddress);
            intent.putExtra("distance", ble.distance);
            sendBroadcast(intent);
        }
    }

    @Override
    public void onDetectBeacon(BeaconAdapter.ScannedBleDevice ble) {
    }
}


text:
#pragma once
#include <aws/ssm/SSM_EXPORTS.h>
#include <aws/ssm/SSMRequest.h>
#include <aws/ssm/model/OperatingSystem.h>
#include <aws/ssm/model/PatchProperty.h>
#include <aws/ssm/model/PatchSet.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>

namespace Aws
{
namespace SSM
{
namespace Model
{

  /**
   */
  class AWS_SSM_API DescribePatchPropertiesRequest : public SSMRequest
  {
  public:
    DescribePatchPropertiesRequest();

    // Service request name is the Operation name which will send this request out,
    // each operation should has unique request name, so that we can get operation's name from this request.
    // Note: this is not true for response, multiple operations may have the same response name,
    // so we can not get operation's name from response.
    inline virtual const char* GetServiceRequestName() const override { return "DescribePatchProperties"; }

    Aws::String SerializePayload() const override;

    Aws::Http::HeaderValueCollection GetRequestSpecificHeaders() const override;

    /**
     *
The operating system type for which to list patches.

     */
    inline const OperatingSystem& GetOperatingSystem() const{ return m_operatingSystem; }

    /**
     *
The operating system type for which to list patches.

     */
    inline bool OperatingSystemHasBeenSet() const { return m_operatingSystemHasBeenSet; }

    /**
     *
The operating system type for which to list patches.

     */
    inline void SetOperatingSystem(const OperatingSystem& value) { m_operatingSystemHasBeenSet = true; m_operatingSystem = value; }

    /**
     *
The operating system type for which to list patches.

     */
    inline void SetOperatingSystem(OperatingSystem&& value) { m_operatingSystemHasBeenSet = true; m_operatingSystem = std::move(value); }

    /**
     *
The operating system type for which to list patches.

     */
    inline DescribePatchPropertiesRequest& WithOperatingSystem(const OperatingSystem& value) { SetOperatingSystem(value); return *this;}

    /**
     *
The operating system type for which to list patches.

     */
    inline DescribePatchPropertiesRequest& WithOperatingSystem(OperatingSystem&& value) { SetOperatingSystem(std::move(value)); return *this;}

    /**
     *
The patch property for which you want to view patch details.

     */
    inline const PatchProperty& GetProperty() const{ return m_property; }

    /**
     *
The patch property for which you want to view patch details.

     */
    inline bool PropertyHasBeenSet() const { return m_propertyHasBeenSet; }

    /**
     *
The patch property for which you want to view patch details.

     */
    inline void SetProperty(const PatchProperty& value) { m_propertyHasBeenSet = true; m_property = value; }

    /**
     *
The patch property for which you want to view patch details.

     */
    inline void SetProperty(PatchProperty&& value) { m_propertyHasBeenSet = true; m_property = std::move(value); }

    /**
     *
The patch property for which you want to view patch details.

     */
    inline DescribePatchPropertiesRequest& WithProperty(const PatchProperty& value) { SetProperty(value); return *this;}

    /**
     *
The patch property for which you want to view patch details.

     */
    inline DescribePatchPropertiesRequest& WithProperty(PatchProperty&& value) { SetProperty(std::move(value)); return *this;}

    /**
     *
Indicates whether to list patches for the Windows operating system or for
     * Microsoft applications. Not applicable for the Linux or macOS operating
     * systems.

     */
    inline const PatchSet& GetPatchSet() const{ return m_patchSet; }

    /**
     *
Indicates whether to list patches for the Windows operating system or for
     * Microsoft applications. Not applicable for the Linux or macOS operating
     * systems.

     */
    inline bool PatchSetHasBeenSet() const { return m_patchSetHasBeenSet; }

    /**
     *
Indicates whether to list patches for the Windows operating system or for
     * Microsoft applications. Not applicable for the Linux or macOS operating
     * systems.

     */
    inline void SetPatchSet(const PatchSet& value) { m_patchSetHasBeenSet = true; m_patchSet = value; }

    /**
     *
Indicates whether to list patches for the Windows operating system or for
     * Microsoft applications. Not applicable for the Linux or macOS operating
     * systems.

     */
    inline void SetPatchSet(PatchSet&& value) { m_patchSetHasBeenSet = true; m_patchSet = std::move(value); }

    /**
     *
Indicates whether to list patches for the Windows operating system or for
     * Microsoft applications. Not applicable for the Linux or macOS operating
     * systems.

     */
    inline DescribePatchPropertiesRequest& WithPatchSet(const PatchSet& value) { SetPatchSet(value); return *this;}

    /**
     *
Indicates whether to list patches for the Windows operating system or for
     * Microsoft applications. Not applicable for the Linux or macOS operating
     * systems.

     */
    inline DescribePatchPropertiesRequest& WithPatchSet(PatchSet&& value) { SetPatchSet(std::move(value)); return *this;}

    /**
     *
The maximum number of items to return for this call. The call also returns a
     * token that you can specify in a subsequent call to get the next set of
     * results.

     */
    inline int GetMaxResults() const{ return m_maxResults; }

    /**
     *
The maximum number of items to return for this call. The call also returns a
     * token that you can specify in a subsequent call to get the next set of
     * results.

     */
    inline bool MaxResultsHasBeenSet() const { return m_maxResultsHasBeenSet; }

    /**
     *
The maximum number of items to return for this call. The call also returns a
     * token that you can specify in a subsequent call to get the next set of
     * results.

     */
    inline void SetMaxResults(int value) { m_maxResultsHasBeenSet = true; m_maxResults = value; }

    /**
     *
The maximum number of items to return for this call. The call also returns a
     * token that you can specify in a subsequent call to get the next set of
     * results.

     */
    inline DescribePatchPropertiesRequest& WithMaxResults(int value) { SetMaxResults(value); return *this;}

    /**
     *
The token for the next set of items to return. (You received this token from
     * a previous call.)

     */
    inline const Aws::String& GetNextToken() const{ return m_nextToken; }

    /**
     *
The token for the next set of items to return. (You received this token from
     * a previous call.)

     */
    inline bool NextTokenHasBeenSet() const { return m_nextTokenHasBeenSet; }

    /**
     *
The token for the next set of items to return. (You received this token from
     * a previous call.)

     */
    inline void SetNextToken(const Aws::String& value) { m_nextTokenHasBeenSet = true; m_nextToken = value; }

    /**
     *
The token for the next set of items to return. (You received this token from
     * a previous call.)

     */
    inline void SetNextToken(Aws::String&& value) { m_nextTokenHasBeenSet = true; m_nextToken = std::move(value); }

    /**
     *
The token for the next set of items to return. (You received this token from
     * a previous call.)

     */
    inline void SetNextToken(const char* value) { m_nextTokenHasBeenSet = true; m_nextToken.assign(value); }

    /**
     *
The token for the next set of items to return. (You received this token from
     * a previous call.)

     */
    inline DescribePatchPropertiesRequest& WithNextToken(const Aws::String& value) { SetNextToken(value); return *this;}

    /**
     *
The token for the next set of items to return. (You received this token from
     * a previous call.)

     */
    inline DescribePatchPropertiesRequest& WithNextToken(Aws::String&& value) { SetNextToken(std::move(value)); return *this;}

    /**
     *
The token for the next set of items to return. (You received this token from
     * a previous call.)

     */
    inline DescribePatchPropertiesRequest& WithNextToken(const char* value) { SetNextToken(value); return *this;}

  private:

    OperatingSystem m_operatingSystem;
    bool m_operatingSystemHasBeenSet;

    PatchProperty m_property;
    bool m_propertyHasBeenSet;

    PatchSet m_patchSet;
    bool m_patchSetHasBeenSet;

    int m_maxResults;
    bool m_maxResultsHasBeenSet;

    Aws::String m_nextToken;
    bool m_nextTokenHasBeenSet;
  };

} // namespace Model
} // namespace SSM
} // namespace Aws


text:
<?php

namespace Illuminate\Support\Facades;

/**
 * @method static bool hasForLocale(string $key, string $locale = null)
 * @method static bool has(string $key, string $locale = null, bool $fallback = true)
 * @method static mixed get(string $key, array $replace = [], string $locale = null, bool $fallback = true)
 * @method static string choice(string $key, \Countable|int|array $number, array $replace = [], string $locale = null)
 * @method static string getLocale()
 * @method static void setLocale(string $locale)
 *
 * @see \Illuminate\Translation\Translator
 */
class Lang extends Facade
{
    /**
     * Get the registered name of the component.
     *
     * @return string
     */
    protected static function getFacadeAccessor()
    {
        return 'translator';
    }
}


text: FAILURE


text:
package org.apache.camel.spring;

import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

public class StartupShutdownSpringCamelContextFactoryBeanOrderTest extends StartupShutdownOrderBaseTest {
    @Configuration
    static class CamelContextConfiguration {
        @Bean
        CamelContextFactoryBean camelContext() {
            final CamelContextFactoryBean factory = new CamelContextFactoryBean();
            factory.setId("camelContext");

            return factory;
        }
    }

    @Override
    ConfigurableApplicationContext createContext() {
        final ConfigurableApplicationContext context = new AnnotationConfigApplicationContext(
            CamelContextConfiguration.class, Beans.class);
        return context;
    }

}


text:
package org.sdgas.service.impl;

import org.sdgas.base.DaoSupport;
import org.sdgas.model.Contract;
import org.sdgas.model.Payment;
import org.sdgas.service.ContractService;
import org.sdgas.service.PaymentService;
import org.sdgas.util.ChangeTime;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by 120378 on 2015/8/19.
 */
@Service
@Transactional
public class PaymentServiceImpl extends DaoSupport<Payment> implements PaymentService {

    private ContractService contractService;

    @Override
    public Payment findByContractId(String contractId) {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("contract", contractService.findContractById(contractId));
        return (Payment) this.findSpecialObject(Payment.class, params);
    }

    @Override
    public Payment saveOrUpdatePay(String contract, String paymentDate, String paymentMoney, String remark) {
        String tep[] = paymentMoney.split(",");
        double money = 0.0d;
        for (String str : tep) {
            if (!str.trim().isEmpty()) {
                money += Double.valueOf(str);
            }
        }
        int k = 0;
        for (; k < tep.length; k++) {
            if ("".equals(tep[k].trim()))
                break;
        }
        String pm = "";
        for (int j = k - 1; j > -1; j--)
            pm = tep[j] + "," + pm;
        pm = pm.substring(0, pm.length() - 1);

        tep = paymentDate.split(",");
        String pd = "";
        int i = 0;
        for (; i < tep.length; i++) {
            if ("".equals(tep[i].trim()))
                break;
        }
        for (int j = i - 1; j > -1; j--)
            pd = tep[j] + "," + pd;
        pd = pd.substring(0, pd.length() - 1);

        Payment payment = this.findByContractId(contract);
        if (payment == null) {
            payment = new Payment();
            payment.setContract(contractService.find(Contract.class, contract));
            payment.setPaymentDate(pd);
            payment.setPayMoney(paymentMoney);
            payment.setRemark(remark);
            payment.setLeftMoney(contractService.findContractById(contract).getContractMoney() - money);
            this.save(payment);
        } else {
            if (payment.getPaymentDate() != null)
                payment.setPaymentDate(payment.getPaymentDate() + "," + pd);
            else
                payment.setPaymentDate(payment.getPaymentDate() + pd);

            if (payment.getPayMoney() != null)
                payment.setPayMoney(payment.getPayMoney() + "," + pm);
            else
                payment.setPayMoney(payment.getPayMoney() + pm);
            payment.setRemark(payment.getRemark() + "<br/>" + remark);
            payment.setLeftMoney(payment.getLeftMoney() - money);
            this.update(payment);
        }
        return payment;
    }

    @Resource(name = "contractServiceImpl")
    public void setContractService(ContractService contractService) {
        this.contractService = contractService;
    }
}


text:
package com.code4a.jlibrarydemo.http;

import retrofit2.http.GET;
import retrofit2.http.Path;
import rx.Observable;

/**
 * Created by gaohailong on 2016/5/17.
 */
public interface Code4aService {

    @GET("{key}")
    Observable<String> getAlipayInfo(
            @Path("key") String key
    );

}


text:
![Ash Api Framework](/logo_vertical.jpg?raw=true "Ash Api Framework")

ash-core

Node.js API framework

View the API docs at [https://ash-framework.github.io/core](https://ash-framework.github.io/core)

Get started by installing the cli at [https://github.com/ash-framework/cli](https://github.com/ash-framework/cli)

Install

NPM

Install: npm install --save ash-core

Module: require('ash-core')

## Developing Ash

### Running tests

1. Install jest
```
npm i -g jest
```

2. Create a postgres database for integration tests

3. Run tests passing postgres database connection string as an environment variable
```
PG_DB=<database> PG_USER=<user> jest
```

History

Discover the release history by heading on over to the releases page.

Backers

Maintainers

These amazing people are maintaining this project:

Richard Walker digitalsadhu@gmail.com

Sponsors

These amazing people have contributed finances to this project:

The Media Suite

Become a sponsor!

Contributors

These amazing people have contributed code to this project:

Richard Walker — view contributions

Mark Stuart https://github.com/markstuart

Patches https://github.com/pnw

Patrick Haply — view contributions

License

Unless stated otherwise all works are:

Copyright © Richard Walker

and licensed under:

MIT License


text:
import { Dom7Array } from 'dom7';
import Framework7, { CSSSelector, Framework7EventsClass, Framework7Plugin } from '../app/app-class';
import { Router } from '../../modules/router/router';

export namespace View {
  interface View extends Framework7EventsClass<Events> {
    /** Link to global app instance */
    app: Framework7;
    /** View HTML element */
    el: HTMLElement;
    /** Dom7 instance with view HTML element */
    $el: Dom7Array;
    /** View name that was passed name parameter */
    name: string;
    /** Boolean property indicating is it a main view or not */
    main: boolean;
    /** Array with available router's routes */
    routes: Router.RouteParameters[];
    /** Array with view history */
    history: string[];
    /** Object with view initialization parameters */
    params: Parameters;
    /** View's initialized router instance */
    router: Router.Router;
    /** Destroy view instance */
    destroy(): void;
  }
  interface Parameters {
    /**	View name. If view was created with name, then it may be accessed via app.views.[name] */
    name?: string;
    /**	Specify whether this is View is main or not. If not passed then will be determined based on whether its element has view-main class or not */
    main?: boolean;
    /**	Set to false to disable view router */
    router?: boolean;
    /**	Default (initial) View's url. If not specified, then it is equal to document url */
    url?: string;
    /**	If enabled then all previous pages in navigation chain will not be removed from DOM when you navigate deeper and deeper. It could be useful, for example, if you have some Form from 5 steps (5 pages) and when you are on last 5th page you need access to form that was on 1st page. */
    stackPages?: boolean;
    /**	CSS Selector of another view or object with initialized View instance. By default all links in initialized (only) view will load pages in this view. This tell links to load pages in other view. */
    linksView?: CSSSelector | View;
    /**	You may enable this parameter to allow loading of new pages that have same url as currently "active" page in View. */
    allowDuplicateUrls?: boolean;
    /**	Enables transitions between pages */
    animate?: boolean;
    /** Custom page transition effect name */
    transition?: string;
    /**	Enable/disable preloading of previous page when you go deep in navigation. Should be enabled for correct work of "swipe back page" feature. */
    preloadPreviousPage?: boolean;
    /**	When enabled, View will always reload currently active page without loading new one */
    reloadPages?: boolean;
    /** When enabled it will reload every detail page when navigating (by default false) */
    reloadDetail?: boolean;
    /** Minimum app width to enable Master Detail view for master routes (routes with master: true parameter) */
    masterDetailBreakpoint?: number;
    /** Enables resizable Master Detail */
    masterDetailResizable?: boolean;
    /**	When enabled it will restore page scroll top when you get back to this page */
    restoreScrollTopOnBack?: boolean;
    /**	Delay (in ms) after new page will be loaded and inserted to DOM and before it will be transitioned. Can be increased a bit to improve performance. Will have effect only under iOS theme */
    iosPageLoadDelay?: number;
    /**	Delay (in ms) after new page will be loaded and inserted to DOM and before it will be transitioned. Can be increased a bit to improve performance. Will have effect only under MD theme */
    mdPageLoadDelay?: number;
    /**	Delay (in ms) after new page will be loaded and inserted to DOM and before it will be transitioned. Can be increased a bit to improve performance. Will have effect only under Aurora theme */
    auroraPageLoadDelay?: number;
    /**	When enabled then router will pass route url query to request url query (for url, componentUrl route properties) */
    passRouteQueryToRequest?: boolean;
    /**	When enabled then router will pass current route parameters to request url query (for url, componentUrl route properties) */
    passRouteParamsToRequest?: boolean;
    /**	Array with current View routes. In case if specified then will overwrite global app routes and routes only specified here will be available for the current View */
    routes?: Router.RouteParameters[];
    /**	Array with additional routes that will extend global app routes. This additional routes will only be available for the current View */
    routesAdd?: Router.RouteParameters[];
    /**	Function (or array of functions) that will be executed before every route load/enter. To proceed route loading resolve must be called. In case of array then every function in array must be resolved to proceed. */
    routesBeforeEnter?(ctx: {
      to: Router.Route;
      from: Router.Route;
      resolve: Function;
      reject: Function;
      router: Router.Router;
      direction?: 'forward' | 'backward';
    }): void;
    /**	Function (or array of functions) that will be executed before every route unload/leave. To proceed navigation resolve must be called. In case of array then every function in array must be resolved to proceed. */
    routesBeforeLeave?(ctx: {
      to: Router.Route;
      from: Router.Route;
      resolve: Function;
      reject: Function;
      router: Router.Router;
      direction?: 'forward' | 'backward';
    }): void;
    /**	During page transitions Router may remove unused Page and Navbar elements from DOM. Useful to be disabled in case you want to handle elements removal manually or using other library, e.g. Vue or React */
    removeElements?: boolean;
    /**	When enabled then Router will remove elements after timeout */
    removeElementsWithTimeout?: boolean;
    /**	Timeout to remove elements (in case of removeElementsWithTimeout: true) */
    removeElementsTimeout?: number;
    /**	Unloads routable tab content (removes tab inner content) when tab becomes visible. Only for routable tabs */
    unloadTabContent?: boolean;
    /**	As Router can use Ajax to load HTML content for pages it is good to use caching, especially if your content in those pages updates not very often. */
    xhrCache?: boolean;
    /**	Array of URLs (string) that should not be cached */
    xhrCacheIgnore?: string[];
    /**	If "true" then URLs like "about.html?id=2" and "about.html?id=3" will be treated and cached like single "about.html" page */
    xhrCacheIgnoreGetParameters?: boolean;
    /**	Duration in ms (milliseconds) while app will use cache instead of loading page with another Ajax request. By default it takes 10 minutes. */
    xhrCacheDuration?: number;
    /** When enabled, Router will cache components specified via `componentUrl` (default true) */
    componentCache?: boolean;
    /** When enabled, and there is no children pages inside of the View. It will load initial page that matches to initial URL (default true) */
    loadInitialPage?: boolean;
    /**	Enables dynamic navbar for iOS theme */
    iosDynamicNavbar?: boolean;
    /**	This option (when enabled) gives more native look for dynamic navbar left back-link icon animation. Useful only when you use dynamic navbar with default back-link icon on left side set as "sliding". */
    iosAnimateNavbarBackIcon?: boolean;
    /**	Enable/disable ability to swipe back from left edge of screen to get to the previous page. For iOS theme */
    iosSwipeBack?: boolean;
    /**	Value in px. Swipe back action will start if "touch distance" will be more than this value. For iOS theme */
    iosSwipeBackThreshold?: number;
    /**	Value in px. Width of invisible left edge of the screen that triggers swipe back action. For iOS theme */
    iosSwipeBackActiveArea?: number;
    /**	Enable/disable box-shadow animation during swipe back action. You can disable it to improve performance. For iOS theme */
    iosSwipeBackAnimateShadow?: boolean;
    /**	Enable/disable opacity animation during swipe back action. You can disable it to improve performance. For iOS theme */
    iosSwipeBackAnimateOpacity?: boolean;
    /**	Enable/disable ability to swipe back from left edge of screen to get to the previous page. For MD theme */
    mdSwipeBack?: boolean;
    /**	Value in px. Swipe back action will start if "touch distance" will be more than this value. For MD theme */
    mdSwipeBackThreshold?: number;
    /**	Value in px. Width of invisible left edge of the screen that triggers swipe back action. For MD theme */
    mdSwipeBackActiveArea?: number;
    /**	Enable/disable box-shadow animation during swipe back action. You can disable it to improve performance. For MD theme */
    mdSwipeBackAnimateShadow?: boolean;
    /**	Enable/disable opacity animation during swipe back action. You can disable it to improve performance. For MD theme */
    mdSwipeBackAnimateOpacity?: boolean;
    /**	Enable/disable ability to swipe back from left edge of screen to get to the previous page. For Aurora theme */
    auroraSwipeBack?: boolean;
    /**	Value in px. Swipe back action will start if "touch distance" will be more than this value. For Aurora theme */
    auroraSwipeBackThreshold?: number;
    /**	Value in px. Width of invisible left edge of the screen that triggers swipe back action. For Aurora theme */
    auroraSwipeBackActiveArea?: number;
    /**	Enable/disable box-shadow animation during swipe back action. You can disable it to improve performance. For Aurora theme */
    auroraSwipeBackAnimateShadow?: boolean;
    /**	Enable/disable opacity animation during swipe back action. You can disable it to improve performance. For Aurora theme */
    auroraSwipeBackAnimateOpacity?: boolean;
    /**	If you develop web app (not PhoneGap or Home Screen web app) it is useful to enable hash navigation (browser url will look like "http://my-webapp.com/#!/about.html"). User as well will be able to navigate through app's history by using browser's default back and forward buttons. */
    browserHistory?: boolean;
    /**	Browser history root URL, for example "http://my-app.com/". It is useful only in case when you use empty ("") browserHistorySeparator */
    browserHistoryRoot?: string;
    /**	Enable/disable page transitions on history change */
    browserHistoryAnimate?: boolean;
    /**	Enable/disable page transition on app load */
    browserHistoryAnimateOnLoad?: boolean;
    /**	Browser history URL separator, can be changed for something like '#page/' and then your URLs will look like "http://myapp.com/#page/about.html" */
    browserHistorySeparator?: string;
    /**	Disable to ignore parsing browser history URL and loading page on app load */
    browserHistoryOnLoad?: boolean;
    /**	Set to true when your server cofigured to respond with content that matches to requested URL (e.g. using with server-side rendering frameworks like Nuxt.js, Next.js, and others). Also must be enabled when used in Framework7-React/Vue/Svelte. By default disabled */
    browserHistoryInitialMatch?: boolean;
    /**	When enabled (by default), it will store router history in localStorage and try to restore it on next web app visit */
    browserHistoryStoreHistory?: boolean;
    /** Object with events handlers.. */
    on?: {
      [event in keyof Events]?: Events[event];
    };
  }
  interface View extends Router.AppMethods {}
  interface Events extends Router.Events {
    /** Event will be fired on View init */
    init: (view: View) => void;
    /** Event will be triggered right when resizable Master Detail resized */
    resize: (view: View, masterWidth: number) => void;
  }
  interface DomEvents extends Router.DomEvents {
    /** Event will be fired on View init */
    'view:init': () => void;
    /** Event will be triggered right when resizable Master Detail resized */
    'view:resize': () => void;
  }
  interface AppMethods extends Router.AppEvents {
    view: {
      current: View;
      main: View;
      create(viewEl: HTMLElement | CSSSelector, parameters?: Parameters): View;
      get(viewEl: HTMLElement | CSSSelector): View;
    };
    views: {
      current: View;
      main: View;
      create(viewEl: HTMLElement | CSSSelector, parameters?: Parameters): View;
      get(viewEl: HTMLElement | CSSSelector): View;
    };
  }
  interface AppParams {
    view?: Parameters | undefined;
  }
  interface AppEvents extends Router.Events {
    /** Event will be fired on View init */
    viewInit: (view: View) => void;
    /** Event will be triggered right when resizable Master Detail resized */
    viewResize: (view: View, masterWidth: number) => void;
  }
}

declare const ViewComponent: Framework7Plugin;
export default ViewComponent;


text:
from django.db import models
from .mixins import TimeStampedMixin
from django.contrib.auth.models import User

class Category(TimeStampedMixin):
    description = models.CharField(max_length=255)
    icon = models.CharField(max_length=255)

    def __str__(self):
        return self.description

class Site(TimeStampedMixin):
    user = models.ManyToManyField(User, through='Rating', related_name="ratings")
    user_like = models.ManyToManyField(User, through='Like')
    description = models.CharField(max_length=255)
    detail = models.TextField(blank=True, null=True)
    latitude = models.CharField(max_length=50)
    longitude = models.CharField(max_length=50)
    tags = models.TextField()
    category = models.ForeignKey(Category)
    creator_by = models.ForeignKey(User, related_name="creator")

    def get_category_icon(self):
        return Category.objects.get(pk=self.category.id).icon

class Picture(TimeStampedMixin):
    picture = models.ImageField(upload_to='sites/')
    site = models.ForeignKey(Site)

class Rating(TimeStampedMixin):
    user = models.ForeignKey(User)
    site = models.ForeignKey(Site)
    rating = models.DecimalField(max_digits=2, decimal_places=1)

class Like(TimeStampedMixin):
    user = models.ForeignKey(User)
    site = models.ForeignKey(Site)


text:
package uk.co.todddavies.website.notes;

import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Optional;
import com.google.inject.*;
import com.google.inject.name.Named;
import com.google.inject.name.Names;
import com.google.inject.servlet.RequestScoped;
import com.google.inject.servlet.ServletModule;

import javax.servlet.*;
import java.io.IOException;
import java.util.logging.Logger;

/**
 * Module for serving '{@code /api/notes*}'.
 */
public final class NotesServletModule extends ServletModule {

  @VisibleForTesting static final String KEY_PARAMTER_NAME = "key";
  private static final Logger log = Logger.getLogger(NotesServletModule.class.getName());

  private final String apiPath;

  private NotesServletModule(String apiPath) {
    this.apiPath = apiPath;
  }

  /**
   * Static method for installing the requisite dependencies.
   */
  public static AbstractModule create(final String apiPath) {
    return new AbstractModule() {
      @Override
      protected void configure() {
        install(new NotesServletModule(apiPath));
      }
    };
  }

  @Override
  protected void configureServlets() {
    filter(apiPath + "notes-dl*").through(KeyFilter.class);
    serve(apiPath + "notes-dl*").with(NotesApiDownloadServlet.class);
    serve(apiPath + "notes").with(NotesApiServlet.class);
  }

  /**
   * Injects {@code @named{"key"} Long key} to requests with a 'key' GET parameter.
   */
  @Singleton
  @VisibleForTesting
  static final class KeyFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {/* Not required. */}

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
        FilterChain chain) throws IOException, ServletException {
      String keyParameter = request.getParameter(KEY_PARAMTER_NAME);
      Optional<Long> key = parseLong(keyParameter, KEY_PARAMTER_NAME);
      request.setAttribute(
          Key.get(
              new TypeLiteral<Optional<Long>>() {},
              Names.named(KEY_PARAMTER_NAME))
            .toString(),
          key);
      chain.doFilter(request, response);
    }

    @Override
    public void destroy() {/* Not required. */}

    private static Optional<Long> parseLong(String input, String argument) {
      try {
        return Optional.of(Long.valueOf(input));
      } catch (NumberFormatException e) {
        if (input != null && !input.isEmpty()) {
           log.warning(String.format(
               "Parameter for '%s' could not be parsed to a long. Value passed was:\n%s",
               argument, input));
        }
        return Optional.<Long>absent();
      }
    }
  }

  @Provides
  @Named("key")
  @RequestScoped Optional<Long> provideKey() {
    throw new IllegalStateException("Notes key is derived from the request.");
  }
}


text:
package com.amazonaws.services.lambda.runtime.events;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.List;
import java.util.Map;

/**
 * Represents a Rabbit MQ event sent to Lambda
 * Onboarding Amazon MQ as event source to Lambda
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder(setterPrefix = "with")
public class RabbitMQEvent {

    private String eventSource;
    private String eventSourceArn;
    private Map<String, List<RabbitMessage>> rmqMessagesByQueue;

    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    @Builder(setterPrefix = "with")
    public static class RabbitMessage {
        private BasicProperties basicProperties;
        private boolean redelivered;
        private String data;
    }

    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    @Builder(setterPrefix = "with")
    public static class BasicProperties {

        private String contentType;
        private String contentEncoding;
        private Map<String, Object> headers;
        private int deliveryMode;
        private int priority;
        private String correlationId;
        private String replyTo;
        private int expiration;
        private String messageId;
        private String timestamp;
        private String type;
        private String userId;
        private String appId;
        private String clusterId;
        private int bodySize;
    }
}


text:
package pl.edu.ug.introductiontojee.jpa.core.onetomany.domain;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.Date;
import java.util.List;

@Stateless
public class MessageStorageService {
    @PersistenceContext
    EntityManager em;

    public Message get(Long id) {
        return em.find(Message.class, id);
    }

    public void add(Message message) {
        message.setId(null);
        message.setCreatedAt(new Date());

        em.persist(message);
    }

    public void addComment(Message message, Comment comment) {
        List<Comment> comments = message.getComments();
        comments.add(comment);

        message.setComments(comments);

        em.merge(message);
    }

    public List<Message> getAllMessages(){
        //noinspection unchecked
        return em.createNamedQuery("message.all").getResultList();
    }
}


text:
package jp.yoshi_misa_kae.tatami.recyclerview;

import android.content.Context;
import android.support.annotation.CallSuper;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;

import java.util.List;

import jp.yoshi_misa_kae.tatami.R;

/**
 * Created by ymizusawa on 2015/12/18.
 */
public class TatamiRecyclerView<T> extends RecyclerView {

    private TatamiRecyclerViewListener<T> listener;
    private TatamiRecyclerViewAdapter adapter = null;

    public TatamiRecyclerView(Context context) {
        this(context, null);
    }

    public TatamiRecyclerView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public TatamiRecyclerView(Context context, @Nullable AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);

        if (isInEditMode())
            init(context);
//        else
//            setHasFixedSize(true);
    }

    private void init(Context context) {
        View.inflate(context, R.layout.tatami_recycler_view, this);
    }

    public void setTatamiRecyclerViewListener(TatamiRecyclerViewListener<T> listener, List<T> list) {
        this.listener = listener;
        adapter = new TatamiRecyclerViewAdapter<T>(listener, list);
        setAdapter(adapter);
    }

    @Override
    public Adapter getAdapter() {
        return adapter;
    }

//    public void setList(List<T> list) {
//        if (adapter != null)
//            adapter.setList(list);
////            adapter.notifyDataSetChanged();
//    }

    public void add(T data) {
        adapter.add(data);
    }

    public void add(int position, T data) {
        adapter.add(position, data);
    }

    public void addAll(List<T> data) {
        adapter.addAll(data);
    }

    public void remove(T data) {
        adapter.remove(data);
    }

    public void remove(int position) {
        adapter.remove(position);
        removeViewAt(position);
    }

    private static class TatamiRecyclerViewAdapter<T> extends RecyclerView.Adapter<TatamiViewHolder> {

        private List<T> list;

        private TatamiRecyclerViewListener<T> listener;

        TatamiRecyclerViewAdapter(TatamiRecyclerViewListener<T> listener, List<T> list) {
            this.listener = listener;
            this.list = list;
//            setHasStableIds(true);
        }

        @Override
        public TatamiViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            return listener.onCreateViewHolder(parent, viewType);
        }

        @Override
        public void onBindViewHolder(TatamiViewHolder viewHolder, int position) {
            viewHolder.setListener(listener);
            viewHolder.setData(list.get(position), position);
        }

        @Override
        public int getItemCount() {
            return list == null ? 0 : list.size();
        }

        public void add(T data) {
//            list.add(data);
//            notifyItemInserted(list.size() - 1);
        }

        public void add(int position, T data) {
//            list.add(position, data);
//            notifyItemInserted(position);
        }

        public void addAll(List<T> data) {
            list = data;
//            notifyDataSetChanged();
        }

        public void remove(int position) {
//            list.remove(position);
            notifyItemRemoved(position);
        }

        public void remove(T data) {
//            int position = list.indexOf(data);
//            list.remove(data);
//            notifyItemRemoved(position);
        }

    }

    public static abstract class TatamiViewHolder<T> extends RecyclerView.ViewHolder {

        private TatamiRecyclerViewListener<T> listener;

        public TatamiViewHolder(View itemView) {
            super(itemView);
        }

        public void setListener(TatamiRecyclerViewListener<T> listener) {
            this.listener = listener;
        }

        @CallSuper
        public void setData(final T data, final int position) {
            itemView.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View view) {
//                    int position = getLayoutPosition();
                if(listener != null) listener.itemClick(position, data);
                }

            });

            itemView.setOnLongClickListener(new View.OnLongClickListener() {

                @Override
                public boolean onLongClick(View view) {
//                    int position = getLayoutPosition();
                    if(listener != null) return listener.itemLongClick(position, data);
                    else return false;
                }
            });

        }

    }

}


text:
package com.baomidou.mybatisplus.plugins;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;

import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Plugin;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.SystemMetaObject;
import org.apache.ibatis.scripting.defaults.DefaultParameterHandler;
import org.apache.ibatis.session.RowBounds;

import com.baomidou.mybatisplus.MybatisDefaultParameterHandler;
import com.baomidou.mybatisplus.enums.DBType;
import com.baomidou.mybatisplus.plugins.pagination.DialectFactory;
import com.baomidou.mybatisplus.plugins.pagination.Pagination;
import com.baomidou.mybatisplus.toolkit.JdbcUtils;
import com.baomidou.mybatisplus.toolkit.JsqlParserUtils;
import com.baomidou.mybatisplus.toolkit.PluginUtils;
import com.baomidou.mybatisplus.toolkit.StringUtils;

/**
 *

 * 分页拦截器
 *

 *
 * @author hubin
 * @Date 2016-01-23
 */
@Intercepts({@Signature(type = StatementHandler.class, method = "prepare", args = {Connection.class, Integer.class})})
public class PaginationInterceptor implements Interceptor {

    /* 溢出总页数,设置第一页 */
    private boolean overflowCurrent = false;

    /**
     * Physical Pagination Interceptor for all the queries with parameter {@link org.apache.ibatis.session.RowBounds}
     */
    public Object intercept(Invocation invocation) throws Throwable {
        StatementHandler statementHandler = (StatementHandler) PluginUtils.realTarget(invocation.getTarget());
        MetaObject metaStatementHandler = SystemMetaObject.forObject(statementHandler);
        // 先判断是不是SELECT操作
        MappedStatement mappedStatement = (MappedStatement) metaStatementHandler.getValue("delegate.mappedStatement");
        if (!SqlCommandType.SELECT.equals(mappedStatement.getSqlCommandType())) {
            return invocation.proceed();
        }
        RowBounds rowBounds = (RowBounds) metaStatementHandler.getValue("delegate.rowBounds");
        /* 不需要分页的场合 */
        if (rowBounds == null || rowBounds == RowBounds.DEFAULT) {
            return invocation.proceed();
        }
        BoundSql boundSql = (BoundSql) metaStatementHandler.getValue("delegate.boundSql");
        String originalSql = boundSql.getSql();
        Connection connection = (Connection) invocation.getArgs()[0];
        DBType dbType = JdbcUtils.getDbType(connection.getMetaData().getURL());
        if (rowBounds instanceof Pagination) {
            Pagination page = (Pagination) rowBounds;
            if (page.isSearchCount()) {
                this.queryTotal(JsqlParserUtils.jsqlparserCount(originalSql), mappedStatement, boundSql, page, connection);
                if (page.getTotal() <= 0) {
                    return invocation.proceed();
                }
            }
            originalSql = DialectFactory.buildPaginationSql(page, originalSql, dbType, null);
        } else {
            // support physical Pagination for RowBounds
            originalSql = DialectFactory.buildPaginationSql(rowBounds, originalSql, dbType, null);
        }

		/*
         *
 禁用内存分页

 内存分页会查询所有结果出来处理(这个很吓人的),如果结果变化频繁这个数据还会不准。

		 */
        metaStatementHandler.setValue("delegate.boundSql.sql", originalSql);
        metaStatementHandler.setValue("delegate.rowBounds.offset", RowBounds.NO_ROW_OFFSET);
        metaStatementHandler.setValue("delegate.rowBounds.limit", RowBounds.NO_ROW_LIMIT);
        return invocation.proceed();
    }

    /**
     * 查询总记录条数
     *
     * @param sql
     * @param mappedStatement
     * @param boundSql
     * @param page
     */
    protected void queryTotal(String sql, MappedStatement mappedStatement, BoundSql boundSql, Pagination page, Connection connection) throws SQLException {
        try (PreparedStatement statement = connection.prepareStatement(sql)) {
            DefaultParameterHandler parameterHandler = new MybatisDefaultParameterHandler(mappedStatement, boundSql.getParameterObject(), boundSql);
            parameterHandler.setParameters(statement);
            int total = 0;
            try (ResultSet resultSet = statement.executeQuery()) {
                if (resultSet.next()) {
                    total = resultSet.getInt(1);
                }
            }
            page.setTotal(total);
            /*
             * 溢出总页数,设置第一页
			 */
            int pages = page.getPages();
            if (overflowCurrent && (page.getCurrent() > pages)) {
                page = new Pagination(1, page.getSize());
                page.setTotal(total);
            }
        }
    }

    public Object plugin(Object target) {
        if (target instanceof StatementHandler) {
            return Plugin.wrap(target, this);
        }
        return target;
    }

    @Override
    public void setProperties(Properties prop) {
        String overflowCurrent = prop.getProperty("overflowCurrent");
        if (StringUtils.isNotEmpty(overflowCurrent)) {
            this.overflowCurrent = Boolean.TRUE.toString().equals(overflowCurrent);
        }
    }

    public void setOverflowCurrent(boolean overflowCurrent) {
        this.overflowCurrent = overflowCurrent;
    }

}


text:
{-# LANGUAGE CPP #-}

#if MIN_VERSION_GLASGOW_HASKELL(8,0,0,0)
{-# OPTIONS_GHC -fno-warn-unused-top-binds -fno-warn-redundant-constraints #-}
#else
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
#endif

{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE FunctionalDependencies #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE TemplateHaskell #-}

module Test.Control.Monad.TestFixtureSpec (spec) where

import Test.Hspec

import Control.Monad.Trans.Class (lift)
import Control.Monad.TestFixture
import Control.Monad.TestFixture.TH

newtype Id a = Id Int
newtype DBError = DBError () deriving (Eq, Show)

data HTTPRequest = GET String
data HTTPResponse = HTTPResponse { responseStatus :: Int }
data HTTPError

class DBRecord a where
  procureRecord :: a

data User = User deriving (Eq, Show)
instance DBRecord User where
  procureRecord = User

class Monad m => DB m where
  fetchRecord :: DBRecord a => Id a -> m (Either DBError a)
  insertRecord :: DBRecord a => a -> m (Either DBError (Id a))

class Monad m => HTTP m where
  sendRequest :: HTTPRequest -> m (Either HTTPError HTTPResponse)

class Monad m => Throw m where
  throwMessage :: String -> m a

useDBAndHTTP :: (DB m, HTTP m, DBRecord r) => r -> m (Either DBError r)
useDBAndHTTP record = do
  (Right (Id recordId)) <- insertRecord record
  (Right response) <- sendRequest $ GET ("/record/" ++ show recordId)
  fetchRecord $ Id (responseStatus response)

mkFixture "Fixture" [ts| DB, HTTP, Throw |]

-- At compile time, ensure the fixture type synonyms are generated.
fixturePure :: FixturePure
fixturePure = def :: Fixture (TestFixture Fixture () ())

fixtureLog :: FixtureLog log
fixtureLog = def :: Fixture (TestFixture Fixture log ())

fixtureState :: FixtureState state
fixtureState = def :: Fixture (TestFixture Fixture () s)

fixtureLogState :: FixtureLogState log state
fixtureLogState = def :: Fixture (TestFixture Fixture log state)

fixturePureT :: Monad m => FixturePureT m
fixturePureT = def :: Fixture (TestFixtureT Fixture () () m)

fixtureLogT :: Monad m => FixtureLogT log m
fixtureLogT = def :: Fixture (TestFixtureT Fixture log () m)

fixtureStateT :: Monad m => FixtureStateT state m
fixtureStateT = def :: Fixture (TestFixtureT Fixture () s m)

fixtureLogStateT :: Monad m => FixtureLogStateT log state m
fixtureLogStateT = def :: Fixture (TestFixtureT Fixture log state m)

-- ensure generation of empty fixtures works
mkFixture "EmptyFixture" []

-- ensure fixtures can be generated for partially applied multi-parameter typeclasses
class MultiParam e m | m -> e where
  firstParam :: m e
mkFixture "MultiParamFixture" [ts| MultiParam Bool |]

spec :: Spec
spec = do
  describe "mkFixture" $ do
    it "generates a fixture type that can be used to stub out methods" $ do
      let fixture = def
            { _fetchRecord = \_ -> return $ Right procureRecord
            , _insertRecord = \_ -> return $ Right (Id 42)
            , _sendRequest = \_ -> return $ Right (HTTPResponse 200)
            }
      let result = unTestFixture (useDBAndHTTP User) fixture
      result `shouldBe` Right User

    it "can handle partially applied multi parameter typeclasses" $ do
      let fixture = def { _firstParam = return True }
      unTestFixture firstParam fixture `shouldBe` True

  describe "handle throws" $ do
    it "capture a thrown error message" $ let
      throwFixture :: FixturePureT (Either String)
      throwFixture = def
        { _throwMessage = \msg -> lift (Left msg)
        }

      throwExample :: Throw m => m ()
      throwExample = throwMessage "error message"

      actual = unTestFixtureT throwExample throwFixture
      expected = Left "error message"
      in actual `shouldBe` expected


text:
<!--
  Warning: this is an automatically generated documentation.
  To change the contents of this file, edit the doc comments
  in /lib/IconTab.js
-->

# IconTab

A Tab with an icon.

## Props

### animationDuration

Type: `Number`

The duration of the animation between active and inactive.

Default: `160`

### animationEasing

Type: `Function`

The easing function of the animation between active and inactive.

Default: `easings.easeInOut`

### badgeAnimation

Type: `Function`

Defines the animation of the badge from active to inactive. Receives the
animation progress (`AnimatedValue` between 0 and 1), needs to return a
style object.
See also: https://facebook.github.io/react-native/docs/animations.html#interpolation

Default:
```js
progress => ({
  transform: [
    {
      scale: progress.interpolate({
        inputRange: [0, 1],
        outputRange: [0.9, 1]
      })
    }
  ]
})
```

### badgeSlotStyle

Type: `ViewPropTypes.style`

Extends the style of the badge's wrapping View.

### iconAnimation

Type: `Function`

Defines the animation of the icon from active to inactive. Receives the
animation progress (`AnimatedValue` between 0 and 1), needs to return a
style object.
See also: https://facebook.github.io/react-native/docs/animations.html#interpolation

Default:
```js
progress => ({
  transform: [
    {
      scale: progress.interpolate({
        inputRange: [0, 1],
        outputRange: [1, 1.2]
      })
    }
  ],
  opacity: progress.interpolate({
    inputRange: [0, 1],
    outputRange: [0.8, 1]
  })
})
```

### isActive
**Required.**
Type: `Boolean`

If `true`, the tab is visually active.

### renderBadge

Type: `Function`

The render prop to render the badge. Arguments: `({ isActive })`

### renderIcon
**Required.**
Type: `Function`

The render prop to render the icon. Arguments: `({ isActive })`

### showBadge

Type: `Boolean`

If `true`, the badge will be rendered.

Default: `false`

### style

Type: `ViewPropTypes.style`

Extends the style of the tab's view.


text:
// Generated by the protocol buffer compiler.  DO NOT EDIT!
// source: google/cloud/datafusion/v1beta1/v1beta1.proto

package com.google.cloud.datafusion.v1beta1;

public interface RemoveIamPolicyResponseOrBuilder
    extends
    // @@protoc_insertion_point(interface_extends:google.cloud.datafusion.v1beta1.RemoveIamPolicyResponse)
    com.google.protobuf.MessageOrBuilder {}


text:
package org.fusesource.mq.leveldb.util

/**
 *

 *

 *
 * @author Hiram Chirino
 */
object RetrySupport {

  def retry[T](log:Log, isStarted: ()=>Boolean, func: ()=>T): T = {
    import log._
    var error:Throwable = null
    var rc:Option[T] = None

    // We will loop until the tx succeeds.  Perhaps it's
    // failing due to a temporary condition like low disk space.
    while(!rc.isDefined) {

      try {
        rc = Some(func())
      } catch {
        case e:Throwable =>
          e.printStackTrace()
          if( error==null ) {
            warn(e, "DB operation failed. (entering recovery mode)")
          }
          error = e
      }

      if (!rc.isDefined) {
        // We may need to give up if the store is being stopped.
        if ( !isStarted() ) {
          throw error
        }
        Thread.sleep(1000)
      }
    }

    if( error!=null ) {
      info("DB recovered from failure.")
    }
    rc.get
  }

}


text:
import json

from emoticonvis.apps.corpus.models import *

class AttributeDict(dict):
    __getattr__ = dict.__getitem__
    __setattr__ = dict.__setitem__

lang_map = {
    "English": "En",
    "French": "Fr"
}

def create_a_participant_from_json(json_str, dataset_obj):
    """
    Given a dataset object, imports a participant from json string into
    the dataset.
    """
    data = AttributeDict(json.loads(json_str))
    participant = Participant(id=data.id, name=data.name, dataset=dataset_obj)
    participant.save()
    return participant

def update_full_participant_background_from_json(json_str, dataset_obj):
    """
    Given a dataset object, imports a participant from json string into
    the dataset.
    """
    data = AttributeDict(json.loads(json_str))
    participant = Participant.objects.get(id=data.id)
    participant.position = data.status
    if lang_map.get(data.lang):
        participant.language = lang_map[data.lang]
    participant.save()

    return participant

def update_participant_background_from_json(json_str, dataset_obj):
    """
    Given a dataset object, imports a participant from json string into
    the dataset.
    """
    data = AttributeDict(json.loads(json_str))
    participant = Participant.objects.get(id=data.id)
    participant.status = data.status
    if lang_map.get(data.lang):
        participant.language = lang_map[data.lang]
    participant.is_selected = True
    participant.save()

    return participant

def create_a_message_from_json(json_str, dataset_obj):
    """
    Given a dataset object, imports a participant from json string into
    the dataset.
    """
    data = AttributeDict(json.loads(json_str))

    message = Message(dataset=dataset_obj,
                      id=data.id, participant_id=data.participant_id,
                      idx=data.idx, session_id=data.session_id,
                      time=data.time, type=data.type,
                      text=data.message)
    message.save()
    return message

def create_an_emoticon_from_json(json_str, dataset_obj):
    """
    Given a dataset object, imports a participant from json string into
    the dataset.
    """
    data = AttributeDict(json.loads(json_str))
    emoticon = Emoticon(id=data.id, text=data.emoticon)
    emoticon.save()
    return emoticon

valence_map = {
    "positive": "P",
    "negative": "N",
    "neutral": "O",
}

def update_emoticon_valence_from_json(json_str, dataset_obj):
    """
    Given a dataset object, imports a participant from json string into
    the dataset.
    """
    data = AttributeDict(json.loads(json_str))
    emoticon = Emoticon.objects.get(id=data.id)
    emoticon.valence = valence_map[data.valence]
    emoticon.save()
    return emoticon

def create_a_lang_session_from_json(json_str, dataset_obj):
    """
    Given a dataset object, imports a participant from json string into
    the dataset.
    """
    data = AttributeDict(json.loads(json_str))
    lang_session = LanguageSession(dataset=dataset_obj, id=data.id,
                                   start_time=data.st_time, end_time=data.ed_time)
    lang_session.save()

    return lang_session

def update_a_lang_session_participant_from_json(json_str, dataset_obj):
    """
    Given a dataset object, imports a participant from json string into
    the dataset.
    """
    data = AttributeDict(json.loads(json_str))
    lang_session = LanguageSession.objects.get(id=data.lang_session_id)
    participant = Participant.objects.get(id=data.participant_id)
    lang_session.participants.add(participant)

    return lang_session

def update_a_lang_session_info_from_json(json_str, dataset_obj):
    """
    Given a dataset object, imports a participant from json string into
    the dataset.
    """
    data = AttributeDict(json.loads(json_str))
    lang_session = LanguageSession.objects.get(id=data.lang_session_id)
    lang_session.num_en = data.en_num
    lang_session.num_fr = data.fr_num
    lang_session.en_proportion = data.en_proportion
    lang_session.type = data["class"]
    lang_session.save()

    return lang_session

def update_message_lang_session_from_json(json_str, dataset_obj):
    """
    Given a dataset object, imports a participant from json string into
    the dataset.
    """
    data = AttributeDict(json.loads(json_str))
    message = Message.objects.get(id=data.point_id)
    message.lang_session_id = data.lang_session_id
    message.save()

    return message

def update_message_emotions_from_json(json_str, dataset_obj):
    """
    Given a dataset object, imports a participant from json string into
    the dataset.
    """
    data = AttributeDict(json.loads(json_str))
    message = Message.objects.get(id=data.mid)
    #emoticon = Emoticon.objects.get(id=data.eid)
    message.emoticons.add(data.eid)
    return message


text:
JsonActiveExchangesParser::JsonActiveExchangesParser()
{

}

JsonActiveExchangesParser::JsonActiveExchangesParser( const QJsonObject& a_rOther )
	: QJsonObject( a_rOther )
{
    ResolveExchangesArray();
}

void JsonActiveExchangesParser::ResolveExchangesArray()
{
	if ( find( "Result" ).value().isObject() )
	{
        if ( find( "Result" ).value().toObject().find( "ActiveExchanges" ).value().isArray() )
		{
            QJsonArray arrayOfExchangeDescriptors( find( "Result" ).value().toObject().find( "ActiveExchanges" ).value().toArray() );
            foreach( QJsonValue singleExchangeDescriptor, arrayOfExchangeDescriptors )
			{
                if ( singleExchangeDescriptor.isObject() )
				{
                    m_aActiveExchanges.append( JsonSingleActiveExchange( singleExchangeDescriptor.toObject() ) );
				}
			}
		}
	}
}

const QList<JsonSingleActiveExchange>& JsonActiveExchangesParser::GetExchanges() const
{
    return m_aActiveExchanges;
}

QList<JsonSingleActiveExchange>& JsonActiveExchangesParser::GetExchanges()
{
    return m_aActiveExchanges;
}

void JsonActiveExchangesParser::AddImagesToPool( QmlImageProvider* a_pImageProvider )
{
	if ( a_pImageProvider )
	{
        foreach( JsonSingleActiveExchange oExchange, m_aActiveExchanges )
		{
            a_pImageProvider->AddToImagePool( oExchange.getImageName(), oExchange.getExchangeImage() );
		}
	}
}


text:
package consulo.json.validation.descriptionByAnotherPsiElement;

import com.intellij.openapi.extensions.ExtensionPointName;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiElement;
import consulo.annotation.access.RequiredReadAction;
import consulo.json.validation.descriptor.JsonObjectDescriptor;
import consulo.ui.annotation.RequiredUIAccess;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;

/**
 * @author VISTALL
 * @since 12.11.2015
 */
public interface DescriptionByAnotherPsiElementProvider<T extends PsiElement>
{
	ExtensionPointName<DescriptionByAnotherPsiElementProvider<?>> EP_NAME = ExtensionPointName.create("consulo.javascript.jsonDescriptionByAnotherPsiElementProvider");

	@Nonnull
	String getId();

	@Nonnull
	String getPsiElementName();

	@Nonnull
	@RequiredReadAction
	String getIdFromPsiElement(@Nonnull T element);

	@Nullable
	@RequiredReadAction
	T getPsiElementById(@Nonnull String id, @Nonnull Project project);

	@RequiredUIAccess
	@Nullable
	T chooseElement(@Nonnull Project project);

	@RequiredReadAction
	boolean isAvailable(@Nonnull Project project);

	void fillRootObject(@Nonnull T psiElement, @Nonnull JsonObjectDescriptor root);
}


text:
const gulp = require('gulp');
const sourcemaps = require('gulp-sourcemaps');
const sass = require('gulp-sass');
const Path = require('./path');
const rename = require('gulp-rename');
const tildeImporter = require('node-sass-tilde-importer');

/**
 * @param {string} src
 * @param {string} outFile
 */
module.exports = (src, outFile) => {
    return gulp.src(src)
        .pipe(rename(outFile))
        .pipe(sourcemaps.init())
        .pipe(sass({
            outputStyle: 'compressed',
            importer: tildeImporter,
        }).on('error', sass.logError))
        .pipe(sourcemaps.write('.', {includeContent: false}))
        .pipe(gulp.dest(Path.bundle()));
};