text:
module Searchlogic
  module NamedScopes
    # Handles dynamically creating named scopes for columns. It allows you to do things like:
    #
    #   User.first_name_like("ben")
    #   User.id_lt(10)
    #
    # Notice the constants in this class, they define which conditions Searchlogic provides.
    #
    # See the README for a more detailed explanation.
    module ColumnConditions
      COMPARISON_CONDITIONS = {
        :equals => [:is, :eq],
        :does_not_equal => [:not_equal_to, :is_not, :not, :ne],
        :less_than => [:lt, :before],
        :less_than_or_equal_to => [:lte],
        :date_less_than_or_equal_to => [:date_lte],
        :greater_than => [:gt, :after],
        :greater_than_or_equal_to => [:gte],
      }

      WILDCARD_CONDITIONS = {
        :like => [:contains, :includes],
        :not_like => [:does_not_include],
        :begins_with => [:bw],
        :not_begin_with => [:does_not_begin_with],
        :ends_with => [:ew],
        :not_end_with => [:does_not_end_with]
      }

      BOOLEAN_CONDITIONS = {
        :null => [:nil],
        :not_null => [:not_nil],
        :empty => [],
        :blank => [],
        :not_blank => [:present]
      }

      CONDITIONS = {}

      # Add any / all variations to every comparison and wildcard condition
      COMPARISON_CONDITIONS.merge(WILDCARD_CONDITIONS).each do |condition, aliases|
        CONDITIONS[condition] = aliases
        CONDITIONS["#{condition}_any".to_sym] = aliases.collect { |a| "#{a}_any".to_sym }
        CONDITIONS["#{condition}_all".to_sym] = aliases.collect { |a| "#{a}_all".to_sym }
      end

      CONDITIONS[:equals_any] = CONDITIONS[:equals_any] + [:in]
      CONDITIONS[:does_not_equal_all] = CONDITIONS[:does_not_equal_all] + [:not_in]

      BOOLEAN_CONDITIONS.each { |condition, aliases| CONDITIONS[condition] = aliases }

      PRIMARY_CONDITIONS = CONDITIONS.keys
      ALIAS_CONDITIONS = CONDITIONS.values.flatten

      # Is the name of the method a valid condition that can be dynamically created?
      def condition?(name)
        super || column_condition?(name)
      end

      # We want to return true for any conditions that can be called, and while we're at it. We might as well
      # create the condition so we don't have to do it again.
      def respond_to?(*args)
        super || (self != ::ActiveRecord::Base && !self.abstract_class? && !create_condition(args.first).blank?)
      end

      private
        def column_condition?(name)
          return false if name.blank?
          !condition_details(name).nil? || boolean_condition?(name)
        end

        def boolean_condition?(name)
          column = columns_hash[name.to_s] || columns_hash[name.to_s.gsub(/^not_/, "")]
          column && column.type == :boolean
        end

        def method_missing(name, *args, &block)
          if create_condition(name)
            send(name, *args, &block)
          else
            super
          end
        end

        def condition_details(method_name)
          column_name_matcher = column_names.join("|")
          conditions_matcher = (PRIMARY_CONDITIONS + ALIAS_CONDITIONS).join("|")

          if method_name.to_s =~ /^(#{column_name_matcher})_(#{conditions_matcher})$/
            {:column => $1, :condition => $2}
          end
        end

        def create_condition(name)
          @conditions_already_tried ||= []
          return nil if @conditions_already_tried.include?(name.to_s)
          @conditions_already_tried << name.to_s

          if details = condition_details(name)
            if PRIMARY_CONDITIONS.include?(details[:condition].to_sym)
              create_primary_condition(details[:column], details[:condition])
            elsif ALIAS_CONDITIONS.include?(details[:condition].to_sym)
              create_alias_condition(details[:column], details[:condition])
            end

          elsif boolean_condition?(name)
            column = name.to_s.gsub(/^not_/, "")
            named_scope name, :conditions => {column => (name.to_s =~ /^not_/).nil?}
          end
        end

        def create_primary_condition(column_name, condition)
          column = columns_hash[column_name.to_s]
          column_type = column.type
          skip_conversion = skip_time_zone_conversion_for_attributes.include?(column.name.to_sym)
          match_keyword = self.connection.adapter_name == "PostgreSQL" ? "ILIKE" : "LIKE"

          scope_options = case condition.to_s
          when /^equals/
            scope_options(condition, column, "#{table_name}.#{column.name} = ?", :skip_conversion => skip_conversion)
          when /^does_not_equal/
            scope_options(condition, column, "#{table_name}.#{column.name} != ?", :skip_conversion => skip_conversion)
          when /^less_than_or_equal_to/
            scope_options(condition, column, "#{table_name}.#{column.name} <= ?", :skip_conversion => skip_conversion)
          when /^date_less_than_or_equal_to/
            scope_options(condition, column_type, "#{table_name}.#{column} <= addtime(timestamp(date(?)),'23:59:59')", :skip_conversion => skip_conversion)
          when /^less_than/
            scope_options(condition, column, "#{table_name}.#{column.name} < ?", :skip_conversion => skip_conversion)
          when /^greater_than_or_equal_to/
            scope_options(condition, column, "#{table_name}.#{column.name} >= ?", :skip_conversion => skip_conversion)
          when /^greater_than/
            scope_options(condition, column, "#{table_name}.#{column.name} > ?", :skip_conversion => skip_conversion)
          when /^like/
            scope_options(condition, column, "#{table_name}.#{column.name} #{match_keyword} ?", :skip_conversion => skip_conversion, :value_modifier => :like)
          when /^not_like/
            scope_options(condition, column, "#{table_name}.#{column.name} NOT #{match_keyword} ?", :skip_conversion => skip_conversion, :value_modifier => :like)
          when /^begins_with/
            scope_options(condition, column, "#{table_name}.#{column.name} #{match_keyword} ?", :skip_conversion => skip_conversion, :value_modifier => :begins_with)
          when /^not_begin_with/
            scope_options(condition, column, "#{table_name}.#{column.name} NOT #{match_keyword} ?", :skip_conversion => skip_conversion, :value_modifier => :begins_with)
          when /^ends_with/
            scope_options(condition, column, "#{table_name}.#{column.name} #{match_keyword} ?", :skip_conversion => skip_conversion, :value_modifier => :ends_with)
          when /^not_end_with/
            scope_options(condition, column, "#{table_name}.#{column.name} NOT #{match_keyword} ?", :skip_conversion => skip_conversion, :value_modifier => :ends_with)
          when "null"
            {:conditions => "#{table_name}.#{column.name} IS NULL"}
          when "not_null"
            {:conditions => "#{table_name}.#{column.name} IS NOT NULL"}
          when "empty"
            {:conditions => "#{table_name}.#{column.name} = ''"}
          when "blank"
            {:conditions => "#{table_name}.#{column.name} = '' OR #{table_name}.#{column.name} IS NULL"}
          when "not_blank"
            {:conditions => "#{table_name}.#{column.name} != '' AND #{table_name}.#{column.name} IS NOT NULL"}
          end

          named_scope("#{column.name}_#{condition}".to_sym, scope_options)
        end

        # This method helps cut down on defining scope options for conditions that allow *_any or *_all conditions.
        # Kepp in mind that the lambdas get cached in a method, so you want to keep the contents of the lambdas as
        # fast as possible, which is why I didn't do the case statement inside of the lambda.
        def scope_options(condition, column, sql, options = {})
          equals = !(condition.to_s =~ /^equals/).nil?
          does_not_equal = !(condition.to_s =~ /^does_not_equal/).nil?

          case condition.to_s
          when /_(any|all)$/
            any = $1 == "any"
            join_word = any ? " OR " : " AND "
            searchlogic_lambda(column.type, :skip_conversion => options[:skip_conversion]) { |*values|
              unless values.empty?
                if equals && any
                  has_nil = values.include?(nil)
                  values = values.flatten.compact
                  sql = attribute_condition("#{table_name}.#{column.name}", values)
                  subs = [values]

                  if has_nil
                    sql += " OR " + attribute_condition("#{table_name}.#{column.name}", nil)
                    subs << nil
                  end

                  {:conditions => [sql, *subs]}
                else
                  values.flatten!
                  values.collect! { |value| value_with_modifier(value, options[:value_modifier]) }

                  scope_sql = values.collect { |value| sql }.join(join_word)

                  {:conditions => [scope_sql, *values]}
                end
              else
                {}
              end
            }
          else
            searchlogic_lambda(column.type, :skip_conversion => options[:skip_conversion]) { |*values|
              values.collect! { |value| value_with_modifier(value, options[:value_modifier]) }

              new_sql = if does_not_equal && values == [nil]
                sql.gsub('!=', 'IS NOT')
              elsif equals && values == [nil]
                sql.gsub('=', 'IS')
              else
                sql
              end

              {:conditions => [new_sql, *values]}
            }
          end
        end

        def value_with_modifier(value, modifier)
          case modifier
          when :like
            "%#{value}%"
          when :begins_with
            "#{value}%"
          when :ends_with
            "%#{value}"
          else
            value
          end
        end

        def create_alias_condition(column_name, condition)
          primary_condition = primary_condition(condition)
          alias_name = "#{column_name}_#{condition}"
          primary_name = "#{column_name}_#{primary_condition}"
          if respond_to?(primary_name)
            (class << self; self; end).class_eval { alias_method alias_name, primary_name }
          end
        end

        # Returns the primary condition for the given alias. Ex:
        #
        #   primary_condition(:gt) => :greater_than
        def primary_condition(alias_condition)
          CONDITIONS.find { |k, v| k == alias_condition.to_sym || v.include?(alias_condition.to_sym) }.first
        end

        # Returns the primary name for any condition on a column. You can pass it
        # a primary condition, alias condition, etc, and it will return the proper
        # primary condition name. This helps simply logic throughout Searchlogic. Ex:
        #
        #   condition_scope_name(:id_gt) => :id_greater_than
        #   condition_scope_name(:id_greater_than) => :id_greater_than
        def condition_scope_name(name)
          if details = condition_details(name)
            if PRIMARY_CONDITIONS.include?(name.to_sym)
              name
            else
              "#{details[:column]}_#{primary_condition(details[:condition])}".to_sym
            end
          else
            nil
          end
        end
    end
  end
end


text:
require_relative 'array_like'

module Contentful
  # The includes hashes returned when include_level is specified
  class Includes
    include ArrayLike

    attr_accessor :items, :lookup

    def initialize(items = [], lookup = nil)
      self.items = items
      self.lookup = lookup || build_lookup
    end

    def self.from_response(json, raw = true)
      includes = if raw
                   json['items'].dup
                 else
                   json['items'].map(&:raw)
                 end

      %w[Entry Asset].each do |type|
        includes.concat(json['includes'].fetch(type, [])) if json.fetch('includes', {}).key?(type)
      end

      new includes || []
    end

    def find_link(link)
      key = "#{link['sys']['linkType']}:#{link['sys']['id']}"
      lookup[key]
    end

    # Override some of the features of Array to take into account the lookup
    # field in a performant way.

    # If the lookups are the same then these two objects are effectively the same
    def ==(other)
      object_id == other.object_id || lookup == other.lookup
    end

    def +(other)
      # If we're being asked to add to itself, just return without duplicating
      return self if self == other

      dup.tap do |copy|
        copy.items += other.items
        copy.lookup.merge!(other.lookup)
      end
    end

    def dup
      self.class.new(items.dup, lookup.dup)
    end

    def marshal_dump
      items
    end

    def marshal_load(array)
      self.items = array
      self.lookup = build_lookup
    end

    private

    def build_lookup
      items.each_with_object({}) do |i, h|
        key = "#{i['sys']['type']}:#{i['sys']['id']}"
        h[key] = i
      end
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
import { ChatBotUtil } from '../../src'

class Logic {
  static getStarted () {
    return [
      ChatBotUtil.textMessage(['Hi!', 'Hey there!'].any()),
      ChatBotUtil.textMessage(['How is life?', 'What\'s up?'].any(),
        ChatBotUtil.makeReplyButton('Great!', Logic.intro))
    ]
  }

  static intro () {
    return [
      ChatBotUtil.textMessage('That\'s good to hear!'),
      ChatBotUtil.textMessage('Want to know more about me?',
        ChatBotUtil.makeReplyButton('Sure!', Logic.about),
        ChatBotUtil.makeReplyButton('Nope', Logic.end))
    ]
  }

  static about () {
    return [
      ChatBotUtil.textMessage('I\'m a chatbot! 🤖'),
      ChatBotUtil.textMessage('And u?',
        ChatBotUtil.makeTextInputField('Send', 'Your name', Logic.entersName))
    ]
  }

  static entersName (value) {
    return [
      ChatBotUtil.textMessage(`Welcome ${value}!`,
        ChatBotUtil.makeReplyButton('Nice!', Logic.end)
      )
    ]
  }

  static end () {
    return [
      ChatBotUtil.textMessage('Ok, that\'s it for today'),
      ChatBotUtil.textMessage('Come back later! 😉',
        ChatBotUtil.makeReplyButton('Bye'))
    ]
  }
}

export default Logic


text:
import { types as t } from "@babel/core";
import type { PluginAPI, PluginObject } from "@babel/core";
import type { NodePath } from "@babel/traverse";
import nameFunction from "@babel/helper-function-name";
import splitExportDeclaration from "@babel/helper-split-export-declaration";
import {
  buildPrivateNamesNodes,
  buildPrivateNamesMap,
  transformPrivateNamesUsage,
  buildFieldsInitNodes,
  buildCheckInRHS,
} from "./fields";
import type { PropPath } from "./fields";
import { buildDecoratedClass, hasDecorators } from "./decorators";
import { injectInitialization, extractComputedKeys } from "./misc";
import { enableFeature, FEATURES, isLoose, shouldTransform } from "./features";
import { assertFieldTransformed } from "./typescript";

export { FEATURES, enableFeature, injectInitialization, buildCheckInRHS };

declare const PACKAGE_JSON: { name: string; version: string };

// Note: Versions are represented as an integer. e.g. 7.1.5 is represented
//       as 70000100005. This method is easier than using a semver-parsing
//       package, but it breaks if we release x.y.z where x, y or z are
//       greater than 99_999.
const version = PACKAGE_JSON.version
  .split(".")
  .reduce((v, x) => v * 1e5 + +x, 0);
const versionKey = "@babel/plugin-class-features/version";

interface Options {
  name: string;
  feature: number;
  loose?: boolean;
  inherits?: PluginObject["inherits"];
  manipulateOptions?: PluginObject["manipulateOptions"];
  api?: PluginAPI;
}

export function createClassFeaturePlugin({
  name,
  feature,
  loose,
  manipulateOptions,
  // @ts-ignore(Babel 7 vs Babel 8) TODO(Babel 8): Remove the default value
  api = { assumption: () => void 0 },
  inherits,
}: Options): PluginObject {
  const setPublicClassFields = api.assumption("setPublicClassFields");
  const privateFieldsAsProperties = api.assumption("privateFieldsAsProperties");
  const constantSuper = api.assumption("constantSuper");
  const noDocumentAll = api.assumption("noDocumentAll");

  if (loose === true) {
    const explicit = [];

    if (setPublicClassFields !== undefined) {
      explicit.push(`"setPublicClassFields"`);
    }
    if (privateFieldsAsProperties !== undefined) {
      explicit.push(`"privateFieldsAsProperties"`);
    }
    if (explicit.length !== 0) {
      console.warn(
        `[${name}]: You are using the "loose: true" option and you are` +
          ` explicitly setting a value for the ${explicit.join(" and ")}` +
          ` assumption${explicit.length > 1 ? "s" : ""}. The "loose" option` +
          ` can cause incompatibilities with the other class features` +
          ` plugins, so it's recommended that you replace it with the` +
          ` following top-level option:\n` +
          `\t"assumptions": {\n` +
          `\t\t"setPublicClassFields": true,\n` +
          `\t\t"privateFieldsAsProperties": true\n` +
          `\t}`,
      );
    }
  }

  return {
    name,
    manipulateOptions,
    inherits,

    pre(file) {
      enableFeature(file, feature, loose);

      if (!file.get(versionKey) || file.get(versionKey) < version) {
        file.set(versionKey, version);
      }
    },

    visitor: {
      Class(path, { file }) {
        if (file.get(versionKey) !== version) return;

        if (!shouldTransform(path, file)) return;

        if (path.isClassDeclaration()) assertFieldTransformed(path);

        const loose = isLoose(file, feature);

        let constructor: NodePath<t.ClassMethod>;
        const isDecorated = hasDecorators(path.node);
        const props: PropPath[] = [];
        const elements = [];
        const computedPaths: NodePath<t.ClassProperty | t.ClassMethod>[] = [];
        const privateNames = new Set<string>();
        const body = path.get("body");

        for (const path of body.get("body")) {
          if (
            // check path.node.computed is enough, but ts will complain
            (path.isClassProperty() || path.isClassMethod()) &&
            path.node.computed
          ) {
            computedPaths.push(path);
          }

          if (path.isPrivate()) {
            const { name } = path.node.key.id;
            const getName = `get ${name}`;
            const setName = `set ${name}`;

            if (path.isClassPrivateMethod()) {
              if (path.node.kind === "get") {
                if (
                  privateNames.has(getName) ||
                  (privateNames.has(name) && !privateNames.has(setName))
                ) {
                  throw path.buildCodeFrameError("Duplicate private field");
                }
                privateNames.add(getName).add(name);
              } else if (path.node.kind === "set") {
                if (
                  privateNames.has(setName) ||
                  (privateNames.has(name) && !privateNames.has(getName))
                ) {
                  throw path.buildCodeFrameError("Duplicate private field");
                }
                privateNames.add(setName).add(name);
              }
            } else {
              if (
                (privateNames.has(name) &&
                  !privateNames.has(getName) &&
                  !privateNames.has(setName)) ||
                (privateNames.has(name) &&
                  (privateNames.has(getName) || privateNames.has(setName)))
              ) {
                throw path.buildCodeFrameError("Duplicate private field");
              }

              privateNames.add(name);
            }
          }

          if (path.isClassMethod({ kind: "constructor" })) {
            constructor = path;
          } else {
            elements.push(path);
            if (
              path.isProperty() ||
              path.isPrivate() ||
              path.isStaticBlock?.()
            ) {
              props.push(path as PropPath);
            }
          }
        }

        if (process.env.BABEL_8_BREAKING) {
          if (!props.length) return;
        } else {
          if (!props.length && !isDecorated) return;
        }

        const innerBinding = path.node.id;
        let ref: t.Identifier;
        if (!innerBinding || path.isClassExpression()) {
          nameFunction(path);
          ref = path.scope.generateUidIdentifier("class");
        } else {
          ref = t.cloneNode(path.node.id);
        }

        // NODE: These three functions don't support decorators yet,
        //       but verifyUsedFeatures throws if there are both
        //       decorators and private fields.
        const privateNamesMap = buildPrivateNamesMap(props);
        const privateNamesNodes = buildPrivateNamesNodes(
          privateNamesMap,
          (privateFieldsAsProperties ?? loose) as boolean,
          file,
        );

        transformPrivateNamesUsage(
          ref,
          path,
          privateNamesMap,
          {
            privateFieldsAsProperties: privateFieldsAsProperties ?? loose,
            noDocumentAll,
            innerBinding,
          },
          file,
        );

        let keysNodes: t.Statement[],
          staticNodes: t.Statement[],
          instanceNodes: t.Statement[],
          pureStaticNodes: t.FunctionDeclaration[],
          wrapClass: (path: NodePath<t.Class>) => NodePath;

        if (!process.env.BABEL_8_BREAKING) {
          if (isDecorated) {
            staticNodes = pureStaticNodes = keysNodes = [];
            ({ instanceNodes, wrapClass } = buildDecoratedClass(
              ref,
              path,
              elements,
              file,
            ));
          } else {
            keysNodes = extractComputedKeys(path, computedPaths, file);
            ({ staticNodes, pureStaticNodes, instanceNodes, wrapClass } =
              buildFieldsInitNodes(
                ref,
                path.node.superClass,
                props,
                privateNamesMap,
                file,
                (setPublicClassFields ?? loose) as boolean,
                (privateFieldsAsProperties ?? loose) as boolean,
                (constantSuper ?? loose) as boolean,
                innerBinding,
              ));
          }
        } else {
          keysNodes = extractComputedKeys(path, computedPaths, file);
          ({ staticNodes, pureStaticNodes, instanceNodes, wrapClass } =
            buildFieldsInitNodes(
              ref,
              path.node.superClass,
              props,
              privateNamesMap,
              file,
              (setPublicClassFields ?? loose) as boolean,
              (privateFieldsAsProperties ?? loose) as boolean,
              (constantSuper ?? loose) as boolean,
              innerBinding,
            ));
        }

        if (instanceNodes.length > 0) {
          injectInitialization(
            path,
            constructor,
            instanceNodes,
            (referenceVisitor, state) => {
              if (!process.env.BABEL_8_BREAKING) {
                if (isDecorated) return;
              }
              for (const prop of props) {
                // @ts-expect-error: TS doesn't infer that prop.node is not a StaticBlock
                if (t.isStaticBlock?.(prop.node) || prop.node.static) continue;
                prop.traverse(referenceVisitor, state);
              }
            },
          );
        }

        // rename to make ts happy
        const wrappedPath = wrapClass(path);
        wrappedPath.insertBefore([...privateNamesNodes, ...keysNodes]);
        if (staticNodes.length > 0) {
          wrappedPath.insertAfter(staticNodes);
        }
        if (pureStaticNodes.length > 0) {
          wrappedPath
            .find(parent => parent.isStatement() || parent.isDeclaration())
            .insertAfter(pureStaticNodes);
        }
      },

      ExportDefaultDeclaration(path, { file }) {
        if (!process.env.BABEL_8_BREAKING) {
          if (file.get(versionKey) !== version) return;

          const decl = path.get("declaration");

          if (decl.isClassDeclaration() && hasDecorators(decl.node)) {
            if (decl.node.id) {
              // export default class Foo {}
              //   -->
              // class Foo {} export { Foo as default }
              splitExportDeclaration(path);
            } else {
              // @ts-expect-error Anonymous class declarations can be
              // transformed as if they were expressions
              decl.node.type = "ClassExpression";
            }
          }
        }
      },
    },
  };
}


text:
/*global define*/
///////////////////////////////////////////////////////////////////////////
// Copyright © 2015 Esri. All Rights Reserved.
//
// Licensed under the Apache License Version 2.0 (the 'License');
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an 'AS IS' BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
///////////////////////////////////////////////////////////////////////////
define({
  "units": {
    "miles": "Мили",
    "kilometers": "Километры",
    "feet": "Футы",
    "meters": "Метры"
  },
  "layerSetting": {
    "layerSettingTabTitle": "Параметры поиска",
    "buttonSet": "Установить",
    "selectLayersLabel": "Выбрать слой",
    "selectLayersHintText": "Подсказка: Используется для выборки полигонального слоя и связанного с ним точечного слоя.",
    "selectPrecinctSymbolLabel": "Выбрать символ для выделения полигона",
    "selectGraphicLocationSymbol": "Символ адреса или местоположения",
    "graphicLocationSymbolHintText": "Подсказка: Символ для найденных адресов или местоположений, по которым щелкнули",
    "precinctSymbolHintText": "Подсказка: Используется для отображения символа выбранных полигонов",
    "selectColorForPoint": "Выберите цвет для выделения точки",
    "selectColorForPointHintText": "Подсказка: Используется для отображения цвета подсветки выбранной точки"
  },
  "layerSelector": {
    "selectPolygonLayerLabel": "Выбрать полигональный слой",
    "selectPolygonLayerHintText": "Подсказка: Используется для выбора полигонального слоя.",
    "selectRelatedPointLayerLabel": "Выбрать точечный слой, связанный с полигональным слоем",
    "selectRelatedPointLayerHintText": "Подсказка: Используется для выборки точечного слоя, связанного с полигональным слоем",
    "polygonLayerNotHavingRelatedLayer": "Выбрать полигональный слой, у которого есть связанный точечный слой.",
    "errorInSelectingPolygonLayer": "Выбрать полигональный слой, у которого есть связанный точечный слой.",
    "errorInSelectingRelatedLayer": "Выберите точечный слой, связанный с полигональным слоем."
  },
  "routeSetting": {
    "routeSettingTabTitle": "Параметры путевых листов",
    "routeServiceUrl": "Сервис маршрутизации",
    "buttonSet": "Установить",
    "routeServiceUrlHintText": "Подсказка: Щелкните \"Установить\", чтобы перейти к выбору сервиса маршрутов сетевого анализа",
    "directionLengthUnit": "Единицы длины маршрутов",
    "unitsForRouteHintText": "Подсказка: Используется для отображения единиц измерения маршрутов",
    "selectRouteSymbol": "Выбрать символ отображения маршрута",
    "routeSymbolHintText": "Подсказка: Используется для отображения линейного символа маршрута",
    "routingDisabledMsg": "Для включения возможности построения путевых листов убедитесь, что построение маршрутов включено в элементе ArcGIS Online."
  },
  "networkServiceChooser": {
    "arcgislabel": "Добавить с ArcGIS Online",
    "serviceURLabel": "Добавить URL-адрес сервиса",
    "routeURL": "URL маршрута",
    "validateRouteURL": "Проверить",
    "exampleText": "Пример",
    "hintRouteURL1": "https://route.arcgis.com/arcgis/rest/services/World/Route/NAServer/",
    "hintRouteURL2": "https://route.arcgis.com/arcgis/rest/services/World/Route/NAServer/Route_World",
    "invalidRouteServiceURL": "Укажите допустимый сервис маршрутов",
    "rateLimitExceeded": "Превышен предел скорости. Попробуйте позже.",
    "errorInvokingService": "Неверное имя пользователя или пароль."
  },
  "symbolPickerPreviewText": "Просмотр:"
});


text:
ENV = test
REPORTER = spec
BIN = node_modules/.bin

# Use grep to run only tests with keywords:
# make test GREP=events
ifeq ($(GREP), )
	GREP_CMND =
else
 	GREP_CMND = --grep $(GREP)
endif

MOCHA-OPTS = --reporter $(REPORTER) \
		--require chai \
		--ui bdd \
		--recursive \
		--colors

test:
	@NODE_ENV=$(ENV) $(BIN)/mocha \
		$(MOCHA-OPTS) \
		$(GREP_CMND)
.PHONY: test

lint:
	npm run lint
.PHONY: lint

## Coverage:

test-coverage:
	@NODE_ENV=test $(BIN)/istanbul cover $(BIN)/_mocha -- $(MOCHA-OPTS)
.PHONY: test-coverage

check-coverage: test-coverage
	@$(BIN)/istanbul check-coverage --function 80 --branch 80 --statement 80 --lines 92
.PHONY: check-coverage


text:
// ==========================================================================
//  Squidex Headless CMS
// ==========================================================================
//  Copyright (c) Squidex UG (haftungsbeschraenkt)
//  All rights reserved. Licensed under the MIT license.
// ==========================================================================

using System.ComponentModel.DataAnnotations;
using Squidex.Domain.Apps.Core.HandleRules;
using Squidex.Domain.Apps.Core.Rules;
using Squidex.Infrastructure.Validation;

namespace Squidex.Extensions.Actions.Prerender;

[RuleAction(
    Title = "Prerender",
    IconImage = "<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'><path d='M2.073 17.984l8.646-5.36v-1.787L.356 17.325v1.318l10.363 6.488v-1.787zM29.927 17.984l-8.646-5.36v-1.787l10.363 6.488v1.318l-10.363 6.488v-1.787zM18.228 6.693l-6.276 19.426 1.656.548 6.276-19.426z'/></svg>",
    IconColor = "#2c3e50",
    Display = "Recache URL",
    Description = "Prerender a javascript website for bots.",
    ReadMore = "https://prerender.io")]
public sealed record PrerenderAction : RuleAction
{
    [LocalizedRequired]
    [Display(Name = "Token", Description = "The prerender token from your account.")]
    [Editor(RuleFieldEditor.Text)]
    [Formattable]
    public string Token { get; set; }

    [LocalizedRequired]
    [Display(Name = "Url", Description = "The url to recache.")]
    [Editor(RuleFieldEditor.Text)]
    public string Url { get; set; }
}


text:
package org.settings4j.test;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.apache.log4j.AppenderSkeleton;
import org.apache.log4j.spi.LoggingEvent;

/**
 * UnitTest Helper for Log4j Configuration tests.
 *
 * @author brabenetz
 */
public class InMemoryLog4jAppender extends AppenderSkeleton {

    private static final List<String> LINES = Collections.synchronizedList(new ArrayList<String>());

    /**
     * Returns the number of lines in this list. If this list contains more than <tt>Integer.MAX_VALUE</tt> elements, returns <tt>Integer.MAX_VALUE</tt>.
     *
     * @return the number of lines in this list.
     */
    public static int linesSize() {
        return LINES.size();
    }

    /**
     * Removes all of the lines from this list (optional operation). This list will be empty after this call returns (unless it throws an exception).
     */
    public static void linesClear() {
        LINES.clear();
    }

    /**
     * Returns the line at the specified position in this list.
     *
     * @param index
     *        index of line to return.
     * @return the line at the specified position in this list.
     * @throws IndexOutOfBoundsException
     *         if the index is out of range (index < 0 || index >= size()).
     */
    public static Object linesGet(final int index) throws IndexOutOfBoundsException {
        return LINES.get(index);
    }

    @Override
    public void close() {
        LINES.clear();
    }

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

    @Override
    protected void append(final LoggingEvent event) {
        final String message = this.layout.format(event);
        LINES.add(message);
        System.out.print("[InMemoryLog4jAppender] " + message);
    }

}


text:
package restapi

import (
	"encoding/json"
	"errors"
	"fmt"
	"sort"

	"github.com/gantsign/alt-galaxy/internal/rolesfile"
	"github.com/hashicorp/go-version"
)

type RoleQueryVersion struct {
	ReleaseDate string `json:"release_date"`
	Name        string
	Id          int
}

type RoleQuerySummaryFields struct {
	Versions []RoleQueryVersion `json:"versions"`
}

type RoleQueryResult struct {
	SummaryFields RoleQuerySummaryFields `json:"summary_fields"`
	GitHubUser    string                 `json:"github_user"`
	GitHubRepo    string                 `json:"github_repo"`
}

type RoleQueryResponse struct {
	Results []RoleQueryResult `json:"results"`
}

func ParseRoleQueryResponse(bytes []byte) (RoleQueryResponse, error) {
	var response RoleQueryResponse
	err := json.Unmarshal(bytes, &response)
	return response, err
}

func (result RoleQueryResult) LatestVersion() (string, error) {
	versions := result.SummaryFields.Versions
	if len(versions) == 0 {
		return "master", nil
	}
	libVersions := make([]*version.Version, len(versions))
	for i, rawVersion := range versions {
		ver, err := version.NewVersion(rawVersion.Name)
		if err != nil {
			return "", err
		}
		libVersions[i] = ver
	}

	sort.Sort(version.Collection(libVersions))
	latestVersion := libVersions[len(libVersions)-1]

	// The version library normalizes the version string (e.g. removing the 'v'
	// prefix and adding '.0's); loop through and return the raw version string.
	for _, rawVersion := range versions {
		ver, _ := version.NewVersion(rawVersion.Name)
		if latestVersion.Equal(ver) {
			return rawVersion.Name, nil
		}
	}

	// Should be unreachable
	return "", errors.New("Unable to find matching version")
}

func (restApi restApiImpl) QueryRolesByName(roleName rolesfile.RoleName) (RoleQueryResponse, error) {
	// https://galaxy.ansible.com/api/v1/roles/?owner__username=gantsign&name=apt
	url := fmt.Sprintf("%s/roles/?owner__username=%s&name=%s", restApi.baseUrl, roleName.UsernamePart, roleName.RoleNamePart)

	_, respBytes, err := restApi.restClient.JsonHttpGet(url)
	if err != nil {
		return RoleQueryResponse{}, fmt.Errorf("GET request to [%s] failed.\nCaused by: %s", url, err)
	}

	return ParseRoleQueryResponse(respBytes)
}


text:
docker rm -t coreos-pxe-swarm

set -e

docker build -t coreos-pxe-swarm .
echo "Starting image in interactive mode...";
docker run --net=host -e INTERFACE_BOOTSTRAP=br0 -it coreos-pxe-swarm

echo "Image closed...";


text:
Demo application that create/write (inside app folder)/move (to SD card)/open (with external application) a PDF file

This demo is about 4 tasks using Cordova/Phonegap:

1. Create a PDF file with makePDF in Javascript
2. Write a file in Cordova/Phonegap Application folder
3. Move a file into a SD Card, or a more accessible location for the user with Cordova/Phonegap
4. Open automatically a file from Cordova/Phonegap application

## Preparing the project
At this part we need to execute the creation commands, add the plugins, and finally add the required JS libraries:

```
cordova create createPdfWithPhonegap
cd createPdfWithPhonegap
cordova platform add android
cordova plugin add cordova-plugin-file
cordova plugin add cordova-plugin-file-transfer
cordova plugin add https://github.com/pwlin/cordova-plugin-file-opener2
```
Now, inside de www folder we need to add the pdfmake library:
```
npm install pdfmake
```
In order to make a simple HTML with the neccesary, I remove some lines that came with the original index.html, and add two simple buttons

```html
<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Security-Policy" content="default-src 'self' data: gap: https://ssl.gstatic.com 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *; img-src 'self' data: content:;">
    <meta name="format-detection" content="telephone=no">
    <meta name="msapplication-tap-highlight" content="no">
    <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width">
    <link rel="stylesheet" type="text/css" href="css/index.css">
    <title>Create PDF and Save it on Download folder</title>
</head>
<body>
<div>
    <input type="button" value="Make PDF" id="make_pdf" />
    <input type="button" value="View PDF" id="view_pdf" />
</div>
</body>
</html>
```

Course, it's neccesary add the JS Scripts just before de last body tag
```html
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript" src="js/index.js"></script>
<script type="text/javascript" src="node_modules/jquery/jquery.min.js"></script>
<script type="text/javascript" src="node_modules/pdfmake/build/pdfmake.js"></script>
<script type="text/javascript" src="node_modules/pdfmake/build/vfs_fonts.js"></script>
<script type="text/javascript" src="js/app.js"></script>
<script type="text/javascript" src="js/process_pdf.js"></script>
```

Fine, now it's time to view the code:

## Create a PDF file with makePDF in Javascript
I make this with [pdfmake library](https://github.com/bpampuch/pdfmake), wich is perfect for my purpose. Easy to use, and has a lot of features.

First, I create the "document definition" (DD). This part it's like this because it's possible to create a custom DD independent the creating process. Then, that DD is passing like parameter to the creation.
```javascript
var docDefinition = {
  content: [
    {
      table: {
        headerRows: 1,
        widths: [ '*', 'auto', 100, '*' ],
        body: [
          [ 'First C1', 'Second C', '7hird C', 'The last one' ],
          [ 'Value 1', 'Value 2', 'Value 3', 'Value 4' ],
          [ { text: 'Bold value', bold: true }, 'Val 2', 'Val 3', 'Val 4' ]
        ]
      }
    }
  ]
};
makePDF( docDefinition );
```

In the other file, the function makePDF has only one line, because we don't need nothing more, just make the file content, and convert it to a binary buffer. Then call the writeFile function to start to write in the disc our PDF file.
```javascript
function makePDF(dd){
    pdfMake.createPdf( dd ).getBuffer( onGetBuffer );
}

function onGetBuffer(buffer){
    FILE_CONTENT = buffer;
    writeFile();
}
```
Finally, the binary content is stored in *FILE_CONTENT* variable.

## Write a file in Cordova/Phonegap Application folder
[*File*](https://github.com/apache/cordova-plugin-file) plugin is required in this task.

Start calling writeFile function, which execute requestFileSystem function from window object. Really, *window.requestFileSystem* is not writing the file indeed, just verify that the deveice has enough resources for do that.

If success, we start to get the resource for stored our content, and it's here where we really are stocking the *FILE_CONTENT* varibale in a file.

```javascript
function writeFile() {
   var type = window.TEMPORARY;
   var size = 5*1024*1024;
   window.requestFileSystem(type, size, successCallback, errorCallback)
}

function successCallback(fs) {
  fs.root.getFile(FILE_NAME_LOCAL, {create: true}, onSuccessGetFile, errorCallback);
}

function onSuccessGetFile(fileEntry){
    fileEntry.createWriter(onCreateWriter, errorCallback);
}

function onCreateWriter(fileWriter){
    fileWriter.onwriteend = onWriteEnd;
    fileWriter.onerror = onErrorWritingFile;
    var blob = new Blob([FILE_CONTENT], {type: 'application/octet-binary'});
    fileWriter.write(blob);
}
```

It's important to know that the file is stored in a hidden file. Only the application can get it normally. Otherwise, we need to use the command line for access it.

If we want do that, we need the command line in order to get the hidden file using *adb* commands:
1. Start the shell
```
adb shell
```
Prompt change a little like **root@generic_x86:/ #**
2. Open like application
```
run-as com.gersonm.pdfreportcreator
```
If we don't know it, just see the *config.xml* file to get the application *id* at the begin of the file.
3. Stand on the cache folder. Here is where our file was stored.
```
cd cache
ls -l
```
Now, if we want extract that file, we need exit to the normal user prompt. It's necessary execute the *exit* command twice, and execute adb pull:
```
adb pull /sdcard/Download/file.pdf /path/to/computer/destination/
```
## Move a file into a SD Card, or a more accessible location for the user with Cordova/Phonegap
Normally, our file it's located in a folder application that is not accessible for a user, so in order to allow to the user get the file, we need to move it, or more exactly, copy it in, for example, the default Download folder in the device. Here is where [*File-Transfer*](https://github.com/apache/cordova-plugin-file-transfer) plugin is used.

The process begin when the file is finally stored, so, in this time we call the copy function sending two parameters:
1. Source indicate the path to the original file.
2. Target indicate the final destination in the device.

```javascript
function onWriteEnd(entry){
    var sourceFilePath = cordova.file.dataDirectory + "../cache/" + FILE_NAME_LOCAL;
    FILE_TARGET_PATH = cordova.file.externalRootDirectory + DESTINATION_FOLDER + FILE_NAME;
    copyFile(sourceFilePath, FILE_TARGET_PATH);
}

function copyFile(source, target){
    var ft = new FileTransfer();
    ft.download(source, target, onCopySuccess, onCopyError);
}
```
## Open automatically a file from Cordova/Phonegap application
When copy is finished, we are ready to open the file, and that operation is possible (in this demo) thanks to [*fileOpener2*](https://github.com/pwlin/cordova-plugin-file-opener2) plugin. This one is too easy to implement:

```javascript
function openFile(){
    cordova.plugins.fileOpener2.open( FILE_TARGET_PATH, 'application/pdf',
        {
            error : onErrorOpening,
            success : onSuccessOpening
        }
    );
}
```
Normally, if *onErrorOpening* is triggered, that's because the device has not an PDF viewer application.

And that's all. Code is more explained by comments.

I hope it can be useful.

## PS
This was my work of the last week, reading, searching, experimenting, etc. I visited so many sites, viewed a lot of code and making a lot mistakes, but there are a few links where I got the main code for do the tutorial. Thanks.

- [pdfmake - Get PDF like jsPDF function output()](http://stackoverflow.com/questions/28824723/pdfmake-get-pdf-like-jspdf-function-output)
- [Copy file from application folder to root folder in JQM/Phonegap App?](http://stackoverflow.com/questions/29479060/copy-file-from-application-folder-to-root-folder-in-jqm-phonegap-app)
- [Cordova - File System](https://www.tutorialspoint.com/cordova/cordova_file_system.htm)
- [Opening PDF in Phonegap (Android)](http://stackoverflow.com/questions/31492589/opening-pdf-in-phonegap-android)


text:
/**
    @file

    The abstract string validator interface.

    @author Emil Maskovsky
*/

#ifndef BRACKETS_PUZZLE_I_VALIDATOR_HPP_2001410251817
#define BRACKETS_PUZZLE_I_VALIDATOR_HPP_2001410251817

// standard library
#include <string>

namespace BracketPuzzle
{

/**
    The abstract string validator interface.
*/
class IValidator
{

public:

    /**
        The destructor.
    */
    virtual ~IValidator()
    {
    }

    /**
        Validate the input string.

        @param [in] str The input string.

        @return bool
            Returns @c true if the string is well formed (validated),
            @c false otherwise.
    */
    virtual bool validate(
        const std::string & str) const = 0;

}; // class IValidator

} // namespace BracketPuzzle

#endif // BRACKETS_PUZZLE_I_VALIDATOR_HPP_2001410251817

/* EOF */


text:
<!doctype html>

        <meta charset="utf-8">
        <meta http-equiv="x-ua-compatible" content="ie=edge">
        <title></title>
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <link rel="apple-touch-icon" href="apple-touch-icon.png">

        <link rel="stylesheet" href="css/normalize.css">
        <link rel="stylesheet" href="css/materialize.min.css">
        <link rel="stylesheet" href="css/flexboxgrid.min.css">
        <link rel="stylesheet" href="css/competidores1.css">

        PETROBOWL

Resultados

UDO MONAGAS

1-1

2:00h

21 Abr 2017

SPE

		<button class="butonPulsar btn " type="submit" name="action">
    		Responder
  		</button>


text:
'use strict';

const events = require('events');
const binding = require('./binding');
const errors = require('./errors');

/**
 * @private
 */
class SearchExecutor {
  constructor(conn) {
    this._conn = conn;
  }

  /**
   *
   * @param {string} indexName
   * @param {string} query
   * @param {Object|Array} params
   * @param {Object} [options]
   * @param {number} [options.skip]
   * @param {number} [options.limit]
   * @param {boolean} [options.explain]
   * @param {Object} [options.highlight]
   * @param {HighlightStyle} [options.highlight.style]
   * @param {string[]} [options.highlight.fields]
   * @param {string[]} [options.fields]
   * @param {SearchFacet[]} [options.facets]
   * @param {string|SearchSort} [options.sort]
   * @param {boolean} [options.disableScoring]
   * @param {SearchScanConsistency} [options.consistency]
   * @param {MutationState} [options.consistentWith]
   * @param {number} [options.timeout]
   * @param {SearchQueryCallback} [callback]
   *
   * @private
   */
  query(indexName, query, options) {
    var queryObj = {};
    var queryObjCtl = {};
    var queryFlags = 0;

    queryObj.indexName = indexName;
    queryObj.query = query;

    if (options.skip !== undefined) {
      queryObj.from = options.skip;
    }
    if (options.limit !== undefined) {
      queryObj.size = options.limit;
    }
    if (options.explain) {
      queryObj.explain = !!options.explain;
    }
    if (options.highlight) {
      queryObj.highlight = options.highlight;
    }
    if (options.fields) {
      queryObj.fields = options.fields;
    }
    if (options.facets) {
      queryObj.facets = options.facets;
    }
    if (options.sort) {
      queryObj.sort = options.sort;
    }
    if (options.disableScoring) {
      queryObj.score = 'none';
    }
    if (options.consistency) {
      queryObjCtl.consistency = {
        level: options.consistency,
      };
    }
    if (options.consistentWith) {
      if (queryObjCtl.consistency) {
        throw new Error(
          'cannot specify consistency and consistentWith together'
        );
      }

      queryObjCtl.consistency = {
        level: 'at_plus',
        vectors: options.consistentWith.toObject(),
      };
    }
    if (options.timeout) {
      queryObjCtl.timeout = options.timeout;
    }

    // Only inject the `ctl` component if there are ctl's.
    if (Object.keys(queryObjCtl).length > 0) {
      queryObj.ctl = queryObjCtl;
    }

    var queryData = JSON.stringify(queryObj);

    var emitter = new events.EventEmitter();

    this._conn.searchQuery(
      queryData,
      queryFlags,
      options.timeout * 1000,
      (err, flags, data) => {
        if (!(flags & binding.LCBX_RESP_F_NONFINAL)) {
          if (err) {
            err = errors.wrapLcbErr(err);

            emitter.emit('error', err);
            emitter.emit('end');
            return;
          }

          var meta = JSON.parse(data);
          emitter.emit('meta', meta);
          emitter.emit('end');

          return;
        }

        if (err) {
          err = errors.wrapLcbErr(err);

          emitter.emit('error', err);
          return;
        }

        var row = JSON.parse(data);
        emitter.emit('row', row);
      }
    );

    return emitter;
  }
}

module.exports = SearchExecutor;


text:
const LEVELS = ['log', 'trace', 'debug', 'info', 'warn', 'error'];
let logLevel = 0;

export function LoggerProvider() {
  // DDO
  return { setLogLevel, $get };

  // Implementation

  function $get($log) {
    'ngInject';

    // Interface
    const service = {};
    // Enable correct log level
    LEVELS.forEach(function onEachLogLevel(level) {
      service[level] = (LEVELS.indexOf(level) >= logLevel) ? $log[level] : angular.noop;
    });
    return service;
  }

  function setLogLevel(level) {
    logLevel = LEVELS.indexOf(level);
  }
}

module.exports = LoggerProvider;


text:
namespace g{namespace Fuse{namespace Scripting{struct NativeEvent;}}}
namespace g{namespace Uno{namespace Collections{struct Queue;}}}

namespace g{
namespace Fuse{
namespace Scripting{

// public sealed class NativeEvent :475
// {
::g::Fuse::Scripting::NativeProperty_type* NativeEvent_typeof();
void NativeEvent__ctor_4_fn(NativeEvent* __this, uString* name, bool* queueEventsBeforeHandlerIsSet);
void NativeEvent__DispatchQueue_fn(NativeEvent* __this);
void NativeEvent__GetProperty_fn(NativeEvent* __this, ::g::Fuse::Scripting::Function** __retval);
void NativeEvent__New4_fn(uString* name, bool* queueEventsBeforeHandlerIsSet, NativeEvent** __retval);
void NativeEvent__RaiseAsync_fn(NativeEvent* __this, uArray* args);
void NativeEvent__SetProperty1_fn(NativeEvent* __this, ::g::Fuse::Scripting::Function* function);

struct NativeEvent : ::g::Fuse::Scripting::NativeProperty
{
    uStrong< ::g::Uno::Collections::Queue*> _eventArgsQueue;
    uStrong< ::g::Fuse::Scripting::Function*> _jsFunction;
    bool _queueEventsBeforeEvaluation;

    void ctor_4(uString* name, bool queueEventsBeforeHandlerIsSet);
    void DispatchQueue();
    void RaiseAsync(uArray* args);
    static NativeEvent* New4(uString* name, bool queueEventsBeforeHandlerIsSet);
};
// }

}}} // ::g::Fuse::Scripting


text:
from collections import deque
import logging
import nghttp2
import asynqp
import asyncio
import urllib
import io
from fnmatch import fnmatch
from urllib.parse import urlparse, parse_qs

LOG = logging.getLogger(__name__)

def create(config):
    return Controller(config)

def _topic_translation(key, translation=str.maketrans('/', '.')):
    return key.translate(translation)

class Serialiser(object):
    pass

class TextEventStream(Serialiser):
    @staticmethod
    def content_type():
        return 'text/event-stream'

    @staticmethod
    def serialise(message):
        body_in = io.BytesIO(message.body)
        out = bytearray()
        for line in body_in:
            out.extend(b'data: ')
            out.extend(line)
            out.extend(b"\n")
        out.extend(b"\n")
        return out

class PlainTextStream(Serialiser):
    @staticmethod
    def content_type():
        return 'text/plain'

    @staticmethod
    def serialise(message):
        return b''.join([message.body, b"\n"])

def create_serialiser(accept_string):
    media_ranges = { media_range: { key: value for key, value in map(lambda x: x.split('=', 1), param_list) } for media_range, *param_list in map(lambda x: map(lambda y: y.strip(), x.split(';')), accept_string.decode('ascii').split(',')) }

    for media_range, _ in sorted(media_ranges.items(), key=lambda x: float(x[1].get('q', 1.0)), reverse=True):
        # if fnmatch(TextEventStream.content_type(), media_range):
        return TextEventStream
        #elif fnmatch(PlainTextStream.content_type(), media_range):
        #    return PlainTextStream

class Controller(object):
    def __init__(self, config):
        self._config = config
        self._sessions = {}

    @property
    def config(self):
        return self._config

    def session(self, request):
        try:
            return self._sessions[request.session_id]
        except KeyError:
            session = Session(self.config, request)
            self._sessions[request.session_id] = session
            return session

    def post(self, request, start_response):
        return self.session(request).publish(request, start_response)

    def get(self, request, start_response):
        accept = next(i for i in request.headers if i[0] == b'accept')
        accept = accept[1] if not accept is None else b'text/event-stream'
        serialiser = create_serialiser(accept)

        start_response(200, [('content-type', serialiser.content_type()), ('cache-control', 'no-cache')])
        return self.session(request).subscribe(request, serialiser)

class Session(object):
    def __init__(self, config, request):
        self._config = config
        self._connection = None
        self._channel = None
        self._exchange = None
        self.setup_done = asyncio.async(self.setup())

    @asyncio.coroutine
    def setup(self):
        LOG.debug("Connecting to %s", self._config)
        self._connection = yield from asynqp.connect(host=self._config['host'],
                                                     username=self._config['username'],
                                                     password=self._config['password'],
                                                     virtual_host=self._config['virtual_host'])
        self._channel = yield from self._connection.open_channel()
        exchange_type = self._config.get('exchange_type', 'topic')
        self._exchange = yield from self._channel.declare_exchange(self._config.get('exchange_name', "amq.{}".format(exchange_type)),
                                                                   exchange_type, durable=False, auto_delete=False)

    @property
    def config(self):
        return self._config

    @property
    def connection(self):
        return self._connection

    @property
    def channel(self):
        return self._channel

    @property
    def exchange(self):
        return self._exchange

    def subscribe(self, request, serialiser):
        return Subscription(self, request, serialiser)

    def publish(self, request, start_response):
        return Sender(self, request, start_response)

class Subscription(object):
    def __init__(self, session, request, serialiser):
        self.session = session
        self.request = request
        self.serialiser = serialiser
        self.request.eof = False
        self.buf = deque()
        self.queue = None
        self.binding = None
        self.consumer = None
        asyncio.async(self.setup())

    def __call__(self, n):
        items = len(self.buf)
        message = self.buf.popleft() if items > 0 else None

        if not message and not self.request.eof:
            return None, nghttp2.DATA_DEFERRED
        else:
            if items > 1:
                self.request.resume()
            data = self.serialiser.serialise(message)
            message.ack()
            return data, nghttp2.DATA_EOF if self.request.eof else nghttp2.DATA_OK

    @asyncio.coroutine
    def setup(self):
        yield from self.session.setup_done
        self.queue = yield from self.session.channel.declare_queue(str(self.request.session_id), durable=False, auto_delete=False, arguments={'x-expires': 5*60*1000})
        subscription = _topic_translation(self.session.config.get('subscription', urllib.parse.unquote(self.request.match.get('subscription', '#'))))

        LOG.debug('Subscribing to %s', subscription)
        self.binding = yield from self.queue.bind(self.session.exchange, subscription)
        self.consumer = yield from self.queue.consume(self.consume)

    def consume(self, message):
        self.buf.append(message)
        self.request.resume()

    @asyncio.coroutine
    def close(self):
        if not self.binding is None:
            yield from self.binding.unbind()
        if not self.consumer is None:
            yield from self.consumer.cancel()
        if not self.queue is None:
            yield from self.queue.delete(if_unused=False, if_empty=False)

    def on_request_done(self):
        pass

class Sender(object):
    def __init__(self, session, request, start_response):
        self.start_response = start_response
        self.session = session
        self.request = request
        self.response = None
        self.data = io.BytesIO()

    def __call__(self, n):
        if self.response is None:
            return None, nghttp2.DATA_DEFERRED
        else:
            return self.response, nghttp2.DATA_EOF

    @asyncio.coroutine
    def publish(self):
        yield from self.session.setup_done
        params = parse_qs(urlparse(self.request.path).query)
        data = self.data.getvalue()
        try:
            content_type = next(i for i in self.request.headers if i[0] == b'content-type')
            if content_type:
                content_type = content_type[1]
            else:
                content_type = 'text/plain'
            message = asynqp.Message(data, content_type=content_type)
            key = self.session.config.get('routing_key', params.get(b'k', ['default'])[0])
            self.session.exchange.publish(message, key, mandatory=False)
            self.start_response(200, [('content-type', 'application/json'), ('cache-control', 'no-cache')])
            self.response = b'{}'
            self.request.resume()
        except KeyError as e:
            self.start_response(500, [('content-type', 'application/json'), ('cache-control', 'no-cache')])
            self.response = "{'e': {} }".format(e)
            self.request.resume()

    def on_data(self, data):
        self.data.write(data)

    def on_request_done(self):
        asyncio.async(self.publish())


text:
from __future__ import unicode_literals

from django.contrib import admin
from django.db.models.signals import pre_delete
from django.dispatch import receiver
from django.http import HttpResponse, HttpResponseNotFound
from django.shortcuts import get_object_or_404, render_to_response
from django.template import RequestContext
from django.utils.html import format_html
from django.utils.translation import ugettext_lazy as _

from reviewboard.accounts.admin import fix_review_counts
from reviewboard.admin.server import get_server_url
from reviewboard.scmtools.forms import RepositoryForm
from reviewboard.scmtools.models import Repository, Tool

class RepositoryAdmin(admin.ModelAdmin):
    list_display = ('name', 'path', 'hosting', '_visible', 'inline_actions')
    list_select_related = ('hosting_account',)
    search_fields = ('name', 'path', 'mirror_path', 'tool__name')
    raw_id_fields = ('local_site',)
    ordering = ('name',)
    fieldsets = (
        (_('General Information'), {
            'fields': ('name', 'visible',),
            'classes': ('wide',),
        }),
        (_('Repository Hosting'), {
            'fields': (
                'hosting_type',
                'hosting_url',
                'hosting_account',
                'hosting_account_username',
                'hosting_account_password',
                'hosting_account_two_factor_auth_code',
            ),
            'classes': ('wide',),
        }),
        (RepositoryForm.REPOSITORY_INFO_FIELDSET, {
            'fields': (
                'tool',
                'repository_plan',
                'path',
                'mirror_path',
                'raw_file_url',
                'username',
                'password',
                'use_ticket_auth',
            ),
            'classes': ('wide',),
        }),
        (RepositoryForm.SSH_KEY_FIELDSET, {
            'fields': (
                'associate_ssh_key',
            ),
            'classes': ('wide',),
        }),
        (RepositoryForm.BUG_TRACKER_FIELDSET, {
            'fields': (
                'bug_tracker_use_hosting',
                'bug_tracker_type',
                'bug_tracker_hosting_url',
                'bug_tracker_plan',
                'bug_tracker_hosting_account_username',
                'bug_tracker',
            ),
            'classes': ('wide',),
        }),
        (_('Access Control'), {
            'fields': ('public', 'users', 'review_groups'),
            'classes': ('wide',),
        }),
        (_('Advanced Settings'), {
            'fields': ('encoding',),
            'classes': ('wide', 'collapse'),
        }),
        (_('Internal State'), {
            'description': _('
This is advanced state that should not be '
                             'modified unless something is wrong.
'),
            'fields': ('local_site', 'hooks_uuid', 'extra_data'),
            'classes': ['collapse'],
        }),
    )
    form = RepositoryForm

    def hosting(self, repository):
        if repository.hosting_account_id:
            account = repository.hosting_account

            if account.service:
                return '%s@%s' % (account.username, account.service.name)

        return ''

    def inline_actions(self, repository):
        s = ['
']

        if repository.hosting_account:
            service = repository.hosting_account.service

            if service and service.has_repository_hook_instructions:
                s.append(format_html(
                    '[{1}]',
                    repository.pk, _('Hooks')))

        s.append(format_html(
            '[{1}]',
            repository.pk, _('RBTools Setup')))

        s.append('
')

        return ''.join(s)
    inline_actions.allow_tags = True
    inline_actions.short_description = ''

    def _visible(self, repository):
        return repository.visible
    _visible.boolean = True
    _visible.short_description = _('Show')

    def get_urls(self):
        from django.conf.urls import patterns

        return patterns(
            '',

            (r'^(?P<repository_id>[0-9]+)/hooks-setup/$',
             self.admin_site.admin_view(self.hooks_setup)),

            (r'^(?P<repository_id>[0-9]+)/rbtools-setup/$',
             self.admin_site.admin_view(self.rbtools_setup)),
        ) + super(RepositoryAdmin, self).get_urls()

    def hooks_setup(self, request, repository_id):
        repository = get_object_or_404(Repository, pk=repository_id)

        if repository.hosting_account:
            service = repository.hosting_account.service

            if service and service.has_repository_hook_instructions:
                return HttpResponse(service.get_repository_hook_instructions(
                    request, repository))

        return HttpResponseNotFound()

    def rbtools_setup(self, request, repository_id):
        repository = get_object_or_404(Repository, pk=repository_id)

        return render_to_response(
            'admin/scmtools/repository/rbtools_setup.html',
            RequestContext(request, {
                'repository': repository,
                'reviewboard_url': get_server_url(
                    local_site=repository.local_site),
            }))

@receiver(pre_delete, sender=Repository,
          dispatch_uid='repository_delete_reset_review_counts')
def repository_delete_reset_review_counts(sender, instance, using, **kwargs):
    """Reset review counts in the dashboard when deleting repository objects.

    There doesn't seem to be a good way to get notified on cascaded delete
    operations, which means that when deleting a repository, there's no
    good way to update the review counts that are shown to users. This
    method clears them out entirely to be regenerated. Deleting
    repositories should be a very rare occurrance, so it's not too
    upsetting to do this.
    """
    fix_review_counts()

class ToolAdmin(admin.ModelAdmin):
    list_display = ('__str__', 'class_name')

admin.site.register(Repository, RepositoryAdmin)
admin.site.register(Tool, ToolAdmin)


text:
namespace CodeHub.Web.ViewModels.Comment
{
    using System.ComponentModel.DataAnnotations;
    using System.Web.Mvc;

    using CodeHub.Data.Models;
    using CodeHub.Web.Infrastructure.Mapping;

    public class BaseCommentViewModel : IMapFrom<Comment>
    {
        [Required]
        [AllowHtml]
        [MinLength(5)]
        [UIHint("BootstrapTextArea")]
        [Display(Name = "Enter your comment")]
        public string Content { get; set; }
    }
}


text:
extern "Rust" {
    fn miri_backtrace_size(flags: u64) -> usize;
    fn miri_get_backtrace(flags: u64, buf: *mut *mut ());
    fn miri_resolve_frame_names(ptr: *mut (), flags: u64, name_buf: *mut u8, filename_buf: *mut u8);
}

fn main() {
    unsafe {
        let mut buf = vec![std::ptr::null_mut(); miri_backtrace_size(0)];

        miri_get_backtrace(1, buf.as_mut_ptr());

        // miri_resolve_frame_names will error from an invalid backtrace before it will from invalid flags
        miri_resolve_frame_names(buf[0], 2, std::ptr::null_mut(), std::ptr::null_mut()); //~ ERROR:  unsupported operation: unknown `miri_resolve_frame_names` flags 2
    }
}


text:
package lt.itdbaltics.camel.component.existdb;

import org.xmldb.api.base.Collection;

public class QueryServiceFactory {
    public QueryService createQueryService(Collection collection, QueryServiceType serviceType) {
        return new QueryService(collection, serviceType);
    }
}


text:
namespace blink {

// Maximum number of ad components a bid in an auction can have. When a renderer
// retrieves the component ad URLs from an auction, the API acts as if exactly
// this number of ad components were returned by padding the returned list with
// additional obfuscated URN URLs that map to about:blank, to avoid creating a
// side channel from a bidder worklet to the main ad.
constexpr size_t kMaxAdAuctionAdComponents = 20;

}  // namespace blink

#endif  // THIRD_PARTY_BLINK_PUBLIC_COMMON_INTEREST_GROUP_AD_AUCTION_CONSTANTS_H_


text:
package cmd

import (
	"fmt"
	"regexp"
	"sort"

	"strings"

	"github.com/akolb1/sentrytool/sentryapi"
	"github.com/spf13/cobra"
	"github.com/spf13/viper"
)

// listCmd represents the list command
var roleListCmd = &cobra.Command{
	Use:     "list",
	Aliases: []string{"ls"},
	Short:   "list roles",
	Long: `list all roles.
If optional '-m regexp' flag is specified, only list roles matching regexp.
If '-g group' flag is specifiedm only list roles for the speecified group.
In verbose mode prints groups for each role.

If roles are provided in arguments, list those roles, otherwise list all matching roles.

Example:

  sentrytool role list -v
  sentrytool role list -v role1 role2
  sentrytool role list -g group1

`,
	Run: listRoles,
}

type roleGroupMap map[string][]string

// getRoles returns a list of Sentry roles from the server
// if useMatcher is true, filters result according to '-m' flag
// If any roles are specified in args, use them
func getRoles(cmd *cobra.Command,
	args []string,
	useMatcher bool,
	client sentryapi.ClientAPI) ([]string, roleGroupMap, error) {
	group, _ := cmd.Flags().GetString(groupOpt)
	roles, roleGroups, err := client.ListRoleByGroup(group)
	if err != nil {
		return nil, nil, err
	}
	sort.Strings(roles)

	var matchRegex *regexp.Regexp

	if useMatcher {
		match, _ := cmd.Flags().GetString(matchOpt)
		if match != "" {
			r, err := regexp.Compile(match)
			if err != nil {
				return nil, nil,
					fmt.Errorf("invalid match expression: %s", err)
			}
			matchRegex = r
		}
	}

	result := make([]string, 0, len(roles))
	roleResult := make(roleGroupMap)

	for _, role := range roleGroups {
		// If match is specified, filter by matches
		if matchRegex != nil && !matchRegex.MatchString(role.Name) {
			continue
		}
		result = append(result, role.Name)
		roleResult[role.Name] = role.Groups
	}

	// If there are any roles on the command line, remove any roles that are
	// not mentioned there
	if len(args) == 0 {
		return result, roleResult, nil
	}

	result = make([]string, 0, len(args))
	roleMap := make(roleGroupMap)

	for _, name := range args {
		if r, ok := roleResult[name]; ok {
			result = append(result, name)
			roleMap[name] = r
		}
	}
	return result, roleMap, nil
}

func listRoles(cmd *cobra.Command, args []string) {
	client, err := getClient()
	if err != nil {
		fmt.Println(err)
		return
	}
	defer client.Close()

	roles, roleGroups, err := getRoles(cmd, args, true, client)
	if err != nil {
		fmt.Println(toAPIError(err))
		return
	}

	verbose := viper.GetBool(verboseOpt)

	for _, r := range roles {
		if !verbose {
			fmt.Println(r)
			continue
		}
		groups := strings.Join(roleGroups[r], ",")
		fmt.Printf("%s: (%s)\n", r, groups)
	}
}

func init() {
	roleListCmd.Flags().StringP(matchOpt, "m", "", "regexp matching role")
	roleListCmd.Flags().StringP(groupOpt, "g", "", "group for a role")
	roleCmd.AddCommand(roleListCmd)
}


text:
Home

Tables

Managed Tables

Managed Tables header small text goes here...

jQuery File Upload

                            <form id="fileupload" action="#" method="POST" enctype="multipart/form-data">

                                            Add files...
                                            <input type="file" name="files[]" multiple>

                                        <button type="submit" class="btn btn-primary start">

                                            Start upload
                                        </button>
                                        <button type="reset" class="btn btn-warning cancel">

                                            Cancel upload
                                        </button>
                                        <button type="button" class="btn btn-danger delete">

                                            Delete
                                        </button>

                            </form>

Demo Notes

The maximum file size for uploads in this demo is 5 MB (default file size is unlimited).

Only image files (JPG, GIF, PNG) are allowed in this demo (by default there is no file type restriction).

Uploaded files will be deleted automatically after 5 minutes (demo setting).

                                ‹
                                ›
                                ×

Color Theme

Header Styling

                        <select name="header-styling" class="form-control input-sm">
                            <option value="1">default</option>
                            <option value="2">inverse</option>
                        </select>

Header

                        <select name="header-fixed" class="form-control input-sm">
                            <option value="1">fixed</option>
                            <option value="2">default</option>
                        </select>

Sidebar Styling

                        <select name="sidebar-styling" class="form-control input-sm">
                            <option value="1">default</option>
                            <option value="2">grid</option>
                        </select>

Sidebar

                        <select name="sidebar-fixed" class="form-control input-sm">
                            <option value="1">fixed</option>
                            <option value="2">default</option>
                        </select>

Sidebar Gradient

                        <select name="content-gradient" class="form-control input-sm">
                            <option value="1">disabled</option>
                            <option value="2">enabled</option>
                        </select>

Content Styling

                        <select name="content-styling" class="form-control input-sm">
                            <option value="1">default</option>
                            <option value="2">black</option>
                        </select>

                         Reset Local Storage

        <input type="hidden" id="hid" value="<?= $gid;?>">


text:
package com.simplaapliko.apprater.sample;

import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.simplaapliko.apprater.AppRater;
import com.simplaapliko.apprater.RateAppDialog;

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

public class MainFragment extends Fragment implements DialogInterface.OnClickListener {

    public MainFragment() {
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        AppRater.appLaunched(getActivity(), this, this, this);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_main, container, false);

        view.findViewById(R.id.show_dialog).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                DialogFragment dialog = new RateAppDialog.Builder()
                        .build();

                ((RateAppDialog) dialog).setOnPositiveButtonListener(MainFragment.this);
                ((RateAppDialog) dialog).setOnNegativeButtonListener(MainFragment.this);
                ((RateAppDialog) dialog).setOnNeutralButtonListener(MainFragment.this);

                dialog.show(getFragmentManager(), RateAppDialog.class.getSimpleName());
            }
        });

        view.findViewById(R.id.get_first_launch_date).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DateFormat format = SimpleDateFormat.getDateInstance(DateFormat.LONG);
                Date firstLaunch = AppRater.getFirstLaunchDate(getContext());
                Toast.makeText(getContext(), format.format(firstLaunch), Toast.LENGTH_SHORT).show();
            }
        });

        view.findViewById(R.id.get_launch_count).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int launchCount = AppRater.getLaunchCount(getContext());
                Toast.makeText(getContext(), String.valueOf(launchCount), Toast.LENGTH_SHORT).show();
            }
        });

        view.findViewById(R.id.is_do_not_show_again).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String isTimeToRate;
                if (AppRater.isDoNotShowAgain(getContext())) {
                    isTimeToRate = "yes";
                } else {
                    isTimeToRate = "no";
                }
                Toast.makeText(getContext(), isTimeToRate, Toast.LENGTH_SHORT).show();
            }
        });

        view.findViewById(R.id.is_time_to_rate).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String isTimeToRate;
                if (AppRater.isTimeToRate(getContext())) {
                    isTimeToRate = "yes";
                } else {
                    isTimeToRate = "no";
                }
                Toast.makeText(getContext(), isTimeToRate, Toast.LENGTH_SHORT).show();
            }
        });

        return view;
    }

    @Override
    public void onClick(DialogInterface dialog, int which) {
        switch (which) {
            case DialogInterface.BUTTON_POSITIVE:
                Toast.makeText(getContext(), "onPositiveButtonClick()", Toast.LENGTH_SHORT).show();
                break;
            case DialogInterface.BUTTON_NEGATIVE:
                Toast.makeText(getContext(), "onNegativeButtonClick()", Toast.LENGTH_SHORT).show();
                break;
            case DialogInterface.BUTTON_NEUTRAL:
                Toast.makeText(getContext(), "onNeutralButtonClick()", Toast.LENGTH_SHORT).show();
                break;
        }
    }
}


text:
<!DOCTYPE html>
<html lang="en" ng-app="cycleDB">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <base href="/">
    @yield('title')

    {{ HTML::style(asset('assets/styles/styles.css')) }}
    {{ HTML::script(asset('assets/scripts/libraries.js')) }}
    {{ HTML::script(asset('assets/scripts/modules.js')) }}
    {{ HTML::script(asset('assets/scripts/app.js')) }}

    <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
      <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
      <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
    <![endif]-->

  </head>
	<body>

    @yield('filter')

    @include('layouts.navbar')

    <div class="container">

      @yield('container')

      @include('layouts.footer')

    </div>

    @include('layouts.scripts.disqus')

	</body>

</html>


text:
package com.azure.resourcemanager.marketplaceordering.implementation;

import com.azure.resourcemanager.marketplaceordering.fluent.models.OperationInner;
import com.azure.resourcemanager.marketplaceordering.models.Operation;
import com.azure.resourcemanager.marketplaceordering.models.OperationDisplay;

public final class OperationImpl implements Operation {
    private OperationInner innerObject;

    private final com.azure.resourcemanager.marketplaceordering.MarketplaceOrderingManager serviceManager;

    OperationImpl(
        OperationInner innerObject,
        com.azure.resourcemanager.marketplaceordering.MarketplaceOrderingManager serviceManager) {
        this.innerObject = innerObject;
        this.serviceManager = serviceManager;
    }

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

    public OperationDisplay display() {
        return this.innerModel().display();
    }

    public OperationInner innerModel() {
        return this.innerObject;
    }

    private com.azure.resourcemanager.marketplaceordering.MarketplaceOrderingManager manager() {
        return this.serviceManager;
    }
}


text:
<?
	if( get_row_layout() == 'content_left_icon_right'):
		$bgImg = get_sub_field('background_image');
		$leftBgColor = get_sub_field('left_bg_color');
		$bg = (empty($bgImg)) ? 'style="background:'.$leftBgColor.'";' : 'style="background: url('.$bgImg.') no-repeat center center;background-size: cover;"';
		$title = get_sub_field('content_title');
		$rollover = get_sub_field('rollover_text');
		$leftLink = get_sub_field('left_link');
		if(!empty($title)){
?>

					<div class="bg-img" <?php echo $bg; ?>>

					<a class="box-anchor" href="<?php echo $leftLink; ?>">

<?php echo $title; ?>

							<?php if(!empty($rollover)){ ?>

								<?php echo $rollover; ?>

							<?php } ?>

<?php
		}// end if title is not empty
		$bgColor = get_sub_field('background_color');
		$icon = get_sub_field('font_awesome_icon');
		$imgIcon = get_sub_field('image_icon');
		$iconTitle = get_sub_field('icon_title');
		$titleColor = get_sub_field('title_color');
		$rightLink = get_sub_field('right_link');
		if(!empty($iconTitle)){
?>

					<div class="bg-img" style="background-color: <?php echo $bgColor?>">

					<a class="box-anchor" href="<?php echo $rightLink; ?>">

						<?php if (!empty($imgIcon)){ ?>
							<img class="img-icon" src="<?php echo $imgIcon; ?>" />
						<?php  } else { ?>
							<i class="img-icon fa <?php echo $icon; ?>" style="color: <?php echo $titleColor; ?>">
						<?php } ?>
							<h2 class="icon-title" style="color: <?php echo $titleColor; ?>"><?php echo $iconTitle; ?>

<?php
		}//end if title is not empty
	endif;
?>


text:
require 'apostle/version'
require 'apostle/mail'
require 'apostle/queue'
require 'uri'

module Apostle
  @@delivery_host = URI(ENV['APOSTLE_DELIVERY_HOST'] || 'http://deliver.apostle.io')
  @@domain_key = ENV['APOSTLE_DOMAIN_KEY']
  @@deliver = true

  def self.delivery_host=(host)
    @@delivery_host = host
  end

  # Lazily create a delivery_host URI
  def self.delivery_host
    if @@delivery_host.is_a?(URI)
      @@delivery_host
    else
      URI(@@delivery_host)
    end
  end

  def self.domain_key=(key)
    @@domain_key = key
  end

  def self.domain_key
    @@domain_key
  end

  def self.deliver=(bool)
    @@deliver = !!bool
  end

  def self.deliver
    @@deliver
  end

  class << self
    def configure
      yield self
    end
  end

  Error = Class.new(StandardError)
  DeliveryError = Class.new(Error)
  Unauthorized = Class.new(DeliveryError)
  Forbidden = Class.new(DeliveryError)
  UnprocessableEntity = Class.new(DeliveryError)
  ServerError = Class.new(DeliveryError)
end


text:
<?php
session_start();
?>
<!doctype html>

    <title>Login with Facebook</title>
<link href="http://www.bootstrapcdn.com/twitter-bootstrap/2.2.2/css/bootstrap-combined.min.css" rel="stylesheet">

  <?php if ($_SESSION['FBID']): ?>

Hello <?php echo $_SESSION['FULLNAME']; ?>

Welcome to "facebook login" tutorial

Image

<img src="https://graph.facebook.com/<?php echo $_SESSION['FBID']; ?>/picture">

Facebook ID

<?php echo  $_SESSION['FBID']; ?>

Facebook fullname

<?php echo $_SESSION['FULLNAME']; ?>

Facebook Email

<?php echo $_SESSION['EMAIL']; ?>

Logout

    <?php else: ?>

Login with Facebook

           Not Connected

      Login with Facebook

 View Post

    <?php endif ?>


text:
<?php

namespace Mastercel\ChartBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * Validacionescontables
 *
 * @ORM\Table(name="ValidacionesContables", uniqueConstraints={@ORM\UniqueConstraint(name="Indice_1", columns={"StrValidacion_ky"})}, indexes={@ORM\Index(name="Indice_2", columns={"StrDescripcion"}), @ORM\Index(name="Indice_3", columns={"DteActualizacion"}), @ORM\Index(name="Indice_4", columns={"NumEstadoComunicacion"})})
 * @ORM\Entity
 */
class Validacionescontables
{
    /**
     * @var integer
     *
     * @ORM\Column(name="NumValidacion_id", type="integer", nullable=false)
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    private $numvalidacionId = '0';

    /**
     * @var string
     *
     * @ORM\Column(name="StrValidacion_ky", type="string", length=10, nullable=true)
     */
    private $strvalidacionKy;

    /**
     * @var string
     *
     * @ORM\Column(name="StrDescripcion", type="string", length=60, nullable=true)
     */
    private $strdescripcion;

    /**
     * @var integer
     *
     * @ORM\Column(name="NumTipoValidacion", type="integer", nullable=true)
     */
    private $numtipovalidacion = '0';

    /**
     * @var integer
     *
     * @ORM\Column(name="NumCreadoPor_id", type="integer", nullable=true)
     */
    private $numcreadoporId = '0';

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="DteCreacion", type="datetime", nullable=true)
     */
    private $dtecreacion;

    /**
     * @var integer
     *
     * @ORM\Column(name="NumActualizadoPor_id", type="integer", nullable=true)
     */
    private $numactualizadoporId = '0';

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="DteActualizacion", type="datetime", nullable=true)
     */
    private $dteactualizacion;

    /**
     * @var integer
     *
     * @ORM\Column(name="NumEstadoComunicacion", type="integer", nullable=true)
     */
    private $numestadocomunicacion = '0';

    /**
     * Get numvalidacionId
     *
     * @return integer
     */
    public function getNumvalidacionId()
    {
        return $this->numvalidacionId;
    }

    /**
     * Set strvalidacionKy
     *
     * @param string $strvalidacionKy
     * @return Validacionescontables
     */
    public function setStrvalidacionKy($strvalidacionKy)
    {
        $this->strvalidacionKy = $strvalidacionKy;

        return $this;
    }

    /**
     * Get strvalidacionKy
     *
     * @return string
     */
    public function getStrvalidacionKy()
    {
        return $this->strvalidacionKy;
    }

    /**
     * Set strdescripcion
     *
     * @param string $strdescripcion
     * @return Validacionescontables
     */
    public function setStrdescripcion($strdescripcion)
    {
        $this->strdescripcion = $strdescripcion;

        return $this;
    }

    /**
     * Get strdescripcion
     *
     * @return string
     */
    public function getStrdescripcion()
    {
        return $this->strdescripcion;
    }

    /**
     * Set numtipovalidacion
     *
     * @param integer $numtipovalidacion
     * @return Validacionescontables
     */
    public function setNumtipovalidacion($numtipovalidacion)
    {
        $this->numtipovalidacion = $numtipovalidacion;

        return $this;
    }

    /**
     * Get numtipovalidacion
     *
     * @return integer
     */
    public function getNumtipovalidacion()
    {
        return $this->numtipovalidacion;
    }

    /**
     * Set numcreadoporId
     *
     * @param integer $numcreadoporId
     * @return Validacionescontables
     */
    public function setNumcreadoporId($numcreadoporId)
    {
        $this->numcreadoporId = $numcreadoporId;

        return $this;
    }

    /**
     * Get numcreadoporId
     *
     * @return integer
     */
    public function getNumcreadoporId()
    {
        return $this->numcreadoporId;
    }

    /**
     * Set dtecreacion
     *
     * @param \DateTime $dtecreacion
     * @return Validacionescontables
     */
    public function setDtecreacion($dtecreacion)
    {
        $this->dtecreacion = $dtecreacion;

        return $this;
    }

    /**
     * Get dtecreacion
     *
     * @return \DateTime
     */
    public function getDtecreacion()
    {
        return $this->dtecreacion;
    }

    /**
     * Set numactualizadoporId
     *
     * @param integer $numactualizadoporId
     * @return Validacionescontables
     */
    public function setNumactualizadoporId($numactualizadoporId)
    {
        $this->numactualizadoporId = $numactualizadoporId;

        return $this;
    }

    /**
     * Get numactualizadoporId
     *
     * @return integer
     */
    public function getNumactualizadoporId()
    {
        return $this->numactualizadoporId;
    }

    /**
     * Set dteactualizacion
     *
     * @param \DateTime $dteactualizacion
     * @return Validacionescontables
     */
    public function setDteactualizacion($dteactualizacion)
    {
        $this->dteactualizacion = $dteactualizacion;

        return $this;
    }

    /**
     * Get dteactualizacion
     *
     * @return \DateTime
     */
    public function getDteactualizacion()
    {
        return $this->dteactualizacion;
    }

    /**
     * Set numestadocomunicacion
     *
     * @param integer $numestadocomunicacion
     * @return Validacionescontables
     */
    public function setNumestadocomunicacion($numestadocomunicacion)
    {
        $this->numestadocomunicacion = $numestadocomunicacion;

        return $this;
    }

    /**
     * Get numestadocomunicacion
     *
     * @return integer
     */
    public function getNumestadocomunicacion()
    {
        return $this->numestadocomunicacion;
    }
}


text:
import Vue from 'vue'
import VueResource from 'vue-resource'
import Sortable from 'vue-sortable'
import VueRouter from 'vue-router'
import App from './App'
import routes from './router'

Vue.use(VueResource)
Vue.use(VueRouter)
Vue.use(Sortable)

const router = new VueRouter({
  mode: 'hash', //hash模式
  base: './',
  routes: routes
})

new Vue({
  el: '#app',
  router,
  template: '<App/>',
  components: {
    App
  }
})


text:
import { fork, take, call, put, race, cancel } from 'redux-saga/effects';
import { SagaCancellationException } from 'redux-saga';
import * as actions from './actions.js';
import * as spinnerActions from 'modules/app/containers/AppSpinner/actions';
import * as messageActions from 'modules/app/containers/AppMessage/actions';
import { serverApi, graphApi } from 'api';
import { pushHistory } from 'modules/workspace/containers/HistoryControls/actions';
import { updatePage } from 'modules/workspace/containers/DeskPage/actions';
import { setSelectedKey } from 'modules/workspace/containers/SelectionBreadcrumbs/actions';

const delay = ms => new Promise(resolve => setTimeout(() => resolve('timed out'), ms));

function* delaySaveComponentSourceCode(){
    try{
        yield call(delay, 10000);
        yield put(messageActions.timeout('Saving source code is timed out. Check the console output for errors.'));
        yield put(actions.setReloadPageRequest());
        yield put(actions.saveSourceCodeTimeout());
    } catch(e){
        if (e instanceof SagaCancellationException) {
            // do nothing
        }
    }
}

function* saveComponentSourceCode(options){
    try {
        const {key, sourcePropsObj, text, sourceCode, sourceFilePath} = options;
        let node = graphApi.getNode(key);
        if (node) {
            if(sourceCode && sourceFilePath){
                yield call(serverApi.writeComponentSource, sourceFilePath, sourceCode);
            }
            yield put(pushHistory());
            node.modelNode.props = sourcePropsObj;
            node.modelNode.text = text;
            yield put(setSelectedKey(key));
            yield put(updatePage());
            yield put(actions.hideModal());
        } else {
            yield put(messageActions.failed('Saving source code error. Error: component with key ' + key + ' was not found.'));
        }
        yield put(actions.saveSourceCodeDone());
    } catch (error) {
        console.error(error);
        if (error instanceof SagaCancellationException) {
            // do nothing
        } else {
            yield put(messageActions.failed('Saving source code error. Error: ' + (error.message ? error.message : error)));
            yield put(actions.saveSourceCodeDone());
        }
    }
}

function* saveSourceCode(){
    while(true){
        const { payload } = yield take(actions.SAVE_SOURCE_CODE);
        yield put(spinnerActions.started('Saving source code'));
        const saveTask = yield fork(saveComponentSourceCode, payload);
        const delayTask = yield fork(delaySaveComponentSourceCode);
        yield take([actions.SAVE_SOURCE_CODE_DONE, actions.SAVE_SOURCE_CODE_TIMEOUT]);
        yield cancel(saveTask);
        yield cancel(delayTask);
        yield put(spinnerActions.done('Saving source code'));
    }
}

function* loadComponentOptions(componentName, namespace, sourceFilePath){
    try{
        return yield call(serverApi.loadComponentOptions, componentName, namespace, sourceFilePath);
    } catch(error){
        if(error instanceof SagaCancellationException){
            yield put(messageActions.failed('Loading component options was canceled.'));
        } else {
            yield put(messageActions.failed('Loading component options error. Error: ' + (error.message ? error.message : error)));
        }
    }
}

function* loadOptionsAndShowModal(){
    while(true){
        const { payload } = yield take(actions.LOAD_OPTIONS_AND_SHOW_MODAL);
        yield put(spinnerActions.started('Loading component options'));
        try {
            const {sourceFilePath, componentName, namespace} = payload;
            const {timeout, response} = yield race({
                response: call(loadComponentOptions, componentName, namespace, sourceFilePath),
                timeout: call(delay, 10000)
            });
            if(response){
                yield put(actions.setOptions({...payload, ...response}));
                yield put(actions.showModal());
            } else if(timeout) {
                yield put(messageActions.timeout('Loading component options is timed out.'));
            }
        } catch(error) {
            yield put(messageActions.failed('Loading component options error. Error: ' + (error.message ? error.message : error)));
        }
        yield put(spinnerActions.done('Loading component options'));
    }
}

// main saga
export default function* mainSaga() {
    yield [fork(saveSourceCode), fork(loadOptionsAndShowModal)];
};


text:
from .. import helpers
import NSURLSessionTask

class NSURLSessionDataTaskSyntheticProvider(NSURLSessionTask.NSURLSessionTaskSyntheticProvider):
    """
    Class representing NSURLSessionDataTask.
    """
    def __init__(self, value_obj, internal_dict):
        super(NSURLSessionDataTaskSyntheticProvider, self).__init__(value_obj, internal_dict)
        self.type_name = "NSURLSessionDataTask"

def summary_provider(value_obj, internal_dict):
    return helpers.generic_summary_provider(value_obj, internal_dict, NSURLSessionDataTaskSyntheticProvider)


text:
import {ReplaySubject} from 'rxjs/ReplaySubject';
import {Injectable, OnDestroy} from '@angular/core';
import {Observable} from 'rxjs/Observable';
import {Subject} from 'rxjs/Subject';

@Injectable()
export class NgxDestroy$ extends Observable<boolean> implements OnDestroy {

  private subject: Subject<boolean>;

  constructor() {
    super();
    this.subject = new ReplaySubject<boolean>(1);
    this.source = this.subject;
  }

  /**
   * take advantage of the fact that ngOnDestroy is called when a provider is destoyed!
   */
  public ngOnDestroy(): void {
    this.subject.next(true);
    this.subject.complete();
  }

}


text:
const omp::HandEvaluator Player::evaluator = omp::HandEvaluator();

Player::Player(Position::Position seat, double stack, PlayerStrategy* strategy) :
	Player(seat, stack, false, { Card::None, Card::None }, strategy)
{
}

Player::Player(Position::Position seat, double stack, bool isHero, Holding holding, PlayerStrategy* strategy) :
	seat(seat),
	stack(stack),
	isHero(isHero),
	holding(holding),
	strategy(strategy),
	lastAction(Action::Waiting)
{
}

Position::Position Player::Seat() const
{
	return seat;
}

double Player::Stack() const
{
	return stack;
}

bool Player::IsHero() const
{
	return isHero;
}

bool Player::IsPlaying() const
{
	return lastAction != Action::Fold;
}

Action Player::LastAction() const
{
	return lastAction;
}

void Player::SetLastAction(Action action)
{
	lastAction = action;
}

void Player::SetStack(double wager)
{
	stack = (stack - wager) < 0.0 ? 0.0 : stack - wager;
}

Holding Player::GetHolding() const
{
	return holding;
}

PlayerStrategy * Player::Strategy() const
{
	return strategy;
}

bool Player::operator<(const Player& other)
{
	return seat < other.seat;
}


text:
require 'rails_helper'

RSpec.describe FoodTrucksController, type: :controller do

end


text:
```
void surf(Input IN, inout SurfaceOutput o)
    {
        fixed2    uv0 = IN.uv_MainTex;
        fixed2    uv1 = IN.uv_MainTex2;
        fixed4    paramtex = tex2D(_ParamTex, uv0);
        fixed4    mainTex = tex2D(_MainTex, uv0);
        fixed4    mainTex2 = tex2D(_MainTex2, uv1);
        fixed    clipTex = tex2D(_ClipTex, uv0).r;
        fixed factorRed = IN.color.r; // Get from vertex color input. (R)
        fixed factorGreen = IN.color.g; // Get from vertex color input. (G)
        fixed combinedMask = clamp(fPow(factorGreen + (clipTex * _BlendScale1), 2), 0, 1);
        fixed3 texCom = flerp(mainTex, mainTex2, combinedMask);
        paramtex = flerp(paramtex, fixed4(0,0,1,0), combinedMask);
        o.Albedo = texCom * paramtex.b;
        o.Gloss = paramtex.g;
        o.Specular = paramtex.r;

    }
```

---

### ![](/assets/20170218_012312.jpg)

### Texture2LayerHeightBlending.2NormalBlending \(Modular Blending \)

```
void surf(Input IN, inout SurfaceOutput o)
    {
        fixed2    uv0 = IN.uv_MainTex;
        fixed2    uv1 = IN.uv_MainTex2;
        fixed4    paramtex = tex2D(_ParamTex, uv0);
        fixed4    mainTex = tex2D(_MainTex, uv0) * _MainColor;
        fixed4    mainTexBump = tex2D(_BumpMap, uv0);
        fixed4    mainTex2 = tex2D(_MainTex2, uv1);
        fixed4    mainTexBump2 = tex2D(_BumpMap2, uv1);
        fixed    clipTex = tex2D(_ClipTex, uv0).r;
        fixed factorRed = IN.color.r; // Get from vertex color input. (R)
        fixed factorGreen = IN.color.g; // Get from vertex color input. (G)
        fixed combinedMask = clamp(fPow(factorGreen + (clipTex * _BlendScale1), 2), 0, 1);
        fixed3 texCom = flerp(mainTex, mainTex2, combinedMask);
        paramtex = flerp(paramtex, fixed4(0, 0, 1, 0), combinedMask);
        o.Albedo = texCom * paramtex.b;
        o.Gloss = paramtex.g;
        o.Specular = paramtex.r;
        o.Normal = fNormalBlender(mainTexBump , mainTexBump2 , IN.color, 1 - _BlendNormal);

    }
```

> #### Related code
>
> ##### [Tweak shader function for the custom shaders.](/simple-shader-func.md)

###


text:
package org.springframework.samples.petclinic.repository.jdbc;

import org.joda.time.LocalDate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.samples.petclinic.model.Visit;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;

/**
 * {@link RowMapper} implementation mapping data from a {@link ResultSet} to the corresponding properties
 * of the {@link Visit} class.
 */
class JdbcVisitRowMapper implements RowMapper<Visit> {

    @Override
    public Visit mapRow(ResultSet rs, int row) throws SQLException {
        Visit visit = new Visit();
        visit.setId(rs.getInt("visit_id"));
        Date visitDate = rs.getDate("visit_date");
        visit.setDate(new LocalDate(visitDate));
        visit.setDescription(rs.getString("description"));
        return visit;
    }
}