text:
package com.batiaev.vk.api;

import com.batiaev.vk.common.VKParameters;
import com.batiaev.vk.common.annotation.Rights;
import com.batiaev.vk.common.consts.VKApiJsonConst;
import com.batiaev.vk.common.consts.VKApiRigths;
import com.batiaev.vk.common.entity.VKCity;
import com.batiaev.vk.common.entity.VKCountry;
import com.batiaev.vk.sdk.VkLocalCache;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.json.JSONArray;
import org.json.JSONObject;

/**
 * Builds requests for API.database part
 *

 * https://vk.com/dev/database
 *
 * @author anbat
 * @since 17/04/15
 */
public class VKApiDatabase extends VKApiBase {
    private static final Logger LOG = LogManager.getLogger(VKApiDatabase.class);

    /**
     * API database.getCountries()
     *
     * @param params method parameters
     * @return String with json respond
     */
    @Rights(value = VKApiRigths.OPEN_METHOD)
    public String getCountries(VKParameters params) {
        return execute(getUrl("getCountries", params)).toString();
    }

    /**
     * API database.getRegions()
     *
     * @param params method parameters
     * @return String with json respond
     */
    @Rights(value = VKApiRigths.OPEN_METHOD)
    public String getRegions(VKParameters params) {
        return execute(getUrl("getRegions", params)).toString();
    }

    /**
     * API database.getStreetsById()
     *
     * @param params method parameters
     * @return String with json respond
     */
    @Rights(value = VKApiRigths.OPEN_METHOD)
    public String getStreetsById(VKParameters params) {
        return execute(getUrl("getStreetsById", params)).toString();
    }

    /**
     * API database.getCountriesById()
     *
     * @param params method parameters
     * @return VKCountry with required id
     */
    @Rights(value = VKApiRigths.OPEN_METHOD)
    public VKCountry getCountriesById(VKParameters params) {
        VKCountry country = new VKCountry();

        int countryId = Integer.parseInt(params.value(VKApiJsonConst.COUNTRY_IDS));
        if (VkLocalCache.hastCountry(countryId)) {
            country.setId(countryId);
            country.setName(VkLocalCache.getCountry(countryId));
        } else {
            String respond = execute(getUrl("getCountriesById", params)).toString();

            LOG.info(respond);

            JSONObject obj = new JSONObject(respond);
            final JSONArray countryList = obj.getJSONArray(VKApiJsonConst.RESPONSE);

            if (countryList.length() == 0) return country;

            JSONObject countryJson = countryList.getJSONObject(0);

            country.setId(countryJson.getInt(VKApiJsonConst.CID));
            country.setName(countryJson.getString(VKApiJsonConst.NAME));

            VkLocalCache.setCountry(country.id(), country.name());
        }
        return country;
    }

    /**
     * API database.getCities()
     *
     * @param params method parameters
     * @return String with json respond
     */
    @Rights(value = VKApiRigths.OPEN_METHOD)
    public String getCities(VKParameters params) {
        return execute(getUrl("getCities", params)).toString();
    }

    /**
     * API database.getCitiesById()
     *
     * @param params method parameters
     * @return city with required id
     */
    @Rights(value = VKApiRigths.OPEN_METHOD)
    public VKCity getCitiesById(VKParameters params) {
        VKCity city = new VKCity();
        int cityId = Integer.parseInt(params.value(VKApiJsonConst.CITY_IDS));
        city.setId(cityId);

        if (VkLocalCache.hastCity(cityId)) {
            city.setName(VkLocalCache.getCity(cityId));
        } else {
            String respond = execute(getUrl("getCitiesById", params)).toString();

            LOG.info(respond);

            JSONObject obj = new JSONObject(respond);
            final JSONArray cityList = obj.getJSONArray(VKApiJsonConst.RESPONSE);

            if (cityList.length() == 0) return city;

            JSONObject cityJson = cityList.getJSONObject(0);

            city.setId(cityJson.getInt(VKApiJsonConst.CID));
            city.setName(cityJson.getString(VKApiJsonConst.NAME));

            VkLocalCache.setCity(city.id(), city.name());
        }

        return city;
    }

    /**
     * API database.getUniversities()
     *
     * @param params method parameters
     * @return String with json respond
     */
    @Rights(value = VKApiRigths.OPEN_METHOD)
    public String getUniversities(VKParameters params) {
        return execute(getUrl("getUniversities", params)).toString();
    }

    /**
     * API database.getSchools()
     *
     * @param params method parameters
     * @return String with json respond
     */
    @Rights(value = VKApiRigths.OPEN_METHOD)
    public String getSchools(VKParameters params) {
        return execute(getUrl("getSchools", params)).toString();
    }

    /**
     * API database.getSchoolClasses()
     *
     * @param params method parameters
     * @return String with json respond
     */
    @Rights(value = VKApiRigths.OPEN_METHOD)
    public String getSchoolClasses(VKParameters params) {
        return execute(getUrl("getSchoolClasses", params)).toString();
    }

    /**
     * API database.getFaculties()
     *
     * @param params method parameters
     * @return String with json respond
     */
    @Rights(value = VKApiRigths.OPEN_METHOD)
    public String getFaculties(VKParameters params) {
        return execute(getUrl("getFaculties", params)).toString();
    }

    /**
     * API database.getChairs()
     *
     * @param params method parameters
     * @return String with json respond
     */
    @Rights(value = VKApiRigths.OPEN_METHOD)
    public String getChairs(VKParameters params) {
        return execute(getUrl("getChairs", params)).toString();
    }

    @Override
    protected String getMethodsGroup() {
        return "database";
    }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">
    <link rel="shortcut icon" href="/static/img/ico/favicon.ico">

    <title>만나순대</title>

    <link rel="stylesheet" href="/static/bootstrap/css/bootstrap.min.css">
    <link rel="stylesheet" href="/static/bootstrap/css/bootstrap-theme.min.css">

    <link href="/static/css/justified-nav.css" rel="stylesheet">
    {% block css %}{% endblock %}

            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
              Toggle navigation

            </button>
            만나순대

홈

                메뉴

전체 메뉴

인기 메뉴

예약 주문 메뉴

일정

연락처

        {% block content %}{% endblock %}

© Company 2014 동부시장 만나순대 063)858-3748

    {% block script %}{% endblock %}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Zend\Captcha;

use Zend\Text\Figlet\Figlet as FigletManager;

/**
 * Captcha based on figlet text rendering service
 *
 * Note that this engine seems not to like numbers
 *
 * @category   Zend
 * @package    Zend_Captcha
 * @subpackage Adapter
 */
class Figlet extends AbstractWord
{
    /**
     * Figlet text renderer
     *
     * @var FigletManager
     */
    protected $figlet;

    /**
     * Constructor
     *
     * @param  null|string|array|\Traversable $options
     */
    public function __construct($options = null)
    {
        parent::__construct($options);
        $this->figlet = new FigletManager($options);
    }

    /**
     * Retrieve the composed figlet manager
     *
     * @return FigletManager
     */
    public function getFiglet()
    {
        return $this->figlet;
    }

    /**
     * Generate new captcha
     *
     * @return string
     */
    public function generate()
    {
        $this->useNumbers = false;
        return parent::generate();
    }

    /**
     * Get helper name used to render captcha
     *
     * @return string
     */
    public function getHelperName()
    {
        return 'captcha/figlet';
    }
}


text:
using System;
using System.Reflection;
using System.Runtime.CompilerServices;

namespace CSharpLib
{
    public class CallerInfoTest
    {
        public static int LineNumber([CallerLineNumber] int line = 777)
        {
            return line;
        }

        public static string FilePath([CallerFilePath] string filePath = "dummy1")
        {
            return filePath;
        }

		public static string MemberName([CallerMemberName] string memberName = "dummy1")
        {
            return memberName;
        }

        public static Tuple<string, int, string> AllInfo(int normalArg, [CallerFilePath] string filePath = "dummy2", [CallerLineNumber] int line = 778, [CallerMemberName] string memberName = "dummy3")
        {
            return new Tuple<string, int, string>(filePath, line, memberName);
        }
    }

    public class MyCallerInfoAttribute : Attribute
    {
        public int LineNumber { get; set; }

        public MyCallerInfoAttribute([CallerLineNumber] int lineNumber = -1)
        {
            LineNumber = lineNumber;
        }
    }

    public class MyCallerMemberNameAttribute : Attribute
    {
        public string MemberName { get; set; }

        public MyCallerMemberNameAttribute([CallerMemberName] string member = "dflt")
        {
            MemberName = member;
        }
    }
}


text:
<?php
//declare(strict_types=1);

namespace Manta\Exceptions;
//not yet used.. maybe remove
class PermissionException extends NoAccessException
{

}


text:
require_relative 'base'

module NyanCash::Models
  model :Commodity do
    include Base

    schema_version 1

    one_to_many :slots, class: models.Slot, key: :obj_guid
  end
end


text:
These settings apply only when `--az` is specified on the command line.

``` yaml $(az)
az:
  extensions: datafactory
  namespace: azure.mgmt.datafactory
  package-name: azure-mgmt-datafactory
  disable-checks: true
  randomize-names: true
az-output-folder:  $(azure-cli-extension-folder)/src/datafactory
python-sdk-output-folder: "$(az-output-folder)/azext_datafactory/vendored_sdks/datafactory"

input-file:
- Microsoft.DataFactory/stable/2018-06-01/entityTypes/DataFlow.json
- Microsoft.DataFactory/stable/2018-06-01/entityTypes/Dataset.json
- Microsoft.DataFactory/stable/2018-06-01/entityTypes/IntegrationRuntime.json
- Microsoft.DataFactory/stable/2018-06-01/entityTypes/LinkedService.json
- Microsoft.DataFactory/stable/2018-06-01/entityTypes/Pipeline.json
- Microsoft.DataFactory/stable/2018-06-01/entityTypes/Trigger.json

directive:
    - from: swagger-document
      where: $.definitions.JsonFormatFilePattern
      transform: >
          $['type'] = 'string';
    - from: swagger-document
      where: $.definitions.CompressionLevel
      transform: >
          $['type'] = 'string';
    - from: swagger-document
      where: $.definitions.DynamicsLinkedServiceTypeProperties.properties.servicePrincipalCredentialType
      transform: >
          $['type'] = 'string';
    - from: swagger-document
      where: $.definitions.ScriptAction.properties.roles
      transform: >
          $['type'] = 'string';
    - where:
          command: datafactory integration-runtime create-linked-integration-runtime
      set:
          command: datafactory integration-runtime linked-integration-runtime create

cli:
    cli-directive:
    # directive on operationGroup
      - where:
            group: Pipelines
            op: CreateOrUpdate$|CreateOrUpdate#Create
            parameter: pipeline
        json: true
      - where:
            group: IntegrationRuntimes
            op: CreateOrUpdate
            param: properties
        poly-resource: true
      - where:
            group: IntegrationRuntimes
            op: CreateOrUpdate#*
            param: properties
        poly-resource: true
      - where:
            group: ExposureControl|IntegrationRuntimeObjectMetadata|DataFlows|DataFlowDebugSession|ManagedVirtualNetworks|ManagedPrivateEndpoints
        hidden: true
      - where:
            group: Factories
            op: ConfigureFactoryRepo
            param: locationId
        name: location
      - where:
            group: IntegrationRuntimes
            op: CreateLinkedIntegrationRuntime
            param: dataFactoryLocation
        name: location
      - where:
            group: Triggers|LinkedServices|Datasets
            op: CreateOrUpdate#Update
            param: properties
        cli-flatten: true
      - where:
            group: Pipelines
            op: CreateOrUpdate#Update
            param: pipeline
        cli-flatten: true
```


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE topic
  PUBLIC "-//OASIS//DTD DITA Composite//EN" "ditabase.dtd">
<topic id="topic1">

    <title id="js140845">gpinitstandby</title>

Adds and/or initializes a standby master host for a Greenplum Database system.

            <title>Synopsis</title>
            <codeblock>gpinitstandby { -s <varname>standby_hostname</varname> [-P port] | -r | -n } [-a] [-q]
    [-D] [-S <varname>standby_data_directory</varname>] [-l <varname>logfile_directory</varname>]

gpinitstandby -v

gpinitstandby -?</codeblock>

            <title>Description</title>

The <codeph>gpinitstandby</codeph> utility adds a backup, standby master instance to
                your Greenplum Database system. If your system has an existing standby master
                instance configured, use the <codeph>-r</codeph> option to remove it before adding
                the new standby master instance.

Before running this utility, make sure that the Greenplum Database software is
                installed on the standby master host and that you have exchanged SSH keys between
                the hosts. It is recommended that the master port is set to the same port number on
                the master host and the standby master host.

This utility should be run on the currently active primary master host.<ph>
                    See the Greenplum Database Installation Guide for instructions.</ph>

The utility performs the following steps:

Updates the Greenplum Database system catalog to remove the
                    existing standby master information (if the <codeph>-r</codeph> option is
                    supplied)

Updates the Greenplum Database system catalog to add the new
                    standby master instance information

Edits the <codeph>pg_hba.conf</codeph> file of the Greenplum
                    Database master to allow access from the newly added standby master

Sets up the standby master instance on the alternate master
                    host

Starts the synchronization process

A backup, standby master instance serves as a 'warm standby' in the event of the
                primary master becoming non-operational. The standby master is kept up to date by
                transaction log replication processes (the <codeph>walsender</codeph> and
                    <codeph>walreceiver</codeph>), which run on the primary master and standby
                master hosts and keep the data between the primary and standby master instances
                synchronized. If the primary master fails, the log replication process is shut down,
                and the standby master can be activated in its place by using the
                    <codeph>gpactivatestandby</codeph> utility. Upon activation of the standby
                master, the replicated logs are used to reconstruct the state of the master instance
                at the time of the last successfully committed transaction.

The activated standby master effectively becomes the Greenplum Database master,
                accepting client connections on the master port and performing normal master
                operations such as SQL command processing and resource management.

            <note type="important">If the <codeph>gpinitstandby</codeph> utility previously failed
                to initialize the standby master, you must delete the files in the standby master
                data directory before running <codeph>gpinitstandby</codeph> again. The standby
                master data directory is not cleaned up after an initialization failure because it
                contains log files that can help in determining the reason for the failure.
If an
                    initialization failure occurs, a summary report file is generated in the standby
                    host directory <codeph>/tmp</codeph>. The report file lists the directories on
                    the standby host that require clean up.
</note>

            <title>Options</title>
            <parml>
                <plentry>
                    <pt>-a (do not prompt)</pt>
                    <pd>Do not prompt the user for confirmation.</pd>
                </plentry>
                <plentry>
                    <pt>-D (debug)</pt>
                    <pd>Sets logging level to debug.</pd>
                </plentry>
                <plentry>
                    <pt>-l <varname>logfile_directory</varname></pt>
                    <pd>The directory to write the log file. Defaults to
                            <codeph>~/gpAdminLogs</codeph>.</pd>
                </plentry>
                <plentry>
                    <pt>-n (restart standby master)</pt>
                    <pd>Specify this option to start a Greenplum Database standby master that has
                        been configured but has stopped for some reason.</pd>
                </plentry>
                <plentry>
                    <pt>-P <varname>port</varname></pt>
                    <pd>This option specifies the port that is used by the Greenplum Database
                        standby master. The default is the same port used by the active Greenplum
                        Database master. </pd>
                    <pd>If the Greenplum Database standby master is on the same host as the active
                        master, the ports must be different. If the ports are the same for the
                        active and standby master and the host is the same, the utility returns an
                        error. </pd>
                </plentry>
                <plentry>
                    <pt>-q (no screen output)</pt>
                    <pd>Run in quiet mode. Command output is not displayed on the screen, but is
                        still written to the log file.</pd>
                </plentry>
                <plentry>
                    <pt>-r (remove standby master)</pt>
                    <pd>Removes the currently configured standby master instance from your Greenplum
                        Database system.</pd>
                </plentry>
                <plentry>
                    <pt>-s standby_hostname</pt>
                    <pd>The host name of the standby master host.</pd>
                </plentry>
                <plentry>
                    <pt>-S <varname>standby_data_directory</varname></pt>
                    <pd>The data directory to use for a new standby master. The default is the same
                        directory used by the active master.</pd>
                    <pd>If the standby master is on the same host as the active master, a different
                        directory must be specified using this option.</pd>
                </plentry>
                <plentry>
                    <pt>-v (show utility version)</pt>
                    <pd>Displays the version, status, last updated date, and checksum of this
                        utility.</pd>
                </plentry>
                <plentry>
                    <pt>-? (help)</pt>
                    <pd>Displays the online help.</pd>
                </plentry>
            </parml>

            <title>Examples</title>

Add a standby master instance to your Greenplum Database system and start the
                synchronization process:

            <codeblock>gpinitstandby -s host09</codeblock>

Start an existing standby master instance and synchronize the data with the current
                primary master instance:

            <codeblock>gpinitstandby -n</codeblock>
            <note type="note">Do not specify the -n and -s options in the same command.</note>

Add a standby master instance to your Greenplum Database system specifying a
                different port:

            <codeblock>gpinitstandby -s myhost -P 2222</codeblock>

If you specify the same host name as the active Greenplum Database master, you must
                also specify a different port number with the <codeph>-P</codeph> option and a
                standby data directory with the <codeph>-S</codeph> option.

Remove the existing standby master from your Greenplum system configuration:

            <codeblock>gpinitstandby -r</codeblock>

            <title>See Also</title>

<codeph><xref href="./gpinitsystem.xml#topic1" type="topic" format="dita"/></codeph>,
                        <codeph><xref href="gpaddmirrors.xml#topic1" type="topic" format="dita"
                    /></codeph>, <codeph><xref href="gpactivatestandby.xml#topic1" type="topic"
                        format="dita"/></codeph>

</topic>


text:
require 'rails_helper'

RSpec.describe AdditionalRespondentsForm::AdditionalRespondent, type: :form do
  let(:additional_respondent) { described_class.new Respondent.new }
  let(:attributes) do
    {
      name: 'Butch McTaggert', acas_early_conciliation_certificate_number: 'XX123456/12/12',
      address_building: '1', address_street: 'High Street',
      address_locality: 'Anytown', address_county: 'Anyfordshire',
      address_post_code: 'W2 3ED'
    }
  end

  let(:target) { Respondent.new }

  describe 'validations' do
    [:name, :address_building, :address_street, :address_locality, :address_post_code].each do |attr|
      it { expect(additional_respondent).to validate_presence_of(attr) }
    end

    it { expect(additional_respondent).to validate_length_of(:name).is_at_most(100) }

    it { expect(additional_respondent).to validate_length_of(:address_building).is_at_most(75) }
    it { expect(additional_respondent).to validate_length_of(:address_street).is_at_most(75) }
    it { expect(additional_respondent).to validate_length_of(:address_locality).is_at_most(25) }
    it { expect(additional_respondent).to validate_length_of(:address_county).is_at_most(25) }
    it { expect(additional_respondent).to validate_length_of(:address_post_code).is_at_most(8) }

    describe 'presence of ACAS certificate number' do
      describe 'when ACAS number is indicated' do
        before { additional_respondent.no_acas_number = 'false' }
        it     { expect(additional_respondent).to validate_presence_of(:acas_early_conciliation_certificate_number) }
      end

      describe 'when no ACAS number is indicated' do
        before { additional_respondent.no_acas_number = 'true' }
        it     { expect(additional_respondent).not_to validate_presence_of(:acas_early_conciliation_certificate_number) }
      end

      describe 'ACAS format validation' do
        { one_char_ten_digits:  'X123456/12/12',
          two_chars_ten_digits: 'XX123456/12/12' }.each do |key, acas_value|
          it "#{key.to_s.humanize} validates correctly" do
            additional_respondent.acas_early_conciliation_certificate_number = acas_value
            additional_respondent.valid?

            expect(additional_respondent.errors[:acas_early_conciliation_certificate_number]).to be_empty
          end
        end

        it 'adds an error if the format is invalid' do
          additional_respondent.acas_early_conciliation_certificate_number = 'invalid'
          additional_respondent.valid?

          expect(additional_respondent.errors[:acas_early_conciliation_certificate_number]).
            to include('You have provided an invalid Acas early conciliation number.')
        end
      end
    end

    describe 'presence of reason explaining no ACAS certificate number' do
      let(:reasons) do
        ['joint_claimant_has_acas_number', 'acas_has_no_jurisdiction', 'employer_contacted_acas', 'interim_relief']
      end

      it { expect(additional_respondent).to validate_inclusion_of(:no_acas_number_reason).in_array reasons }

      describe 'when and ACAS number is given' do
        before { additional_respondent.no_acas_number = 'false' }
        it     { expect(additional_respondent).not_to validate_presence_of(:no_acas_number_reason) }
      end

      describe 'when and ACAS number is given' do
        before { additional_respondent.no_acas_number = 'true' }
        it     { expect(additional_respondent).to validate_presence_of(:no_acas_number_reason) }
      end
    end

    it 'clears acas number when selecting no acas number' do
      additional_respondent.acas_early_conciliation_certificate_number = 'acas'
      additional_respondent.no_acas_number = 'true'
      additional_respondent.valid?

      expect(additional_respondent.acas_early_conciliation_certificate_number).to be nil
    end
  end

  context 'with target' do
    let(:additional_respondent) { AdditionalRespondentsForm::AdditionalRespondent.new(target) }

    before { allow(additional_respondent.target).to receive :enqueue_fee_group_reference_request }

    describe '.model_name_i18n_key' do
      specify do
        expect(described_class.model_name_i18n_key).
          to eq(described_class.model_name.i18n_key)
      end
    end

    describe '#column_for_attribute' do
      it "returns the attribute's type"
    end

    describe '#save' do
      describe 'for valid attributes' do
        before { additional_respondent.assign_attributes attributes }

        it "saves the data" do
          expect(target).to receive(:update_attributes).with additional_respondent.attributes
          additional_respondent.save
        end

        it 'is true' do
          expect(additional_respondent.save).to be true
        end
      end

      describe 'for invalid attributes' do
        before { allow(additional_respondent).to receive(:valid?).and_return false }

        it 'is not saved' do
          expect(target).not_to receive(:update_attributes)
          additional_respondent.save
        end

        it 'is false' do
          expect(additional_respondent.save).to be false
        end
      end

      describe 'when marked for destruction' do
        before { additional_respondent._destroy = 'true' }

        it 'destroys the target' do
          expect(target).to receive :destroy
          additional_respondent.save
        end

        it 'is true' do
          expect(additional_respondent.save).to be true
        end
      end
    end
  end

  context 'shared validation' do
    subject { additional_respondent }

    include_examples "Postcode validation",
      attribute_prefix: 'address',
      error_message: 'Enter a valid UK postcode. If you live abroad, enter SW55 9QT'
  end
end


text:
"""
Functions creating readable objects.

These objects are readable because they have `readline` and `read` methods.
They are used to to create `Response` objects using `Response.from_readable`.
"""

from __future__ import absolute_import, unicode_literals, print_function
import os
import errno
import sys
import tarfile
from io import FileIO
from threading import local
from functools import partial as partial_
from contextlib import closing
from six import PY2
from . import py2compat
assert py2compat
from .url import URL

EXT_WEXIN = '.wexin'
LF = b'\n'

class partial(partial_):
    def __repr__(self):
        """ Customized __repr__ for use with `Open` class. """
        return '%r, %r' % (self.func, self.args)

class Open(object):
    """ Lazily open a readable, when asked for read/readline.

    The reason we want to lazily open the readable is because
    that makes this object pickleable in its pre-opened state
    and that allows us to send the readable into a
    `multiprocessing.Pool`.
    """

    def __init__(self, open):
        self.open = open

    def __repr__(self):
        return 'Open(%r)' % self.open

    def __getattr__(self, name):
        if name not in ('readline', 'read', 'close', 'name'):
            raise AttributeError
        fp = self.open()

        self.__dict__['read'] = fp.read
        self.__dict__['readline'] = fp.readline
        self.__dict__['close'] = fp.close
        if hasattr(fp, 'name'):
            self.__dict__['name'] = fp.name

        assert name in self.__dict__
        return self.__dict__[name]

_open_tarfile = local()
_open_tarfile.tarfile = None

def tarfile_open(path):
    tarfileobj = getattr(_open_tarfile, 'tarfile', None)
    if tarfileobj is not None:
        if tarfileobj.name == path and not tarfileobj.closed:
            # same tarfile - no need to re-open
            return tarfileobj
        # there shouldn't be any problem closing this
        # because the fact that we have been asked to
        # open another tarfile will always mean that this
        # process has moved on to a different file.
        tarfileobj.close()

    _open_tarfile.tarfile = tarfile.open(path, 'r')
    return _open_tarfile.tarfile

def tarfile_tarinfo_open(path, tarinfo):
    tf = tarfile_open(path)
    return tf.extractfile(tarinfo)

def readables_from_paths(paths, save_dir=None):
    """ Yield readables from a sequence of paths """

    for path in paths:
        if path.strip() == b'-':
            stdin = sys.stdin if PY2 else sys.stdin.buffer
            tar = tarfile.open(mode='r|*', fileobj=stdin)
            for member in tar:
                if member.name.endswith(EXT_WEXIN):
                    yield tar.extractfile(member)
        elif not os.path.exists(path) and URL(path).parsed.scheme:
            url = URL(path)
            readables = url.get()
            if save_dir:
                readables = save_readables(url, save_dir, readables)
            for readable in readables:
                yield readable
        else:
            for readable in readables_from_file_path(path):
                yield readable

def save_readables(url, save_dir, readables):
    url_dir = url.mkdirs(save_dir)
    for i, readable in enumerate(readables):
        basename = '{}{}'.format(i, EXT_WEXIN)
        path = os.path.join(url_dir, basename)
        fp = FileIO(path, 'w')
        readable = TeeReadable(readable, fp)
        with closing(readable):
            yield readable

def readables_from_file_path(path):
    """ Yield readables from a file system path """

    numdirs = 0
    for dirpath, dirnames, filenames in os.walk(path):
        numdirs += 1
        # Don't walk into "hidden" directories
        dirnames[:] = [n for n in dirnames if not n.startswith('.')]
        for filename in filenames:
            if filename.lower().endswith(EXT_WEXIN):
                filepath = os.path.join(dirpath, filename)
                yield Open(partial(FileIO, filepath))

    if numdirs < 1:
        if path.lower().endswith('EXT_WEXIN'):
            yield Open(partial(FileIO, path))
        else:
            try:
                tf = tarfile_open(path)
                for readable in readables_from_tarfile(tf):
                    yield readable
            except IOError as exc:
                if exc.errno != errno.ENOENT:
                    raise
                # we want to defer the ENOENT error to later
                # so we do that by yielding an Open(...)
                yield Open(partial(FileIO, path))
            except tarfile.ReadError:
                yield Open(partial(FileIO, path))

def readables_from_tarfile(tf):
    for ti in tf:
        if ti.name.endswith(EXT_WEXIN):
            yield Open(partial(tarfile_tarinfo_open, tf.name, ti))

class TeeReadable(object):
    """ Readable that writes out to a tee file. """

    def __init__(self, readable, tee):
        self.readable = readable
        self.tee = tee

    @property
    def name(self):
        return self.tee.name

    def read(self, size):
        buf = self.readable.read(size)
        if buf:
            self.tee.write(buf)
        return buf

    def readline(self, *args):
        buf = self.readable.readline(*args)
        if buf:
            self.tee.write(buf)
        return buf

    def close(self):
        if not getattr(self.readable, 'closed', False):
            # read remainder so tee gets everything
            chunk_size = 2**16
            while True:
                chunk = self.read(chunk_size)
                if not chunk:
                    break
        self.readable.close()
        self.tee.close()

class ChainedReadable(object):
    """ Readable that combines the contents of multiple filelike together """

    EMPTY = b''

    def __init__(self, *files):
        self.files = files
        self.n = 0

    def read(self, size):
        buf = self.EMPTY
        while len(buf) < size and self.n < len(self.files):
            chunk = self.files[self.n].read(size - len(buf))
            if not chunk:
                self.n += 1
            buf += chunk
        return buf

    def readline(self, *args):
        if self.n >= len(self.files):
            return self.EMPTY
        buf = self.files[self.n].readline(*args)
        while LF not in buf and (not args or len(buf) < args[0]):
            self.n += 1
            if self.n >= len(self.files):
                break
            # OK so this can end up reading a line > limit but it isn't
            # going to really matter so we just ignore the possibiity.
            # We don't want to have to manage remainders unless we have to.
            buf += self.files[self.n].readline(*args)
        return buf

    def close(self):
        for fileobj in self.files:
            fileobj.close()


text:
module BraintreeRails
  class CreditCardValidator < Validator
    Validations = [
      [:cardholder_name, :length => {:maximum => 255}],
      [:customer_id, :presence => true, :length => {:maximum => 36}, :on => :create],
      [:number, :presence => true, :allow_blank => false, :if => :new_record?],
      [:number, :numericality => {:only_integer => true}, :length => {:minimum => 12, :maximum => 19}, 'braintree_rails/luhn_10' => true, :if => Proc.new { Configuration.mode == Configuration::Mode::S2S }],
      [:cvv, :presence => true, :allow_blank => false, :if => :new_record?],
      [:cvv, :numericality => {:only_integer => true}, :length => {:minimum => 3, :maximum => 4}, :if => Proc.new { Configuration.mode == Configuration::Mode::S2S }],
      [:expiration_month, :presence => true, :if => Proc.new { |credit_card| credit_card.new_record? && credit_card.expiration_date.blank? }],
      [:expiration_year, :presence => true, :if => Proc.new { |credit_card| credit_card.new_record? && credit_card.expiration_date.blank? }],
      [:expiration_date, :presence => true, :if => Proc.new { |credit_card| credit_card.new_record? && credit_card.expiration_month.blank? }],
      [:expiration_month, :numericality => { :only_integer => true, :greater_than_or_equal_to => 1, :less_than_or_equal_to => 12 }, :if => Proc.new { Configuration.mode == Configuration::Mode::S2S }],
      [:expiration_year, :numericality => { :only_integer => true, :greater_than_or_equal_to => 1976, :less_than_or_equal_to => 2200 }, :if => Proc.new { Configuration.mode == Configuration::Mode::S2S }],
      [:billing_address, :presence => true, :if => Proc.new {Configuration.require_postal_code || Configuration.require_street_address}],
    ]

    def validate(credit_card)
      validate_association(credit_card, :billing_address)
    end
  end
end


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Xunit;
using Nmqtt;

namespace NmqttTests.Messages.Publish
{
    /// <summary>
    /// MQTT Message Publish Tests
    /// </summary>
    public class Deserialization
    {
        /// <summary>
        /// Tests basic message deserialization from a raw byte array.
        /// </summary>
        [Fact]
        public void ValidPayload()
        {
            // Message Specs________________
            // <30><0C><00><04>fredhello!
            var sampleMessage = new[]
            {
                (byte)0x30,
                (byte)0x0C,
                (byte)0x0,
                (byte)0x4,
                (byte)'f',
                (byte)'r',
                (byte)'e',
                (byte)'d',
                // message payload is here
                (byte)'h',
                (byte)'e',
                (byte)'l',
                (byte)'l',
                (byte)'o',
                (byte)'!',
            };

            MqttMessage baseMessage = MqttMessage.CreateFrom(sampleMessage);

            Console.WriteLine(baseMessage.ToString());

            // check that the message was correctly identified as a connect message.
            Assert.IsType<MqttPublishMessage>(baseMessage);
            MqttPublishMessage message = (MqttPublishMessage)baseMessage;

            // validate the message deserialization
            Assert.Equal<bool>(false, message.Header.Duplicate);
            Assert.Equal<bool>(false, message.Header.Retain);
            Assert.Equal<MqttQos>(MqttQos.AtMostOnce, message.Header.Qos);
            Assert.Equal<MqttMessageType>(MqttMessageType.Publish, message.Header.MessageType);
            Assert.Equal<int>(12, message.Header.MessageSize);

            // make sure the publish message length matches the expectred size.
            Assert.Equal<int>(6, message.Payload.Message.Count);
        }

        /// <summary>
        /// Tests basic message deserialization from a raw byte array.
        /// </summary>
        [Fact]
        public void PayloadTooShort()
        {
            // Message Specs________________
            // <30><0C><00><04>fredhello!
            var sampleMessage = new[]
            {
                (byte)0x30,
                (byte)0x0C,
                (byte)0x0,
                (byte)0x4,
                (byte)'f',
                (byte)'r',
                (byte)'e',
                (byte)'d',
                // message payload is here
                (byte)'h',
                (byte)'e',
                (byte)'l',
                (byte)'l',
                (byte)'o',
            };

            Assert.Throws<InvalidPayloadSizeException>(() => MqttMessage.CreateFrom(sampleMessage));
        }
    }
}


text:
package com.funtl.framework.alipay.trade.pay.protocol.downloadbill.util;

import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

/**
 * This class is used to represent a ZIP file entry.
 *
 * @author David Connelly
 * @version 1.42, 01/02/08
 */
public class ZipEntry implements ZipConstants, Cloneable {
	String name;    // entry name
	long time = -1;    // modification time (in DOS time)
	long crc = -1;    // crc-32 of entry data
	long size = -1;    // uncompressed size of entry data
	long csize = -1;    // compressed size of entry data
	int method = -1;    // compression method
	byte[] extra;       // optional extra field data for entry
	String comment;     // optional comment string for entry

	/**
	 * Compression method for uncompressed entries.
	 */
	public static final int STORED = 0;

	/**
	 * Compression method for compressed (deflated) entries.
	 */
	public static final int DEFLATED = 8;

	static {
	/* Zip library is loaded from System.initializeSystemClass */
		//initIDs();
	}

	private static native void initIDs();

	/**
	 * Creates a new zip entry with the specified name.
	 *
	 * @param name the entry name
	 * @throws NullPointerException     if the entry name is null
	 * @throws IllegalArgumentException if the entry name is longer than
	 *                                  0xFFFF bytes
	 */
	public ZipEntry(String name) {
		if (name == null) {
			throw new NullPointerException();
		}
		if (name.length() > 0xFFFF) {
			throw new IllegalArgumentException("entry name too long");
		}
		this.name = name;
	}

	/**
	 * Creates a new zip entry with fields taken from the specified
	 * zip entry.
	 *
	 * @param e a zip Entry object
	 */
	public ZipEntry(ZipEntry e) {
		name = e.name;
		time = e.time;
		crc = e.crc;
		size = e.size;
		csize = e.csize;
		method = e.method;
		extra = e.extra;
		comment = e.comment;
	}

	/*
	 * Creates a new zip entry for the given name with fields initialized
	 * from the specified jzentry data.
	 */
	ZipEntry(String name, long jzentry) {
		this.name = name;
		initFields(jzentry);
	}

	private native void initFields(long jzentry);

	/*
	 * Creates a new zip entry with fields initialized from the specified
	 * jzentry data.
	 */
	ZipEntry(long jzentry) {
		initFields(jzentry);
	}

	/**
	 * Returns the name of the entry.
	 *
	 * @return the name of the entry
	 */
	public String getName() {
		return name;
	}

	/**
	 * Sets the modification time of the entry.
	 *
	 * @param time the entry modification time in number of milliseconds
	 *             since the epoch
	 * @see #getTime()
	 */
	public void setTime(long time) {
		// fix for bug 6625963: we bypass time calculations while Kernel is
		// downloading bundles, since they aren't necessary and would cause
		// the Kernel core to depend upon the (very large) time zone data

		this.time = javaToDosTime(time);
	}

	/**
	 * Returns the modification time of the entry, or -1 if not specified.
	 *
	 * @return the modification time of the entry, or -1 if not specified
	 * @see #setTime(long)
	 */
	public long getTime() {
		return time != -1 ? dosToJavaTime(time) : -1;
	}

	/**
	 * Sets the uncompressed size of the entry data.
	 *
	 * @param size the uncompressed size in bytes
	 * @throws IllegalArgumentException if the specified size is less
	 *                                  than 0 or greater than 0xFFFFFFFF bytes
	 * @see #getSize()
	 */
	public void setSize(long size) {
		if (size < 0 || size > 0xFFFFFFFFL) {
			throw new IllegalArgumentException("invalid entry size");
		}
		this.size = size;
	}

	/**
	 * Returns the uncompressed size of the entry data, or -1 if not known.
	 *
	 * @return the uncompressed size of the entry data, or -1 if not known
	 * @see #setSize(long)
	 */
	public long getSize() {
		return size;
	}

	/**
	 * Returns the size of the compressed entry data, or -1 if not known.
	 * In the case of a stored entry, the compressed size will be the same
	 * as the uncompressed size of the entry.
	 *
	 * @return the size of the compressed entry data, or -1 if not known
	 * @see #setCompressedSize(long)
	 */
	public long getCompressedSize() {
		return csize;
	}

	/**
	 * Sets the size of the compressed entry data.
	 *
	 * @param csize the compressed size to set to
	 * @see #getCompressedSize()
	 */
	public void setCompressedSize(long csize) {
		this.csize = csize;
	}

	/**
	 * Sets the CRC-32 checksum of the uncompressed entry data.
	 *
	 * @param crc the CRC-32 value
	 * @throws IllegalArgumentException if the specified CRC-32 value is
	 *                                  less than 0 or greater than 0xFFFFFFFF
	 * @see #getCrc()
	 */
	public void setCrc(long crc) {
		if (crc < 0 || crc > 0xFFFFFFFFL) {
			throw new IllegalArgumentException("invalid entry crc-32");
		}
		this.crc = crc;
	}

	/**
	 * Returns the CRC-32 checksum of the uncompressed entry data, or -1 if
	 * not known.
	 *
	 * @return the CRC-32 checksum of the uncompressed entry data, or -1 if
	 * not known
	 * @see #setCrc(long)
	 */
	public long getCrc() {
		return crc;
	}

	/**
	 * Sets the compression method for the entry.
	 *
	 * @param method the compression method, either STORED or DEFLATED
	 * @throws IllegalArgumentException if the specified compression
	 *                                  method is invalid
	 * @see #getMethod()
	 */
	public void setMethod(int method) {
		if (method != STORED && method != DEFLATED) {
			throw new IllegalArgumentException("invalid compression method");
		}
		this.method = method;
	}

	/**
	 * Returns the compression method of the entry, or -1 if not specified.
	 *
	 * @return the compression method of the entry, or -1 if not specified
	 * @see #setMethod(int)
	 */
	public int getMethod() {
		return method;
	}

	/**
	 * Sets the optional extra field data for the entry.
	 *
	 * @param extra the extra field data bytes
	 * @throws IllegalArgumentException if the length of the specified
	 *                                  extra field data is greater than 0xFFFF bytes
	 * @see #getExtra()
	 */
	public void setExtra(byte[] extra) {
		if (extra != null && extra.length > 0xFFFF) {
			throw new IllegalArgumentException("invalid extra field length");
		}
		this.extra = extra;
	}

	/**
	 * Returns the extra field data for the entry, or null if none.
	 *
	 * @return the extra field data for the entry, or null if none
	 * @see #setExtra(byte[])
	 */
	public byte[] getExtra() {
		return extra;
	}

	/**
	 * Sets the optional comment string for the entry.
	 *
	 * @param comment the comment string
	 * @throws IllegalArgumentException if the length of the specified
	 *                                  comment string is greater than 0xFFFF bytes
	 * @see #getComment()
	 */
	public void setComment(String comment) {
		if (comment != null && comment.length() > 0xffff / 3 && ZipOutputStream.getUTF8Length(comment) > 0xffff) {
			throw new IllegalArgumentException("invalid entry comment length");
		}
		this.comment = comment;
	}

	/**
	 * Returns the comment string for the entry, or null if none.
	 *
	 * @return the comment string for the entry, or null if none
	 * @see #setComment(String)
	 */
	public String getComment() {
		return comment;
	}

	/**
	 * Returns true if this is a directory entry. A directory entry is
	 * defined to be one whose name ends with a '/'.
	 *
	 * @return true if this is a directory entry
	 */
	public boolean isDirectory() {
		return name.endsWith("/");
	}

	/**
	 * Returns a string representation of the ZIP entry.
	 */
	public String toString() {
		return getName();
	}

	/*
	 * Converts DOS time to Java time (number of milliseconds since epoch).
	 */
	private static long dosToJavaTime(long dtime) {
		Date d = new GregorianCalendar((int) (((dtime >> 25) & 0x7f) + 80) + 1900, (int) (((dtime >> 21) & 0x0f) - 1), (int) ((dtime >> 16) & 0x1f), (int) ((dtime >> 11) & 0x1f), (int) ((dtime >> 5) & 0x3f), (int) ((dtime << 1) & 0x3e)).getTime();
		return d.getTime();
	}

	/*
	 * Converts Java time to DOS time.
	 */
	private static long javaToDosTime(long time) {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(new Date(Long.parseLong("1480520998663")));
		int year = calendar.get(Calendar.YEAR);
		if (year < 1980) {
			return (1 << 21) | (1 << 16);
		}

		return (year - 1980) << 25 | (calendar.get(Calendar.MONTH) + 1) << 21 | calendar.get(Calendar.DATE) << 16 | calendar.get(Calendar.HOUR_OF_DAY) << 11 | calendar.get(Calendar.MINUTE) << 5 | calendar.get(Calendar.SECOND) >> 1;
	}

	/**
	 * Returns the hash code value for this entry.
	 */
	public int hashCode() {
		return name.hashCode();
	}

	/**
	 * Returns a copy of this entry.
	 */
	public Object clone() {
		try {
			ZipEntry e = (ZipEntry) super.clone();
			e.extra = (extra == null ? null : (byte[]) extra.clone());
			return e;
		} catch (CloneNotSupportedException e) {
			// This should never happen, since we are Cloneable
			throw new InternalError();
		}
	}
}


text:
'use strict';

angular.module('promiseSamplesApp')
	.controller('sample9Controller', ['SamplesService', 'LogService',
		function (SamplesService, LogService) {
			var sample = this;

			LogService.clear();

			sample.name = 'Sample 9';
			sample.desc = 'callbacks can return promises';
			sample.messages = LogService.messages;
			sample.notes = "When a callback returns a promise \
							$q will wait for that promise to resolve \
							before proceding. The state of the promise \
							will determine which callback will be \
							executed next. It is just like if there was another \
							promise in the chain.";

			LogService.log('sample 9 started');

			// if a callback returns a promise
			// $q will wait for that promise to resolve
			// before continuing thru callback chain
			// with that promise state
			SamplesService.getListOfStuffTimedOut()
				.catch(function(reason) {
					LogService.log(reason);
					LogService.log('Retrying with alternative stuff source');
					return SamplesService.delay(2000)
						.then(SamplesService.getListOfStuff);
				})
				.then(SamplesService.getFirstItem)
				.then(LogService.log)
				.catch(LogService.log);

			LogService.log('sample 9 ended');
		}
	]);


text:
<link rel="import" href="../../../../bower_components/polymer/polymer-element.html">

<dom-module id="user-reviews-fragment">
  <template>

user-reviews-fragment

userId: [[userId]]

    <button on-click="__backToRoot">BACK to '/'</button>
    <button on-click="__backToUserProfile">BACK to '/[[userId]]'</button>
  </template>

</dom-module>


text:
using NUnit.Framework;
using VkNet.Enums.SafetyEnums;

namespace VkNet.Tests.Models
{
	[TestFixture]
	public class MessageActionModel : BaseTest
	{
		[Test]
		public void ShouldHaveField_ChatCreate()
		{
			Json = "{'action':'chat_create'}";
			var response = GetResponse();
			var action = MessageAction.FromJsonString(response: response[key: "action"]);
			Assert.That(actual: action, expression: Is.EqualTo(expected: MessageAction.ChatCreate));
		}

		[Test]
		public void ShouldHaveField_ChatInviteUser()
		{
			Json = "{'action':'chat_invite_user'}";
			var response = GetResponse();
			var action = MessageAction.FromJsonString(response: response[key: "action"]);
			Assert.That(actual: action, expression: Is.EqualTo(expected: MessageAction.ChatInviteUser));
		}

		[Test]
		public void ShouldHaveField_ChatInviteUserByLink()
		{
			Json = "{'action':'chat_invite_user_by_link'}";
			var response = GetResponse();
			var action = MessageAction.FromJsonString(response: response[key: "action"]);
			Assert.That(actual: action, expression: Is.EqualTo(expected: MessageAction.ChatInviteUserByLink));
		}

		[Test]
		public void ShouldHaveField_ChatKickUser()
		{
			Json = "{'action':'chat_kick_user'}";
			var response = GetResponse();
			var action = MessageAction.FromJsonString(response: response[key: "action"]);
			Assert.That(actual: action, expression: Is.EqualTo(expected: MessageAction.ChatKickUser));
		}

		[Test]
		public void ShouldHaveField_ChatPhotoRemove()
		{
			Json = "{'action':'chat_photo_remove'}";
			var response = GetResponse();
			var action = MessageAction.FromJsonString(response: response[key: "action"]);
			Assert.That(actual: action, expression: Is.EqualTo(expected: MessageAction.ChatPhotoRemove));
		}

		[Test]
		public void ShouldHaveField_ChatPhotoUpdate()
		{
			Json = "{'action':'chat_photo_update'}";
			var response = GetResponse();
			var action = MessageAction.FromJsonString(response: response[key: "action"]);
			Assert.That(actual: action, expression: Is.EqualTo(expected: MessageAction.ChatPhotoUpdate));
		}

		[Test]
		public void ShouldHaveField_ChatPinMessage()
		{
			Json = "{'action':'chat_pin_message'}";
			var response = GetResponse();
			var action = MessageAction.FromJsonString(response: response[key: "action"]);
			Assert.That(actual: action, expression: Is.EqualTo(expected: MessageAction.ChatPinMessage));
		}

		[Test]
		public void ShouldHaveField_ChatTitleUpdate()
		{
			Json = "{'action':'chat_title_update'}";
			var response = GetResponse();
			var action = MessageAction.FromJsonString(response: response[key: "action"]);
			Assert.That(actual: action, expression: Is.EqualTo(expected: MessageAction.ChatTitleUpdate));
		}

		[Test]
		public void ShouldHaveField_ChatUnpinMessage()
		{
			Json = "{'action':'chat_unpin_message'}";
			var response = GetResponse();
			var action = MessageAction.FromJsonString(response: response[key: "action"]);
			Assert.That(actual: action, expression: Is.EqualTo(expected: MessageAction.ChatUnpinMessage));
		}
	}
}


text:
<?php

namespace AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
use Gedmo\Mapping\Annotation as Gedmo;

/**
 * Category
 *
 * @ORM\Table(name="category")
 * @ORM\Entity(repositoryClass="AppBundle\Repository\CategoryRepository")
 */
class Category
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="name", type="string", length=255)
     */
    private $name;

    /**
     * @var string
     *
     * @Gedmo\Slug(fields={"name"})
     * @ORM\Column(unique=true, length=255)
     */
    private $slug;

    /**
     * @var text
     *
     * @ORM\Column(name="description", type="text", nullable=true)
     */
    private $description;

    /**
     *
     * @ORM\OneToMany(targetEntity="Product", mappedBy="category")
     */
    private $products;

    public function __construct()
    {
        $this->products = new ArrayCollection();
    }

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

    /**
     * Set name
     *
     * @param string $name
     * @return Category
     */
    public function setName($name)
    {
        $this->name = $name;

        return $this;
    }

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

    /**
     * Add products
     *
     * @param \AppBundle\Entity\Product $products
     * @return Category
     */
    public function addProduct(\AppBundle\Entity\Product $products)
    {
        $this->products[] = $products;

        return $this;
    }

    /**
     * Remove products
     *
     * @param \AppBundle\Entity\Product $products
     */
    public function removeProduct(\AppBundle\Entity\Product $products)
    {
        $this->products->removeElement($products);
    }

    /**
     * Get products
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getProducts()
    {
        return $this->products;
    }

    public function __toString()
    {
        return $this->name;
    }

    /**
     * Set slug
     *
     * @param string $slug
     * @return Category
     */
    public function setSlug($slug)
    {
        $this->slug = $slug;

        return $this;
    }

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

    /**
     * Set description
     *
     * @param string $description
     * @return Category
     */
    public function setDescription($description)
    {
        $this->description = $description;

        return $this;
    }

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


text:
import gc
import importlib.util
import inspect
import os
from pathlib import Path
import shlex
import subprocess
import sys

import sphinx_gallery

# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
curr_path = Path(__file__).expanduser().absolute().parent
if curr_path.name == "_staging":
    # Can't use curr_path.parent, because sphinx_gallery requires a relative path.
    tvm_path = Path(os.pardir, os.pardir)
else:
    tvm_path = Path(os.pardir)

sys.path.insert(0, str(tvm_path.resolve() / "python"))
sys.path.insert(0, str(tvm_path.resolve() / "vta" / "python"))
sys.path.insert(0, str(tvm_path.resolve() / "docs"))

# -- General configuration ------------------------------------------------

# General information about the project.
project = "tvm"
author = "Apache Software Foundation"
copyright = "2020 - 2021, %s" % author
github_doc_root = "https://github.com/apache/tvm/tree/main/docs/"

os.environ["TVM_BUILD_DOC"] = "1"

def git_describe_version(original_version):
    """Get git describe version."""
    ver_py = tvm_path.joinpath("version.py")
    libver = {"__file__": ver_py}
    exec(compile(open(ver_py, "rb").read(), ver_py, "exec"), libver, libver)
    _, gd_version = libver["git_describe_version"]()
    if gd_version != original_version:
        print("Use git describe based version %s" % gd_version)
    return gd_version

# Version information.
import tvm
from tvm import topi
from tvm import te
from tvm import testing

version = git_describe_version(tvm.__version__)
release = version

# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom ones
extensions = [
    "sphinx.ext.autodoc",
    "sphinx.ext.autosummary",
    "sphinx.ext.intersphinx",
    "sphinx.ext.napoleon",
    "sphinx.ext.mathjax",
    "sphinx_gallery.gen_gallery",
    "autodocsumm",
]

# Add any paths that contain templates here, relative to this directory.
templates_path = ["_templates"]

# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
# source_suffix = ['.rst', '.md']
source_suffix = [".rst", ".md"]

# The encoding of source files.
# source_encoding = 'utf-8-sig'

# generate autosummary even if no references
autosummary_generate = True

# The master toctree document.
master_doc = "index"

# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#
# This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for these cases.
language = None

# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
# today = ''
# Else, today_fmt is used as the format for a strftime call.
# today_fmt = '%B %d, %Y'

# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ["_build", "_staging"]

# The reST default role (used for this markup: `text`) to use for all
# documents.
# default_role = None

# If true, '()' will be appended to :func: etc. cross-reference text.
# add_function_parentheses = True

# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
# add_module_names = True

# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
# show_authors = False

# The name of the Pygments (syntax highlighting) style to use.
pygments_style = "sphinx"

# A list of ignored prefixes for module index sorting.
# modindex_common_prefix = []

# If true, keep warnings as "system message" paragraphs in the built documents.
# keep_warnings = False

# If true, `todo` and `todoList` produce output, else they produce nothing.
todo_include_todos = False

# -- Options for HTML output ----------------------------------------------

# The theme is set by the make target
html_theme = os.environ.get("TVM_THEME", "rtd")

on_rtd = os.environ.get("READTHEDOCS", None) == "True"
# only import rtd theme and set it if want to build docs locally
if not on_rtd and html_theme == "rtd":
    import sphinx_rtd_theme

    html_theme = "sphinx_rtd_theme"
    html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]

# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ["_static"]

html_theme_options = {
    "analytics_id": "UA-75982049-2",
    "logo_only": True,
}

html_logo = "_static/img/tvm-logo-small.png"

html_favicon = "_static/img/tvm-logo-square.png"

# Output file base name for HTML help builder.
htmlhelp_basename = project + "doc"

# -- Options for LaTeX output ---------------------------------------------
latex_elements = {}

# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
#  author, documentclass [howto, manual, or own class]).
latex_documents = [
    (master_doc, "%s.tex" % project, project, author, "manual"),
]

intersphinx_mapping = {
    "python": ("https://docs.python.org/{.major}".format(sys.version_info), None),
    "numpy": ("https://numpy.org/doc/stable", None),
    "scipy": ("https://docs.scipy.org/doc/scipy-1.8.0/html-scipyorg/", None),
    "matplotlib": ("https://matplotlib.org/", None),
}

from sphinx_gallery.sorting import ExplicitOrder

examples_dirs = [
    tvm_path.joinpath("gallery", "tutorial"),
    tvm_path.joinpath("gallery", "how_to", "compile_models"),
    tvm_path.joinpath("gallery", "how_to", "deploy_models"),
    tvm_path.joinpath("gallery", "how_to", "work_with_relay"),
    tvm_path.joinpath("gallery", "how_to", "work_with_schedules"),
    tvm_path.joinpath("gallery", "how_to", "optimize_operators"),
    tvm_path.joinpath("gallery", "how_to", "tune_with_autotvm"),
    tvm_path.joinpath("gallery", "how_to", "tune_with_autoscheduler"),
    tvm_path.joinpath("gallery", "how_to", "work_with_microtvm"),
    tvm_path.joinpath("gallery", "how_to", "extend_tvm"),
    tvm_path.joinpath("vta", "tutorials"),
]

gallery_dirs = [
    "tutorial",
    "how_to/compile_models",
    "how_to/deploy_models",
    "how_to/work_with_relay",
    "how_to/work_with_schedules",
    "how_to/optimize_operators",
    "how_to/tune_with_autotvm",
    "how_to/tune_with_autoscheduler",
    "how_to/work_with_microtvm",
    "how_to/extend_tvm",
    "topic/vta/tutorials",
]

subsection_order = ExplicitOrder(
    str(p)
    for p in [
        tvm_path / "vta" / "tutorials" / "frontend",
        tvm_path / "vta" / "tutorials" / "optimize",
        tvm_path / "vta" / "tutorials" / "autotvm",
    ]
)

# Explicitly define the order within a subsection.
# The listed files are sorted according to the list.
# The unlisted files are sorted by filenames.
# The unlisted files always appear after listed files.
within_subsection_order = {
    "tutorial": [
        "introduction.py",
        "install.py",
        "tvmc_command_line_driver.py",
        "tvmc_python.py",
        "autotvm_relay_x86.py",
        "tensor_expr_get_started.py",
        "autotvm_matmul_x86.py",
        "auto_scheduler_matmul_x86.py",
        "tensor_ir_blitz_course.py",
        "topi.pi",
        "cross_compilation_and_rpc.py",
        "relay_quick_start.py",
    ],
    "compile_models": [
        "from_pytorch.py",
        "from_tensorflow.py",
        "from_mxnet.py",
        "from_onnx.py",
        "from_keras.py",
        "from_tflite.py",
        "from_coreml.py",
        "from_darknet.py",
        "from_caffe2.py",
        "from_paddle.py",
    ],
    "work_with_schedules": [
        "schedule_primitives.py",
        "reduction.py",
        "intrin_math.py",
        "scan.py",
        "extern_op.py",
        "tensorize.py",
        "tuple_inputs.py",
        "tedd.py",
    ],
    "optimize_operators": [
        "opt_gemm.py",
        "opt_conv_cuda.py",
        "opt_conv_tensorcore.py",
    ],
    "tune_with_autotvm": [
        "tune_conv2d_cuda.py",
        "tune_relay_cuda.py",
        "tune_relay_x86.py",
        "tune_relay_arm.py",
        "tune_relay_mobile_gpu.py",
    ],
    "tune_with_autoscheduler": [
        "tune_matmul_x86.py",
        "tune_conv2d_layer_cuda.py",
        "tune_network_x86.py",
        "tune_network_cuda.py",
    ],
    "extend_tvm": [
        "low_level_custom_pass.py",
        "use_pass_infra.py",
        "use_pass_instrument.py",
        "bring_your_own_datatypes.py",
    ],
    "micro": [
        "micro_autotune.py",
        "micro_reference_vm.py",
        "micro_tflite.py",
        "micro_ethosu.py",
        "micro_tvmc.py",
    ],
}

class WithinSubsectionOrder:
    def __init__(self, src_dir):
        self.src_dir = src_dir.split("/")[-1]

    def __call__(self, filename):
        # If the order is provided, use the provided order
        if (
            self.src_dir in within_subsection_order
            and filename in within_subsection_order[self.src_dir]
        ):
            index = within_subsection_order[self.src_dir].index(filename)
            assert index < 1e10
            return "\0%010d" % index

        # Otherwise, sort by filename
        return filename

# When running the tutorials on GPUs we are dependent on the Python garbage collector
# collecting TVM packed function closures for any device memory to also be released. This
# is not a good setup for machines with lots of CPU ram but constrained GPU ram, so force
# a gc after each example.
def force_gc(gallery_conf, fname):
    gc.collect()

sphinx_gallery_conf = {
    "backreferences_dir": "gen_modules/backreferences",
    "doc_module": ("tvm", "numpy"),
    "reference_url": {
        "tvm": None,
        "matplotlib": "https://matplotlib.org/",
        "numpy": "https://numpy.org/doc/stable",
    },
    "examples_dirs": examples_dirs,
    "within_subsection_order": WithinSubsectionOrder,
    "gallery_dirs": gallery_dirs,
    "subsection_order": subsection_order,
    "filename_pattern": os.environ.get("TVM_TUTORIAL_EXEC_PATTERN", ".py"),
    "find_mayavi_figures": False,
    "download_all_examples": False,
    "min_reported_time": 60,
    "expected_failing_examples": [],
    "reset_modules": ("matplotlib", "seaborn", force_gc),
}

autodoc_default_options = {
    "member-order": "bysource",
}

# Maps the original namespace to list of potential modules
# that we can import alias from.
tvm_alias_check_map = {
    "tvm.te": ["tvm.tir"],
    "tvm.tir": ["tvm.ir", "tvm.runtime"],
    "tvm.relay": ["tvm.ir", "tvm.tir"],
}

## Setup header and other configs
import tlcpack_sphinx_addon

footer_copyright = "© 2020 Apache Software Foundation | All right reserved"
footer_note = " ".join(
    """
Copyright © 2020 The Apache Software Foundation. Apache TVM, Apache, the Apache feather,
and the Apache TVM project logo are either trademarks or registered trademarks of
the Apache Software Foundation.""".split(
        "\n"
    )
).strip()

header_logo = "https://tvm.apache.org/assets/images/logo.svg"
header_logo_link = "https://tvm.apache.org/"

header_links = [
    ("Community", "https://tvm.apache.org/community"),
    ("Download", "https://tvm.apache.org/download"),
    ("VTA", "https://tvm.apache.org/vta"),
    ("Blog", "https://tvm.apache.org/blog"),
    ("Docs", "https://tvm.apache.org/docs"),
    ("Conference", "https://tvmconf.org"),
    ("Github", "https://github.com/apache/tvm/"),
]

header_dropdown = {
    "name": "ASF",
    "items": [
        ("Apache Homepage", "https://apache.org/"),
        ("License", "https://www.apache.org/licenses/"),
        ("Sponsorship", "https://www.apache.org/foundation/sponsorship.html"),
        ("Security", "https://www.apache.org/security/"),
        ("Thanks", "https://www.apache.org/foundation/thanks.html"),
        ("Events", "https://www.apache.org/events/current-event"),
    ],
}

html_context = {
    "footer_copyright": footer_copyright,
    "footer_note": footer_note,
    "header_links": header_links,
    "header_dropdown": header_dropdown,
    "header_logo": header_logo,
    "header_logo_link": header_logo_link,
}

# add additional overrides
templates_path += [tlcpack_sphinx_addon.get_templates_path()]
html_static_path += [tlcpack_sphinx_addon.get_static_path()]

def update_alias_docstring(name, obj, lines):
    """Update the docstring of alias functions.

    This function checks if the obj is an alias of another documented object
    in a different module.

    If it is an alias, then it will append the alias information to the docstring.

    Parameters
    ----------
    name : str
        The full name of the object in the doc.

    obj : object
        The original object.

    lines : list
        The docstring lines, need to be modified inplace.
    """
    arr = name.rsplit(".", 1)
    if len(arr) != 2:
        return
    target_mod, target_name = arr

    if target_mod not in tvm_alias_check_map:
        return
    if not hasattr(obj, "__module__"):
        return
    obj_mod = obj.__module__

    for amod in tvm_alias_check_map[target_mod]:
        if not obj_mod.startswith(amod):
            continue

        if hasattr(sys.modules[amod], target_name):
            obj_type = ":py:func" if callable(obj) else ":py:class"
            lines.append(".. rubric:: Alias of %s:`%s.%s`" % (obj_type, amod, target_name))

def process_docstring(app, what, name, obj, options, lines):
    """Sphinx callback to process docstring"""
    if callable(obj) or inspect.isclass(obj):
        update_alias_docstring(name, obj, lines)

from legacy_redirect import build_legacy_redirect

def setup(app):
    app.connect("autodoc-process-docstring", process_docstring)
    app.connect("build-finished", build_legacy_redirect(tvm_path))


text:
import { Http } from './Http';

new Http();//{onListening: () => console.log('hello world')});


text:
RSpec.describe RuboCop::Cop::Style::RedundantParentheses, :config do
  shared_examples 'redundant' do |expr, correct, type|
    it "registers an offense for parentheses around #{type}" do
      expect_offense(<<~RUBY, expr: expr)
        %{expr}
        ^{expr} Don't use parentheses around #{type}.
      RUBY

      expect_correction(<<~RUBY)
        #{correct}
      RUBY
    end
  end

  shared_examples 'plausible' do |expr|
    it 'accepts parentheses when arguments are unparenthesized' do
      expect_no_offenses(expr)
    end
  end

  shared_examples 'keyword with return value' do |keyword|
    it_behaves_like 'redundant', "(#{keyword})", keyword, 'a keyword'
    it_behaves_like 'redundant', "(#{keyword}())", "#{keyword}()", 'a keyword'
    it_behaves_like 'redundant', "(#{keyword}(1))", "#{keyword}(1)", 'a keyword'
    it_behaves_like 'plausible', "(#{keyword} 1, 2)"
  end

  shared_examples 'keyword with arguments' do |keyword|
    it_behaves_like 'redundant', "(#{keyword})", keyword, 'a keyword'
    it_behaves_like 'redundant', "(#{keyword}())", "#{keyword}()", 'a keyword'
    it_behaves_like 'redundant', "(#{keyword}(1, 2))", "#{keyword}(1, 2)", 'a keyword'
    it_behaves_like 'plausible', "(#{keyword} 1, 2)"
  end

  it_behaves_like 'redundant', '("x")', '"x"', 'a literal'
  it_behaves_like 'redundant', '("#{x}")', '"#{x}"', 'a literal'
  it_behaves_like 'redundant', '(:x)', ':x', 'a literal'
  it_behaves_like 'redundant', '(:"#{x}")', ':"#{x}"', 'a literal'
  it_behaves_like 'redundant', '(1)', '1', 'a literal'
  it_behaves_like 'redundant', '(1.2)', '1.2', 'a literal'
  it_behaves_like 'redundant', '({})', '{}', 'a literal'
  it_behaves_like 'redundant', '([])', '[]', 'a literal'
  it_behaves_like 'redundant', '(nil)', 'nil', 'a literal'
  it_behaves_like 'redundant', '(true)', 'true', 'a literal'
  it_behaves_like 'redundant', '(false)', 'false', 'a literal'
  it_behaves_like 'redundant', '(/regexp/)', '/regexp/', 'a literal'
  it_behaves_like 'redundant', '("x"; "y")', '"x"; "y"', 'a literal'
  it_behaves_like 'redundant', '(1; 2)', '1; 2', 'a literal'
  it_behaves_like 'redundant', '(1i)', '1i', 'a literal'
  it_behaves_like 'redundant', '(1r)', '1r', 'a literal'
  it_behaves_like 'redundant', '(__FILE__)', '__FILE__', 'a keyword'
  it_behaves_like 'redundant', '(__LINE__)', '__LINE__', 'a keyword'
  it_behaves_like 'redundant', '(__ENCODING__)', '__ENCODING__', 'a keyword'
  it_behaves_like 'redundant', '(redo)', 'redo', 'a keyword'
  it_behaves_like 'redundant', '(retry)', 'retry', 'a keyword'
  it_behaves_like 'redundant', '(self)', 'self', 'a keyword'

  it 'registers an offense for parens around constant ternary condition' do
    expect_offense(<<~RUBY)
      (X) ? Y : N
      ^^^ Don't use parentheses around a constant.
      (X)? Y : N
      ^^^ Don't use parentheses around a constant.
    RUBY

    expect_correction(<<~RUBY)
      X ? Y : N
      X ? Y : N
    RUBY
  end

  it_behaves_like 'keyword with return value', 'break'
  it_behaves_like 'keyword with return value', 'next'
  it_behaves_like 'keyword with return value', 'return'

  it_behaves_like 'keyword with arguments', 'super'
  it_behaves_like 'keyword with arguments', 'yield'

  it_behaves_like 'redundant', '(defined?(:A))', 'defined?(:A)', 'a keyword'
  it_behaves_like 'plausible', '(defined? :A)'

  it_behaves_like 'plausible', '(alias a b)'
  it_behaves_like 'plausible', '(not 1)'
  it_behaves_like 'plausible', '(a until b)'
  it_behaves_like 'plausible', '(a while b)'

  it 'registers an offense for parens around a variable after semicolon' do
    expect_offense(<<~RUBY)
      x = 1; (x)
             ^^^ Don't use parentheses around a variable.
    RUBY

    expect_correction(<<~RUBY)
      x = 1; x
    RUBY
  end

  it_behaves_like 'redundant', '(@x)', '@x', 'a variable'
  it_behaves_like 'redundant', '(@@x)', '@@x', 'a variable'
  it_behaves_like 'redundant', '($x)', '$x', 'a variable'

  it_behaves_like 'redundant', '(X)', 'X', 'a constant'

  it_behaves_like 'redundant', '(x)', 'x', 'a method call'
  it_behaves_like 'redundant', '(x(1, 2))', 'x(1, 2)', 'a method call'
  it_behaves_like 'redundant', '("x".to_sym)', '"x".to_sym', 'a method call'
  it_behaves_like 'redundant', '("x"&.to_sym)', '"x"&.to_sym', 'a method call'
  it_behaves_like 'redundant', '(x[:y])', 'x[:y]', 'a method call'
  it_behaves_like 'redundant', '("foo"[0])', '"foo"[0]', 'a method call'
  it_behaves_like 'redundant', '(["foo"][0])', '["foo"][0]', 'a method call'
  it_behaves_like 'redundant', '({0 => :a}[0])', '{0 => :a}[0]', 'a method call'
  it_behaves_like 'redundant', '(x; y)', 'x; y', 'a method call'

  it_behaves_like 'redundant', '(!x)', '!x', 'an unary operation'
  it_behaves_like 'redundant', '(~x)', '~x', 'an unary operation'
  it_behaves_like 'redundant', '(-x)', '-x', 'an unary operation'
  it_behaves_like 'redundant', '(+x)', '+x', 'an unary operation'
  it_behaves_like 'plausible', '(!x.m arg)'
  it_behaves_like 'plausible', '(!x).y'
  it_behaves_like 'plausible', '-(1.foo)'
  it_behaves_like 'plausible', '+(1.foo)'
  it_behaves_like 'plausible', '-(1.foo.bar)'
  it_behaves_like 'plausible', '+(1.foo.bar)'
  it_behaves_like 'plausible', '()'

  it 'registers an offense for parens around an interpolated expression' do
    expect_offense(<<~RUBY)
      "\#{(foo)}"
         ^^^^^ Don't use parentheses around an interpolated expression.
    RUBY

    expect_correction(<<~RUBY)
      "\#{foo}"
    RUBY
  end

  it 'registers an offense for parens around a literal in array' do
    expect_offense(<<~RUBY)
      [(1)]
       ^^^ Don't use parentheses around a literal.
    RUBY

    expect_correction(<<~RUBY)
      [1]
    RUBY
  end

  it 'registers an offense for parens around a literal in array and following newline' do
    expect_offense(<<~RUBY)
      [(1
       ^^ Don't use parentheses around a literal.
      )]
    RUBY

    expect_correction(<<~RUBY)
      [1
      ]
    RUBY
  end

  it_behaves_like 'plausible', "[(1\n),]"

  it_behaves_like 'plausible', <<~RUBY
    [
      (
        1
      ),
      2
    ]
  RUBY

  it_behaves_like 'plausible', <<~RUBY
    [
      x = (
        1
      ),
      y = 2
    ]
  RUBY

  it 'registers an offense for parens around a literal hash value' do
    expect_offense(<<~RUBY)
      {a: (1)}
          ^^^ Don't use parentheses around a literal.
    RUBY

    expect_correction(<<~RUBY)
      {a: 1}
    RUBY
  end

  it 'registers an offense for parens around a literal hash value and following newline' do
    expect_offense(<<~RUBY)
      {a: (1
          ^^ Don't use parentheses around a literal.
      )}
    RUBY

    expect_correction(<<~RUBY)
      {a: 1
      }
    RUBY
  end

  it_behaves_like 'plausible', "{a: (1\n),}"

  it 'registers an offense for parens around an integer exponentiation base' do
    expect_offense(<<~RUBY)
      (0)**2
      ^^^ Don't use parentheses around a literal.
      (2)**2
      ^^^ Don't use parentheses around a literal.
    RUBY

    expect_correction(<<~RUBY)
      0**2
      2**2
    RUBY
  end

  it 'registers an offense for parens around a float exponentiation base' do
    expect_offense(<<~RUBY)
      (2.1)**2
      ^^^^^ Don't use parentheses around a literal.
    RUBY

    expect_correction(<<~RUBY)
      2.1**2
    RUBY
  end

  it 'registers an offense for parens around a negative exponent' do
    expect_offense(<<~RUBY)
      2**(-2)
         ^^^^ Don't use parentheses around a literal.
    RUBY

    expect_correction(<<~RUBY)
      2**-2
    RUBY
  end

  it 'registers an offense for parens around a positive exponent' do
    expect_offense(<<~RUBY)
      2**(2)
         ^^^ Don't use parentheses around a literal.
    RUBY

    expect_correction(<<~RUBY)
      2**2
    RUBY
  end

  it_behaves_like 'plausible', '(-2)**2'
  it_behaves_like 'plausible', '(-2.1)**2'

  it_behaves_like 'plausible', 'x = (foo; bar)'
  it_behaves_like 'plausible', 'x += (foo; bar)'
  it_behaves_like 'plausible', 'x + (foo; bar)'
  it_behaves_like 'plausible', 'x((foo; bar))'

  it 'registers an offense for parens around method body' do
    expect_offense(<<~RUBY)
      def x
        (foo; bar)
        ^^^^^^^^^^ Don't use parentheses around a method call.
      end
    RUBY

    expect_correction(<<~RUBY)
      def x
        foo; bar
      end
    RUBY
  end

  it 'registers an offense for parens around last expressions in method body' do
    expect_offense(<<~RUBY)
      def x
        baz
        (foo; bar)
        ^^^^^^^^^^ Don't use parentheses around a method call.
      end
    RUBY

    expect_correction(<<~RUBY)
      def x
        baz
        foo; bar
      end
    RUBY
  end

  it 'registers an offense for parens around a block body' do
    expect_offense(<<~RUBY)
      x do
        (foo; bar)
        ^^^^^^^^^^ Don't use parentheses around a method call.
      end
    RUBY

    expect_correction(<<~RUBY)
      x do
        foo; bar
      end
    RUBY
  end

  it 'registers an offense for parens around last expressions in block body' do
    expect_offense(<<~RUBY)
      x do
        baz
        (foo; bar)
        ^^^^^^^^^^ Don't use parentheses around a method call.
      end
    RUBY

    expect_correction(<<~RUBY)
      x do
        baz
        foo; bar
      end
    RUBY
  end

  it 'accepts parentheses around a method call with unparenthesized arguments' do
    expect_no_offenses('(a 1, 2) && (1 + 1)')
  end

  it 'accepts parentheses inside an irange' do
    expect_no_offenses('(a)..(b)')
  end

  it 'accepts parentheses inside an erange' do
    expect_no_offenses('(a)...(b)')
  end

  it 'accepts parentheses around an irange' do
    expect_no_offenses('(a..b)')
  end

  it 'accepts parentheses around an erange' do
    expect_no_offenses('(a...b)')
  end

  it 'accepts parentheses around operator keywords' do
    expect_no_offenses('(1 and 2) and (3 or 4)')
  end

  it 'registers an offense when there is space around the parentheses' do
    expect_offense(<<~RUBY)
      if x; y else (1) end
                   ^^^ Don't use parentheses around a literal.
    RUBY
  end

  it 'accepts parentheses when enclosed in parentheses at `while-post`' do
    expect_no_offenses(<<~RUBY)
      begin
        do_something
      end while(bar)
    RUBY
  end

  it 'accepts parentheses when enclosed in parentheses at `until-post`' do
    expect_no_offenses(<<~RUBY)
      begin
        do_something
      end until(bar)
    RUBY
  end

  it 'accepts parentheses when they touch the preceding keyword' do
    expect_no_offenses('if x; y else(1) end')
  end

  it 'accepts parentheses when they touch the following keyword' do
    expect_no_offenses('if x; y else (1)end')
  end

  context 'when the first argument in a method call begins with a hash literal' do
    it 'accepts parentheses if the argument list is not parenthesized' do
      expect_no_offenses('x ({ y: 1 }), z')
      expect_no_offenses('x ({ y: 1 }.merge({ y: 2 })), z')
      expect_no_offenses('x ({ y: 1 }.merge({ y: 2 }).merge({ y: 3 })), z')
    end

    it 'registers an offense if the argument list is parenthesized' do
      expect_offense(<<~RUBY)
        x(({ y: 1 }), z)
          ^^^^^^^^^^ Don't use parentheses around a literal.
      RUBY
    end
  end

  context 'when a hash literal is the second argument in a method call' do
    it 'registers an offense' do
      expect_offense(<<~RUBY)
        x ({ y: 1 }), ({ y: 1 })
                      ^^^^^^^^^^ Don't use parentheses around a literal.
      RUBY
    end
  end

  context 'when a non-parenthesized call has an arg and a block' do
    it 'accepts parens around the arg' do
      expect_no_offenses('method (:arg) { blah }')
    end
  end

  context 'when parentheses are used like method argument parentheses' do
    it 'accepts parens around the arg' do
      expect_no_offenses('method (arg)')
    end
  end

  it 'accepts parentheses around the error passed to rescue' do
    expect_no_offenses(<<~RUBY)
      begin
        some_method
      rescue(StandardError)
      end
    RUBY
  end

  it 'accepts parentheses around a constant passed to when' do
    expect_no_offenses(<<~RUBY)
      case foo
      when(Const)
        bar
      end
    RUBY
  end

  it 'accepts parentheses in super call with hash' do
    expect_no_offenses(<<~RUBY)
      super ({
        foo: bar,
      })
    RUBY
  end

  it 'accepts parentheses in yield call with hash' do
    expect_no_offenses(<<~RUBY)
      yield ({
        foo: bar,
      })
    RUBY
  end
end


text:
Direct Chat

					<button class="btn btn-box-tool" data-widget="collapse"></button>

					<?php include_once 'message_list.php'; ?>

				<form action="#" method="post" class="nodeMessageForm">
					<input type="hidden" name="add_message" value="1">
					<input type="hidden" name="id_user" class="id_user" value="<?php echo $activeUser->id_user; ?>">

						<input type="text" name="message" placeholder="Type Message ..." class="form-control message">

							<button type="submit" class="btn btn-primary btn-flat">Send</button>

				</form>


text:
package org.batfish.question.bidirectionalreachability;

import com.google.common.collect.ImmutableMap;
import java.util.Map;
import javax.annotation.ParametersAreNonnullByDefault;
import net.sf.javabdd.BDD;
import org.batfish.specifier.Location;

/** The result of a bidirectional reachability analysis. */
@ParametersAreNonnullByDefault
public class BidirectionalReachabilityResult {
  private final Map<Location, BDD> _startLocationReturnPassFailureBdds;

  private final Map<Location, BDD> _startLocationReturnPassSuccessBdds;

  public BidirectionalReachabilityResult(
      Map<Location, BDD> startLocationReturnPassSuccessBdds,
      Map<Location, BDD> startLocationReturnPassFailureBdds) {
    _startLocationReturnPassSuccessBdds = ImmutableMap.copyOf(startLocationReturnPassSuccessBdds);
    _startLocationReturnPassFailureBdds = ImmutableMap.copyOf(startLocationReturnPassFailureBdds);
  }

  /**
   * @return A {@link BDD} representing the set of packets at each {@link Location} for which the
   *     forward direction can succeed and then the return direction can fail.
   */
  public Map<Location, BDD> getStartLocationReturnPassFailureBdds() {
    return _startLocationReturnPassFailureBdds;
  }

  /**
   * @return A {@link BDD} representing the set of packets at each {@link Location} for which both
   *     directions (can) succeed.
   */
  public Map<Location, BDD> getStartLocationReturnPassSuccessBdds() {
    return _startLocationReturnPassSuccessBdds;
  }
}


text:
using EOLib.Domain.Character;
using Optional;
using System.Threading.Tasks;
using XNAControls;

namespace EndlessClient.Dialogs.Actions
{
    public interface ICharacterDialogActions
    {
        Task<Option<ICharacterCreateParameters>> ShowCreateCharacterDialog();

        void ShowCharacterReplyDialog(CharacterReply response);

        void ShowCharacterDeleteWarning(string characterName);

        Task<XNADialogResult> ShowConfirmDeleteWarning(string characterName);

        void ShowCharacterDeleteError();
    }
}


text:
package com.adenki.smpp.message;

import org.testng.annotations.Test;

@Test
public class CancelBroadcastSMRespTest extends PacketTests<CancelBroadcastSMResp> {

    protected Class<CancelBroadcastSMResp> getPacketType() {
        return CancelBroadcastSMResp.class;
    }

    @Override
    protected CancelBroadcastSMResp getInitialisedPacket() {
        return new CancelBroadcastSMResp();
    }
}


text:
Type.registerNamespace("Strings");
Strings.OfficeOM = function()
{
};
Strings.OfficeOM.registerClass("Strings.OfficeOM");
Strings.OfficeOM.L_InvalidNamedItemForBindingType = "A megadott kötési típus nem kompatibilis a megadott névvel ellátott elemmel.";
Strings.OfficeOM.L_EventHandlerNotExist = "A megadott eseménykezelő nem található ehhez a kötéshez.";
Strings.OfficeOM.L_UnknownBindingType = "A kötési típus nem támogatott.";
Strings.OfficeOM.L_InvalidNode = "Érvénytelen csomópont";
Strings.OfficeOM.L_NotImplemented = "A(z) {0} függvény nincs implementálva.";
Strings.OfficeOM.L_NoCapability = "Nincs megfelelő engedélye a művelet végrehajtására.";
Strings.OfficeOM.L_SettingsCannotSave = "Nem sikerült menteni a beállításokat.";
Strings.OfficeOM.L_DataWriteReminder = "Adatírási emlékeztető";
Strings.OfficeOM.L_InvalidBinding = "Érvénytelen kötés";
Strings.OfficeOM.L_InvalidSetColumns = "A megadott oszlopok érvénytelenek.";
Strings.OfficeOM.L_BindingCreationError = "Kötés-létrehozási hiba";
Strings.OfficeOM.L_FormatValueOutOfRange = "Az érték kívül esik a megengedett tartományon.";
Strings.OfficeOM.L_SelectionNotSupportCoercionType = "A jelenlegi kijelölés nem kompatibilis a megadott típuskonverzióval.";
Strings.OfficeOM.L_InvalidBindingError = "Hiba: érvénytelen kötés";
Strings.OfficeOM.L_InvalidGetStartRowColumn = "A kezdő sorként vagy kezdő oszlopként megadott érték érvénytelen.";
Strings.OfficeOM.L_InvalidSetRows = "A megadott sorok érvénytelenek.";
Strings.OfficeOM.L_CannotWriteToSelection = "A jelenlegi kijelölés nem írható.";
Strings.OfficeOM.L_MissingParameter = "Hiányzó paraméter";
Strings.OfficeOM.L_IndexOutOfRange = "Az index kívül esik az engedélyezett tartományon.";
Strings.OfficeOM.L_SettingsStaleError = "Hiba: elavult beállítások";
Strings.OfficeOM.L_CannotNavigateTo = "Az objektum olyan helyen található, ahol a navigálás nem támogatott.";
Strings.OfficeOM.L_ReadSettingsError = "Beállításolvasási hiba";
Strings.OfficeOM.L_InvalidGetColumns = "A megadott oszlopok érvénytelenek.";
Strings.OfficeOM.L_CoercionTypeNotSupported = "A megadott típuskonverzió nem támogatott.";
Strings.OfficeOM.L_AppNotExistInitializeNotCalled = "A(z) {0} alkalmazás nem létezik. A Microsoft.Office.WebExtension.initialize(reason) elem hívása nem történik meg.";
Strings.OfficeOM.L_OverwriteWorksheetData = "A beállítási művelet nem sikerült, mert a megadott adatobjektum felülírná vagy eltolná az adatokat.";
Strings.OfficeOM.L_RowIndexOutOfRange = "A sorindex értéke kívül esik a megengedett tartományon. Olyan értéket használjon (0-t vagy nagyobbat), amely kisebb, mint a sorok száma.";
Strings.OfficeOM.L_InvalidReadForBlankRow = "A megadott sor üres.";
Strings.OfficeOM.L_ColIndexOutOfRange = "Az oszlopindex értéke kívül esik a megengedett tartományon. Olyan értéket használjon (0-t vagy nagyobbat), amely kisebb, mint az oszlopok száma.";
Strings.OfficeOM.L_UnsupportedEnumeration = "Nem támogatott számbavétel";
Strings.OfficeOM.L_InvalidParameters = "A(z) {0} függvénynek érvénytelen paraméterei vannak.";
Strings.OfficeOM.L_SetDataParametersConflict = "A megadott paraméterek ütköznek.";
Strings.OfficeOM.L_DataNotMatchCoercionType = "A megadott adatobjektum típusa nem kompatibilis a jelenlegi kijelöléssel.";
Strings.OfficeOM.L_UnsupportedEnumerationMessage = "A számbavétel nem támogatott az aktuális gazdaalkalmazásban.";
Strings.OfficeOM.L_InvalidCoercion = "Érvénytelen típuskonverzió";
Strings.OfficeOM.L_NotSupportedEventType = "A megadott eseménytípus ({0}) nem támogatott.";
Strings.OfficeOM.L_UnsupportedDataObject = "A megadott adatobjektum típusa nem támogatott.";
Strings.OfficeOM.L_GetDataIsTooLarge = "A kért adatkészlet túl nagy.";
Strings.OfficeOM.L_AppNameNotExist = "A(z) {0} alkalmazásneve nem létezik.";
Strings.OfficeOM.L_AddBindingFromPromptDefaultText = "Válasszon a lehetőségek közül.";
Strings.OfficeOM.L_MultipleNamedItemFound = "Több azonos nevű objektum található.";
Strings.OfficeOM.L_InvalidCellsValue = "Legalább egy cellaparaméterhez érvénytelen értéket adott meg. Ellenőrizze az értékeket, és próbálkozzon újra.";
Strings.OfficeOM.L_DataNotMatchBindingType = "A megadott adatobjektum nem kompatibilis a kötéstípussal.";
Strings.OfficeOM.L_InvalidFormatValue = "Legalább egy formátumparaméterhez érvénytelen értéket adott meg. Ellenőrizze az értékeket, és próbálkozzon újra.";
Strings.OfficeOM.L_NotSupportedBindingType = "A megadott kötéstípus ({0}) nem támogatott.";
Strings.OfficeOM.L_InitializeNotReady = "Az Office.js fájl betöltése még nem fejeződött be. Próbálkozzon újra később, vagy ellenőrizze, hogy hozzáadta-e az inicializálási kódot az Office.initialize függvényhez.";
Strings.OfficeOM.L_FormattingReminder = "Formázási emlékeztető";
Strings.OfficeOM.L_ShuttingDown = "A művelet nem sikerült, mert a kiszolgálón lévő adatok nem naprakészek.";
Strings.OfficeOM.L_OperationNotSupported = "A művelet nem támogatott.";
Strings.OfficeOM.L_DocumentReadOnly = "A kért művelet nem engedélyezett a jelenlegi dokumentummódban.";
Strings.OfficeOM.L_NamedItemNotFound = "A névvel ellátott elem nem létezik.";
Strings.OfficeOM.L_InvalidApiCallInContext = "Érvénytelen API-hívás az aktuális környezetben.";
Strings.OfficeOM.L_InvalidGetRows = "A megadott sorok érvénytelenek.";
Strings.OfficeOM.L_CellFormatAmountBeyondLimits = "Megjegyzés: a formázási API hívásával beállított formázási készletek javasolt maximális száma 100.";
Strings.OfficeOM.L_SetDataIsTooLarge = "A megadott adatobjektum túl nagy.";
Strings.OfficeOM.L_DataWriteError = "Adatírási hiba";
Strings.OfficeOM.L_InvalidBindingOperation = "Érvénytelen kötési művelet";
Strings.OfficeOM.L_SpecifiedIdNotExist = "A megadott azonosító nem létezik.";
Strings.OfficeOM.L_FunctionCallFailed = "A(z) {0} függvény hívása sikertelen, hibakód: {1}.";
Strings.OfficeOM.L_DataNotMatchBindingSize = "A megadott adatobjektum nem egyezik a jelenlegi kijelölés méretével.";
Strings.OfficeOM.L_SaveSettingsError = "Beállításmentési hiba";
Strings.OfficeOM.L_InvalidSetStartRowColumn = "A kezdő sorként vagy kezdő oszlopként megadott érték érvénytelen.";
Strings.OfficeOM.L_InvalidFormat = "Hiba: érvénytelen formátum";
Strings.OfficeOM.L_BindingNotExist = "A megadott kötés nem létezik.";
Strings.OfficeOM.L_SettingNameNotExist = "A megadott beállításnév nem létezik.";
Strings.OfficeOM.L_EventHandlerAdditionFailed = "Nem sikerült hozzáadni az eseménykezelőt.";
Strings.OfficeOM.L_InvalidAPICall = "Érvénytelen API-hívás";
Strings.OfficeOM.L_EventRegistrationError = "Eseményregisztrációs hiba";
Strings.OfficeOM.L_ElementMissing = "Nem sikerült a táblázatcella formázása, mert hiányzik néhány paraméterérték. Ellenőrizze a paramétereket, és próbálkozzon újra.";
Strings.OfficeOM.L_NonUniformPartialSetNotSupported = "Koordinátaparaméterek nem használhatók a Táblázat fajtájú típuskonverzióhoz, ha a táblázat egyesített cellákat tartalmaz.";
Strings.OfficeOM.L_NavOutOfBound = "Sikertelen volt a művelet, mert az index kívül esik a tartományon.";
Strings.OfficeOM.L_RedundantCallbackSpecification = "A visszahívás nem adható meg az argumentumlistában és a választható objektumban is.";
Strings.OfficeOM.L_CustomXmlError = "Egyéni XML-hiba.";
Strings.OfficeOM.L_SettingsAreStale = "Nem sikerült menteni a beállításokat, mert nem naprakészek.";
Strings.OfficeOM.L_TooManyOptionalFunction = "több választható függvény van a paraméterlistában";
Strings.OfficeOM.L_MissingRequiredArguments = "hiányzik néhány kötelező argumentum";
Strings.OfficeOM.L_NonUniformPartialGetNotSupported = "Koordinátaparaméterek nem használhatók a Táblázat fajtájú típuskonverzióhoz, ha a táblázat egyesített cellákat tartalmaz.";
Strings.OfficeOM.L_HostError = "Állomáshiba";
Strings.OfficeOM.L_OutOfRange = "Tartományon kívüli érték";
Strings.OfficeOM.L_InvalidSelectionForBindingType = "A jelenlegi kijelöléssel és a megadott kötéstípussal nem hozható létre kötés.";
Strings.OfficeOM.L_TooManyOptionalObjects = "több választható objektum van a paraméterlistában";
Strings.OfficeOM.L_OperationNotSupportedOnMatrixData = "A kijelölt tartalomnak táblázatformátumúnak kell lennie. Formázza az adatokat táblázatként, és próbálkozzon újra.";
Strings.OfficeOM.L_EventHandlerRemovalFailed = "Nem sikerült eltávolítani az eseménykezelőt.";
Strings.OfficeOM.L_BindingToMultipleSelection = "A nem összefüggő kijelölések használata nem támogatott.";
Strings.OfficeOM.L_DataReadError = "Adatolvasási hiba";
Strings.OfficeOM.L_InternalErrorDescription = "Belső hiba történt.";
Strings.OfficeOM.L_InvalidDataFormat = "A megadott adatobjektum formátuma érvénytelen.";
Strings.OfficeOM.L_DataStale = "Az adatok nem naprakészek";
Strings.OfficeOM.L_GetSelectionNotSupported = "A jelenlegi kijelölés nem támogatott.";
Strings.OfficeOM.L_CellDataAmountBeyondLimits = "Megjegyzés: a táblázatcellák javasolt maximális száma 20 000.";
Strings.OfficeOM.L_InvalidTableOptionValue = "Legalább egy tableOptions paraméterhez érvénytelen értéket adott meg. Ellenőrizze az értékeket, és próbálkozzon újra.";
Strings.OfficeOM.L_PermissionDenied = "Engedély megtagadva";
Strings.OfficeOM.L_InvalidDataObject = "Érvénytelen adatobjektum";
Strings.OfficeOM.L_UserNotSignedIn = "No user is signed into Office.";
Strings.OfficeOM.L_SelectionCannotBound = "A jelenlegi kijelöléshez nem lehet kötni.";
Strings.OfficeOM.L_InvalidColumnsForBinding = "A megadott oszlopok érvénytelenek.";
Strings.OfficeOM.L_BadSelectorString = "A választónak átadott karakterlánc helytelenül van formázva vagy nem támogatott.";
Strings.OfficeOM.L_InvalidGetRowColumnCounts = "A sorok vagy oszlopok számának megadott értéke érvénytelen.";
Strings.OfficeOM.L_OsfControlTypeNotSupported = "Az OsfControl típus nem támogatott.";
Strings.OfficeOM.L_InvalidValue = "Érvénytelen érték";
Strings.OfficeOM.L_DataNotMatchSelection = "A megadott adatobjektum nem kompatibilis a jelenlegi kijelölés alakjával vagy méreteivel.";
Strings.OfficeOM.L_InternalError = "Belső hiba";
Strings.OfficeOM.L_NotSupported = "A(z) {0} függvény nem támogatott.";
Strings.OfficeOM.L_CustomXmlNodeNotFound = "A megadott csomópont nem található.";
Strings.OfficeOM.L_CoercionTypeNotMatchBinding = "A megadott típuskonverzió nem kompatibilis ezzel a kötéstípussal.";
Strings.OfficeOM.L_TooManyArguments = "túl sok argumentum";
Strings.OfficeOM.L_OperationNotSupportedOnThisBindingType = "Ezen a kötéstípuson nem támogatott a művelet.";
Strings.OfficeOM.L_InValidOptionalArgument = "érvénytelen választható argumentum";
Strings.OfficeOM.L_FileTypeNotSupported = "A megadott fájltípus nem támogatott.";
Strings.OfficeOM.L_GetDataParametersConflict = "A megadott paraméterek ütköznek.";
Strings.OfficeOM.L_CallbackNotAFunction = "A visszahívás típusa csak függvény lehet, de ehelyett {0} típusú volt."


text:
/**
 * User: phi
 *  .___.
 *  {o,o}
 * /)___)
 * --"-"--
 */
import {Injectable} from "@angular/core";
import {Http, Headers, Response, RequestOptions, XHRBackend, RequestOptionsArgs, Request} from "@angular/http";
import {Observable} from "rxjs/Rx";
import "rxjs/add/operator/map";
import "rxjs/add/operator/catch";
import {GlobalService} from "./global.service";

/**
 * Use custom URL, always use JSON, always send JWT.
 * Configure BASE_URI of rest-API.
 */
@Injectable()
export class HttpApi extends Http {
	private BASE_URI = 'http://localhost:8080';
	//private BASE_URI = 'http://85.214.135.29:8080';

	constructor(backend: XHRBackend, options: RequestOptions, private globalService: GlobalService) {
		super(backend, options);
	}

	/** request wrapper: 1. set auth bearer & content-type json. 2. custom error handler. 3. add base_uri+(...) */
	request(url: string|Request, options?: RequestOptionsArgs): Observable<Response> {
		let currentUser = this.globalService.getCurrentlyLoggedInUser();
		let token = '';
		if (currentUser && currentUser.token) {
			token = currentUser.token;
		}
		if (typeof url === 'string') { // add the token to the options, not in url
			console.log("url is type string?"); // todo
			url = `${this.BASE_URI}${url}`;
			options.headers.set('Authorization', `Bearer ${token}`);
		} else {
			url.url = `${this.BASE_URI}${url.url}`;
			url.headers.set('Authorization', `Bearer ${token}`);
		}
		// toto loading animation ..?
		return super.request(url, options)
			.catch(this.catchError(this));
	}

	get(url: string, options?: RequestOptionsArgs): Observable<Response> {
		options = HttpApi.setContentTypeJson(options);
		return super.get(url, options)
	}

	post(url: string, body: any, options?: RequestOptionsArgs): Observable<Response> {
		options = HttpApi.setContentTypeJson(options);
		return super.post(url, body, options)
	}

	put(url: string, body: any, options?: RequestOptionsArgs): Observable<Response> {
		options = HttpApi.setContentTypeJson(options);
		return super.put(url, body, options)
	}

	delete(url: string, options?: RequestOptionsArgs): Observable<Response> {
		options = HttpApi.setContentTypeJson(options);
		return super.delete(url, options)
	}

	patch(url: string, body: any, options?: RequestOptionsArgs): Observable<Response> {
		options = HttpApi.setContentTypeJson(options);
		return super.patch(url, body, options)
	}

	options(url: string, options?: RequestOptionsArgs): Observable<Response> {
		options = HttpApi.setContentTypeJson(options);
		return super.options(url, options)
	}

	private catchError(self: HttpApi) {
		return (res: Response) => {
			console.log(res);
			if (res.status === 401 || res.status === 403) {
				// not authd
			} else {
				alert("Server says error! :(");
			}
			return Observable.throw(res);
		};
	}

	private static setContentTypeJson(options?: RequestOptionsArgs) {
		if (!options) {
			options = new RequestOptions({headers: new Headers()});
		}
		options.headers.set('Content-Type', 'application/json');
		return options;
	}

}


text:
@protocol SFSynchronizedObject <NSObject>

@required
+ (NSString *)remoteResourceName;
+ (NSString *)remoteIdentifierKey;

@end

@interface SFSynchronizedObject : MTLModel <MTLJSONSerializing, SFSynchronizedObject>
@property (weak, nonatomic, readonly) NSString *remoteID;
@property (nonatomic, strong) NSDate *createdAt;
@property (nonatomic, strong) NSDate *updatedAt;
@property (nonatomic, readonly) BOOL persist;
@property (nonatomic, getter = isFollowed) BOOL followed;
@property (nonatomic, readonly) NSString *resourcePath;

+ (NSString *)remoteResourceName;
+ (NSString *)remoteIdentifierKey;
+ (instancetype)objectWithJSONDictionary:(NSDictionary *)externalRepresentation;
+ (instancetype)existingObjectWithRemoteID:(NSString *)remoteID;
+ (NSArray *)collection;
+ (NSArray *)allObjectsToPersist;

- (void)updateObjectUsingJSONDictionary:(NSDictionary *)externalRepresentation;
- (void)addToCollection;
- (void)removeFromCollection;

@end