text:
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6
// See http://java.sun.com/xml/jaxb
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2012.04.20 at 03:09:04 PM EDT
//

package org.slc.sli.sample.entities;

import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;

/**
 * This entity represents an educational organization that includes staff and students who participate in classes and educational activity groups.
 *
 *
 *
Java class for School complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="School">
 *   <complexContent>
 *     <extension base="{http://ed-fi.org/0100}EducationOrganization">
 *       <sequence>
 *         <element name="GradesOffered" type="{http://ed-fi.org/0100}GradeLevelsType"/>
 *         <element name="SchoolCategories" type="{http://ed-fi.org/0100}SchoolCategoriesType"/>
 *         <element name="SchoolType" type="{http://ed-fi.org/0100}SchoolType" minOccurs="0"/>
 *         <element name="CharterStatus" type="{http://ed-fi.org/0100}CharterStatusType" minOccurs="0"/>
 *         <element name="TitleIPartASchoolDesignation" type="{http://ed-fi.org/0100}TitleIPartASchoolDesignationType" minOccurs="0"/>
 *         <element name="MagnetSpecialProgramEmphasisSchool" type="{http://ed-fi.org/0100}MagnetSpecialProgramEmphasisSchoolType" minOccurs="0"/>
 *         <element name="AdministrativeFundingControl" type="{http://ed-fi.org/0100}AdministrativeFundingControlType" minOccurs="0"/>
 *         <element name="LocalEducationAgencyReference" type="{http://ed-fi.org/0100}EducationalOrgReferenceType" minOccurs="0"/>
 *         <element name="ClassPeriodReference" type="{http://ed-fi.org/0100}ReferenceType" maxOccurs="unbounded" minOccurs="0"/>
 *         <element name="LocationReference" type="{http://ed-fi.org/0100}ReferenceType" maxOccurs="unbounded" minOccurs="0"/>
 *       </sequence>
 *     </extension>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "School", propOrder = {
    "gradesOffered",
    "schoolCategories",
    "schoolType",
    "charterStatus",
    "titleIPartASchoolDesignation",
    "magnetSpecialProgramEmphasisSchool",
    "administrativeFundingControl",
    "localEducationAgencyReference",
    "classPeriodReference",
    "locationReference"
})
public class School
    extends EducationOrganization
{

    @XmlElement(name = "GradesOffered", required = true)
    protected GradeLevelsType gradesOffered;
    @XmlElement(name = "SchoolCategories", required = true)
    protected SchoolCategoriesType schoolCategories;
    @XmlElement(name = "SchoolType")
    protected SchoolType schoolType;
    @XmlElement(name = "CharterStatus")
    protected CharterStatusType charterStatus;
    @XmlElement(name = "TitleIPartASchoolDesignation")
    protected TitleIPartASchoolDesignationType titleIPartASchoolDesignation;
    @XmlElement(name = "MagnetSpecialProgramEmphasisSchool")
    protected MagnetSpecialProgramEmphasisSchoolType magnetSpecialProgramEmphasisSchool;
    @XmlElement(name = "AdministrativeFundingControl")
    protected AdministrativeFundingControlType administrativeFundingControl;
    @XmlElement(name = "LocalEducationAgencyReference")
    protected EducationalOrgReferenceType localEducationAgencyReference;
    @XmlElement(name = "ClassPeriodReference")
    protected List<ReferenceType> classPeriodReference;
    @XmlElement(name = "LocationReference")
    protected List<ReferenceType> locationReference;

    /**
     * Gets the value of the gradesOffered property.
     *
     * @return
     *     possible object is
     *     {@link GradeLevelsType }
     *
     */
    public GradeLevelsType getGradesOffered() {
        return gradesOffered;
    }

    /**
     * Sets the value of the gradesOffered property.
     *
     * @param value
     *     allowed object is
     *     {@link GradeLevelsType }
     *
     */
    public void setGradesOffered(GradeLevelsType value) {
        this.gradesOffered = value;
    }

    /**
     * Gets the value of the schoolCategories property.
     *
     * @return
     *     possible object is
     *     {@link SchoolCategoriesType }
     *
     */
    public SchoolCategoriesType getSchoolCategories() {
        return schoolCategories;
    }

    /**
     * Sets the value of the schoolCategories property.
     *
     * @param value
     *     allowed object is
     *     {@link SchoolCategoriesType }
     *
     */
    public void setSchoolCategories(SchoolCategoriesType value) {
        this.schoolCategories = value;
    }

    /**
     * Gets the value of the schoolType property.
     *
     * @return
     *     possible object is
     *     {@link SchoolType }
     *
     */
    public SchoolType getSchoolType() {
        return schoolType;
    }

    /**
     * Sets the value of the schoolType property.
     *
     * @param value
     *     allowed object is
     *     {@link SchoolType }
     *
     */
    public void setSchoolType(SchoolType value) {
        this.schoolType = value;
    }

    /**
     * Gets the value of the charterStatus property.
     *
     * @return
     *     possible object is
     *     {@link CharterStatusType }
     *
     */
    public CharterStatusType getCharterStatus() {
        return charterStatus;
    }

    /**
     * Sets the value of the charterStatus property.
     *
     * @param value
     *     allowed object is
     *     {@link CharterStatusType }
     *
     */
    public void setCharterStatus(CharterStatusType value) {
        this.charterStatus = value;
    }

    /**
     * Gets the value of the titleIPartASchoolDesignation property.
     *
     * @return
     *     possible object is
     *     {@link TitleIPartASchoolDesignationType }
     *
     */
    public TitleIPartASchoolDesignationType getTitleIPartASchoolDesignation() {
        return titleIPartASchoolDesignation;
    }

    /**
     * Sets the value of the titleIPartASchoolDesignation property.
     *
     * @param value
     *     allowed object is
     *     {@link TitleIPartASchoolDesignationType }
     *
     */
    public void setTitleIPartASchoolDesignation(TitleIPartASchoolDesignationType value) {
        this.titleIPartASchoolDesignation = value;
    }

    /**
     * Gets the value of the magnetSpecialProgramEmphasisSchool property.
     *
     * @return
     *     possible object is
     *     {@link MagnetSpecialProgramEmphasisSchoolType }
     *
     */
    public MagnetSpecialProgramEmphasisSchoolType getMagnetSpecialProgramEmphasisSchool() {
        return magnetSpecialProgramEmphasisSchool;
    }

    /**
     * Sets the value of the magnetSpecialProgramEmphasisSchool property.
     *
     * @param value
     *     allowed object is
     *     {@link MagnetSpecialProgramEmphasisSchoolType }
     *
     */
    public void setMagnetSpecialProgramEmphasisSchool(MagnetSpecialProgramEmphasisSchoolType value) {
        this.magnetSpecialProgramEmphasisSchool = value;
    }

    /**
     * Gets the value of the administrativeFundingControl property.
     *
     * @return
     *     possible object is
     *     {@link AdministrativeFundingControlType }
     *
     */
    public AdministrativeFundingControlType getAdministrativeFundingControl() {
        return administrativeFundingControl;
    }

    /**
     * Sets the value of the administrativeFundingControl property.
     *
     * @param value
     *     allowed object is
     *     {@link AdministrativeFundingControlType }
     *
     */
    public void setAdministrativeFundingControl(AdministrativeFundingControlType value) {
        this.administrativeFundingControl = value;
    }

    /**
     * Gets the value of the localEducationAgencyReference property.
     *
     * @return
     *     possible object is
     *     {@link EducationalOrgReferenceType }
     *
     */
    public EducationalOrgReferenceType getLocalEducationAgencyReference() {
        return localEducationAgencyReference;
    }

    /**
     * Sets the value of the localEducationAgencyReference property.
     *
     * @param value
     *     allowed object is
     *     {@link EducationalOrgReferenceType }
     *
     */
    public void setLocalEducationAgencyReference(EducationalOrgReferenceType value) {
        this.localEducationAgencyReference = value;
    }

    /**
     * Gets the value of the classPeriodReference property.
     *
     *

     * This accessor method returns a reference to the live list,
     * not a snapshot. Therefore any modification you make to the
     * returned list will be present inside the JAXB object.
     * This is why there is not a set method for the classPeriodReference property.
     *
     *

     * For example, to add a new item, do as follows:
     *

     *    getClassPeriodReference().add(newItem);
     *

     *
     *
     *

     * Objects of the following type(s) are allowed in the list
     * {@link ReferenceType }
     *
     *
     */
    public List<ReferenceType> getClassPeriodReference() {
        if (classPeriodReference == null) {
            classPeriodReference = new ArrayList<ReferenceType>();
        }
        return this.classPeriodReference;
    }

    /**
     * Gets the value of the locationReference property.
     *
     *

     * This accessor method returns a reference to the live list,
     * not a snapshot. Therefore any modification you make to the
     * returned list will be present inside the JAXB object.
     * This is why there is not a set method for the locationReference property.
     *
     *

     * For example, to add a new item, do as follows:
     *

     *    getLocationReference().add(newItem);
     *

     *
     *
     *

     * Objects of the following type(s) are allowed in the list
     * {@link ReferenceType }
     *
     *
     */
    public List<ReferenceType> getLocationReference() {
        if (locationReference == null) {
            locationReference = new ArrayList<ReferenceType>();
        }
        return this.locationReference;
    }

}


text:
<?php

namespace app\controllers;

use Yii;
use yii\web\Controller;
use yii\filters\VerbFilter;
use app\models\RecipeForm;
use yii\web\UploadedFile;
use yii\helpers\Json;
use yii\widgets\ActiveForm;
use yii\web\Response;

class SiteController extends Controller
{
    public function actions()
    {
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction',
            ],
        ];
    }

    public function actionIndex()
    {
        $model = new RecipeForm();
        $recipe = false;
	if (Yii::$app->request->isAjax)  {
	    $model->load(Yii::$app->request->post());
            sleep($model->delay);
	    Yii::$app->response->format = Response::FORMAT_JSON;
	    return ActiveForm::validate($model);
	} elseif (Yii::$app->request->post()) {
            $model->load(Yii::$app->request->post());
            die('Success');
            if ($model->validate()) {
                die('Success');
            }
        }

        return $this->render('index', [
            'model' => $model,
            'recipe' => $recipe,
        ]);
    }

    public function actionAbout()
    {
        return $this->render('about');
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.queen.rxjavaretrofitdemo">

    <uses-permission android:name="android.permission.INTERNET" />
    <!-- 网络状态权限 -->
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".activity.MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".activity.FullscreenActivity"
            android:configChanges="orientation|keyboardHidden|screenSize"
            android:label="@string/title_activity_fullscreen"
            android:theme="@style/FullscreenTheme"></activity>
    </application>

</manifest>


text:
module Spree
  # Service class to change fulfilment of inventory units of a particular variant
  # to another shipment. The other shipment would typically have a different
  # shipping method, stock location or delivery date, such that we actually change
  # the planned fulfilment for the items in question.
  #
  # Can be used to merge shipments by moving all items to another shipment, because
  # this class will delete any empty original shipment.
  #
  # @attr [Spree::Shipment] current_shipment The shipment we transfer units from
  # @attr [Spree::Shipment] desired_shipment The shipment we want to move units onto
  # @attr [Spree::StockLocation] current_stock_location The stock location of the current shipment
  # @attr [Spree::StockLocation] desired_stock_location The stock location of the desired shipment
  # @attr [Spree::Variant] variant We only move units that represent this variant
  # @attr [Integer] quantity How many units we want to move
  #
  class FulfilmentChanger
    include ActiveModel::Validations

    attr_accessor :current_shipment, :desired_shipment
    attr_reader :variant, :quantity, :current_stock_location, :desired_stock_location

    def initialize(current_shipment:, desired_shipment:, variant:, quantity:)
      @current_shipment = current_shipment
      @desired_shipment = desired_shipment
      @current_stock_location = current_shipment.stock_location
      @desired_stock_location = desired_shipment.stock_location
      @variant = variant
      @quantity = quantity
    end

    validates :quantity, numericality: { greater_than: 0 }
    validate :current_shipment_not_already_shipped
    validate :desired_shipment_different_from_current
    validates :desired_stock_location, presence: true
    validate :enough_stock_at_desired_location, if: :handle_stock_counts?

    # Performs the change of fulfilment
    # @return [true, false] Whether the requested fulfilment change was successful
    def run!
      # Validations here are intended to catch all necessary prerequisites.
      # We return early so all checks have happened already.
      return false if invalid?
      desired_shipment.save! if desired_shipment.new_record?

      # Retrieve how many on hand items we can take from desired stock location
      available_quantity = [desired_shipment.stock_location.count_on_hand(variant), default_on_hand_quantity].max

      new_on_hand_quantity = [available_quantity, quantity].min
      unstock_quantity = desired_shipment.stock_location.backorderable?(variant) ? quantity : new_on_hand_quantity

      ActiveRecord::Base.transaction do
        if handle_stock_counts?
          # We only run this query if we need it.
          current_on_hand_quantity = [current_shipment.inventory_units.pre_shipment.size, quantity].min

          # Restock things we will not fulfil from the current shipment anymore
          current_stock_location.restock(variant, current_on_hand_quantity, current_shipment)
          # Unstock what we will fulfil with the new shipment
          desired_stock_location.unstock(variant, unstock_quantity, desired_shipment)
        end

        # These two statements are the heart of this class. We change the number
        # of inventory units requested from one shipment to the other.
        # We order by state, because `'backordered' < 'on_hand'`.
        current_shipment.
          inventory_units.
          where(variant: variant).
          order(state: :asc).
          limit(new_on_hand_quantity).
          update_all(shipment_id: desired_shipment.id, state: :on_hand)

        current_shipment.
          inventory_units.
          where(variant: variant).
          order(state: :asc).
          limit(quantity - new_on_hand_quantity).
          update_all(shipment_id: desired_shipment.id, state: :backordered)
      end

      # We modified the inventory units at the database level for speed reasons.
      # The downside of that is that we need to reload the associations.
      current_shipment.inventory_units.reload
      desired_shipment.inventory_units.reload

      # If the current shipment now has no inventory units left, we won't need it any longer.
      if current_shipment.inventory_units.length.zero?
        current_shipment.destroy!
      else
        # The current shipment has changed, so we need to make sure that shipping rates
        # have the correct amount.
        current_shipment.refresh_rates
      end

      # The desired shipment has also change, so we need to make sure shipping rates
      # are up-to-date, too.
      desired_shipment.refresh_rates

      # In order to reflect the changes in the order totals
      desired_shipment.order.reload
      desired_shipment.order.recalculate

      true
    end

    private

    # We don't need to handle stock counts for incomplete orders. Also, if
    # the new shipment and the desired shipment will ship from the same stock location,
    # unstocking and restocking will not be necessary.
    def handle_stock_counts?
      current_shipment.order.completed? && current_stock_location != desired_stock_location
    end

    def default_on_hand_quantity
      if current_stock_location != desired_stock_location
        0
      else
        current_shipment.inventory_units.where(variant: variant).on_hand.count
      end
    end

    def current_shipment_not_already_shipped
      if current_shipment.shipped?
        errors.add(:current_shipment, :has_already_been_shipped)
      end
    end

    def enough_stock_at_desired_location
      unless Spree::Stock::Quantifier.new(variant, desired_stock_location).can_supply?(quantity)
        errors.add(:desired_shipment, :not_enough_stock_at_desired_location)
      end
    end

    def desired_shipment_different_from_current
      if desired_shipment.id == current_shipment.id
        errors.add(:desired_shipment, :can_not_transfer_within_same_shipment)
      end
    end
  end
end


text:
"""
  This is a wrapper for interaction with the database. Each of these methods
  can be overridden to connect to a different db.
"""
from pymongo import MongoClient
import ConfigLayer
import pymongo

connection = None
isUnitTestMode = False

def open_conn():
  """
    Checks if there is already an open db connection. If not then it opens
    one. Either way, it returns the open db connection.
  """
  global connection
  if connection is None:
    connection = MongoClient(ConfigLayer.get_url(), int(ConfigLayer.get_port()))
  return connection

def get_table(tableName):
  """
    gets the dataset associated with the given name. Also checks if the
    connection to the database is open or not. If it is not, then open it.

    args:
      tableName:
        name of the dataset that is wanted by the caller

    returns:
      a dataset upon which futher inquries can be done.
  """
  global isUnitTestMode
  open_conn()
  if isUnitTestMode:
    db = connection['test']
  else:
    db = connection[ConfigLayer.get_db_name()]
  return db[tableName]


text:
import Ember from "ember";
import Calendar from "get-calendar/models/calendar";
import moment from "moment";

export default Ember.Route.extend({

  model() {
    return Calendar.create({
      year: moment().add(3, "months").year(),
      locale: navigator.userLanguage || navigator.language ||
        navigator.browserLanguage || navigator.systemLanguage
    });
  }

});


text:
using System.Diagnostics.CodeAnalysis;
using static Microsoft.AspNetCore.Internal.LinkerFlags;

namespace Microsoft.AspNetCore.Components;

/// <summary>
/// Indicates that the associated component type uses a specified layout.
/// </summary>
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = true)]
public sealed class LayoutAttribute : Attribute
{
    /// <summary>
    /// Constructs an instance of <see cref="LayoutAttribute"/>.
    /// </summary>
    /// <param name="layoutType">The type of the layout.</param>
    public LayoutAttribute([DynamicallyAccessedMembers(Component)] Type layoutType)
    {
        LayoutType = layoutType ?? throw new ArgumentNullException(nameof(layoutType));

        if (!typeof(IComponent).IsAssignableFrom(layoutType))
        {
            throw new ArgumentException($"Invalid layout type: {layoutType.FullName} " +
                $"does not implement {typeof(IComponent).FullName}.");
        }

        // Note that we can't validate its acceptance of a 'Body' parameter at this stage,
        // because the contract doesn't force them to be known statically. However it will
        // be a runtime error if the referenced component type rejects the 'Body' parameter
        // when it gets used.
    }

    /// <summary>
    /// The type of the layout. The type must implement <see cref="IComponent"/>
    /// and must accept a parameter with the name 'Body'.
    /// </summary>
    public Type LayoutType { get; private set; }
}


text:
package org.waveprotocol.wave.model.document;

import org.waveprotocol.wave.model.util.ReadableStringMap;

/**
 * An object that represents an interval of an AnnotationSet.
 *
 * An interval is a maximal range of an AnnotationSet in which all items have
 * the same annotations.  Intervals are always nonempty.
 *
 * @author ohler@google.com (Christian Ohler)
 *
 * @param <V> the type of values in the AnnotationSet
 */
public interface AnnotationInterval<V> {
  /** The index of the first item of this interval. */
  int start();

  /** The index beyond the last item of this interval. */
  int end();

  /** The length of this interval. */
  int length();

  /**
   * The annotations in this interval.
   */
  ReadableStringMap<V> annotations();

  /**
   * The annotations in this interval whose values differ from the previous
   * interval.
   *
   * If this interval is the first interval returned during an iteration,
   * the return value of this method is defined as follows: If the iteration
   * started at index 0, it will contain the same entries as the return value of
   * annotations().  If the iteration started at an index greater than 0, it
   * will contain the differences from the annotations at the index prior to
   * the start of the iteration.
   *
   * This may throw an UnsupportedOperationException if this AnnotationInterval
   * was not returned by a left-to-right iteration.
   */
  ReadableStringMap<V> diffFromLeft();
}


text:
namespace Microsoft.Graph
{
    using System;

    using Newtonsoft.Json;

    /// <summary>
    /// The interface IGroupExtensionsCollectionPage.
    /// </summary>
    [JsonConverter(typeof(InterfaceConverter<GroupExtensionsCollectionPage>))]
    public interface IGroupExtensionsCollectionPage : ICollectionPage<Extension>
    {
        /// <summary>
        /// Gets the next page <see cref="IGroupExtensionsCollectionRequest"/> instance.
        /// </summary>
        IGroupExtensionsCollectionRequest NextPageRequest { get; }

        /// <summary>
        /// Initializes the NextPageRequest property.
        /// </summary>
        void InitializeNextPageRequest(IBaseClient client, string nextPageLinkString);
    }
}


text:
package aip0165

import (
	"testing"

	"github.com/googleapis/api-linter/rules/internal/testutils"
)

func TestRequestParentReference(t *testing.T) {
	for _, test := range []struct {
		name        string
		MessageName string
		FieldName   string
		FieldOpts   string
		problems    testutils.Problems
	}{
		{"Valid", "PurgeBooks", "parent", ` [(google.api.resource_reference) = { type: "foo" }]`, nil},
		{"Missing", "PurgeBooks", "parent", "", testutils.Problems{{Message: "google.api.resource_reference"}}},
		{"IrrelevantMessage", "DeleteBooks", "parent", "", nil},
		{"IrrelevantField", "PurgeBooks", "names", "", nil},
	} {
		t.Run(test.name, func(t *testing.T) {
			f := testutils.ParseProto3Tmpl(t, `
				import "google/api/resource.proto";
				message {{.MessageName}}Request {
					repeated string {{.FieldName}} = 1{{.FieldOpts}};
				}
			`, test)
			field := f.GetMessageTypes()[0].GetFields()[0]
			if diff := test.problems.SetDescriptor(field).Diff(requestParentReference.Lint(f)); diff != "" {
				t.Errorf(diff)
			}
		})
	}
}


text:
package android.opengl.cts;

import java.util.concurrent.CountDownLatch;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;

import android.opengl.GLES20;

public class RendererTwelveShaderTest extends RendererBase {
    private String fragmentShaderCode = Shaders.successfulcompile_frag;

    public RendererTwelveShaderTest(CountDownLatch latch) {
        super(latch);
    }

    @Override
    public void onSurfaceCreated(GL10 gl, EGLConfig config) {
        GLES20.glClearColor(0.5f, 0.5f, 0.5f, 1.0f);
        int fragmentShader = loadShader(GLES20.GL_FRAGMENT_SHADER, fragmentShaderCode);
        //invalid value
        mProgram =  0;

        GLES20.glAttachShader(mProgram, fragmentShader);
        GLES20.glLinkProgram(mProgram);

        mError = GLES20.glGetError();
        mLatch.countDown();
    }
}


text:
#pragma once
#include <aws/workmail/WorkMail_EXPORTS.h>
#include <aws/workmail/WorkMailRequest.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>

namespace Aws
{
namespace WorkMail
{
namespace Model
{

  /**
   */
  class AWS_WORKMAIL_API GetMobileDeviceAccessEffectRequest : public WorkMailRequest
  {
  public:
    GetMobileDeviceAccessEffectRequest();

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

    Aws::String SerializePayload() const override;

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

    /**
     *
The Amazon WorkMail organization to simulate the access effect for.

     */
    inline const Aws::String& GetOrganizationId() const{ return m_organizationId; }

    /**
     *
The Amazon WorkMail organization to simulate the access effect for.

     */
    inline bool OrganizationIdHasBeenSet() const { return m_organizationIdHasBeenSet; }

    /**
     *
The Amazon WorkMail organization to simulate the access effect for.

     */
    inline void SetOrganizationId(const Aws::String& value) { m_organizationIdHasBeenSet = true; m_organizationId = value; }

    /**
     *
The Amazon WorkMail organization to simulate the access effect for.

     */
    inline void SetOrganizationId(Aws::String&& value) { m_organizationIdHasBeenSet = true; m_organizationId = std::move(value); }

    /**
     *
The Amazon WorkMail organization to simulate the access effect for.

     */
    inline void SetOrganizationId(const char* value) { m_organizationIdHasBeenSet = true; m_organizationId.assign(value); }

    /**
     *
The Amazon WorkMail organization to simulate the access effect for.

     */
    inline GetMobileDeviceAccessEffectRequest& WithOrganizationId(const Aws::String& value) { SetOrganizationId(value); return *this;}

    /**
     *
The Amazon WorkMail organization to simulate the access effect for.

     */
    inline GetMobileDeviceAccessEffectRequest& WithOrganizationId(Aws::String&& value) { SetOrganizationId(std::move(value)); return *this;}

    /**
     *
The Amazon WorkMail organization to simulate the access effect for.

     */
    inline GetMobileDeviceAccessEffectRequest& WithOrganizationId(const char* value) { SetOrganizationId(value); return *this;}

    /**
     *
Device type the simulated user will report.

     */
    inline const Aws::String& GetDeviceType() const{ return m_deviceType; }

    /**
     *
Device type the simulated user will report.

     */
    inline bool DeviceTypeHasBeenSet() const { return m_deviceTypeHasBeenSet; }

    /**
     *
Device type the simulated user will report.

     */
    inline void SetDeviceType(const Aws::String& value) { m_deviceTypeHasBeenSet = true; m_deviceType = value; }

    /**
     *
Device type the simulated user will report.

     */
    inline void SetDeviceType(Aws::String&& value) { m_deviceTypeHasBeenSet = true; m_deviceType = std::move(value); }

    /**
     *
Device type the simulated user will report.

     */
    inline void SetDeviceType(const char* value) { m_deviceTypeHasBeenSet = true; m_deviceType.assign(value); }

    /**
     *
Device type the simulated user will report.

     */
    inline GetMobileDeviceAccessEffectRequest& WithDeviceType(const Aws::String& value) { SetDeviceType(value); return *this;}

    /**
     *
Device type the simulated user will report.

     */
    inline GetMobileDeviceAccessEffectRequest& WithDeviceType(Aws::String&& value) { SetDeviceType(std::move(value)); return *this;}

    /**
     *
Device type the simulated user will report.

     */
    inline GetMobileDeviceAccessEffectRequest& WithDeviceType(const char* value) { SetDeviceType(value); return *this;}

    /**
     *
Device model the simulated user will report.

     */
    inline const Aws::String& GetDeviceModel() const{ return m_deviceModel; }

    /**
     *
Device model the simulated user will report.

     */
    inline bool DeviceModelHasBeenSet() const { return m_deviceModelHasBeenSet; }

    /**
     *
Device model the simulated user will report.

     */
    inline void SetDeviceModel(const Aws::String& value) { m_deviceModelHasBeenSet = true; m_deviceModel = value; }

    /**
     *
Device model the simulated user will report.

     */
    inline void SetDeviceModel(Aws::String&& value) { m_deviceModelHasBeenSet = true; m_deviceModel = std::move(value); }

    /**
     *
Device model the simulated user will report.

     */
    inline void SetDeviceModel(const char* value) { m_deviceModelHasBeenSet = true; m_deviceModel.assign(value); }

    /**
     *
Device model the simulated user will report.

     */
    inline GetMobileDeviceAccessEffectRequest& WithDeviceModel(const Aws::String& value) { SetDeviceModel(value); return *this;}

    /**
     *
Device model the simulated user will report.

     */
    inline GetMobileDeviceAccessEffectRequest& WithDeviceModel(Aws::String&& value) { SetDeviceModel(std::move(value)); return *this;}

    /**
     *
Device model the simulated user will report.

     */
    inline GetMobileDeviceAccessEffectRequest& WithDeviceModel(const char* value) { SetDeviceModel(value); return *this;}

    /**
     *
Device operating system the simulated user will report.

     */
    inline const Aws::String& GetDeviceOperatingSystem() const{ return m_deviceOperatingSystem; }

    /**
     *
Device operating system the simulated user will report.

     */
    inline bool DeviceOperatingSystemHasBeenSet() const { return m_deviceOperatingSystemHasBeenSet; }

    /**
     *
Device operating system the simulated user will report.

     */
    inline void SetDeviceOperatingSystem(const Aws::String& value) { m_deviceOperatingSystemHasBeenSet = true; m_deviceOperatingSystem = value; }

    /**
     *
Device operating system the simulated user will report.

     */
    inline void SetDeviceOperatingSystem(Aws::String&& value) { m_deviceOperatingSystemHasBeenSet = true; m_deviceOperatingSystem = std::move(value); }

    /**
     *
Device operating system the simulated user will report.

     */
    inline void SetDeviceOperatingSystem(const char* value) { m_deviceOperatingSystemHasBeenSet = true; m_deviceOperatingSystem.assign(value); }

    /**
     *
Device operating system the simulated user will report.

     */
    inline GetMobileDeviceAccessEffectRequest& WithDeviceOperatingSystem(const Aws::String& value) { SetDeviceOperatingSystem(value); return *this;}

    /**
     *
Device operating system the simulated user will report.

     */
    inline GetMobileDeviceAccessEffectRequest& WithDeviceOperatingSystem(Aws::String&& value) { SetDeviceOperatingSystem(std::move(value)); return *this;}

    /**
     *
Device operating system the simulated user will report.

     */
    inline GetMobileDeviceAccessEffectRequest& WithDeviceOperatingSystem(const char* value) { SetDeviceOperatingSystem(value); return *this;}

    /**
     *
Device user agent the simulated user will report.

     */
    inline const Aws::String& GetDeviceUserAgent() const{ return m_deviceUserAgent; }

    /**
     *
Device user agent the simulated user will report.

     */
    inline bool DeviceUserAgentHasBeenSet() const { return m_deviceUserAgentHasBeenSet; }

    /**
     *
Device user agent the simulated user will report.

     */
    inline void SetDeviceUserAgent(const Aws::String& value) { m_deviceUserAgentHasBeenSet = true; m_deviceUserAgent = value; }

    /**
     *
Device user agent the simulated user will report.

     */
    inline void SetDeviceUserAgent(Aws::String&& value) { m_deviceUserAgentHasBeenSet = true; m_deviceUserAgent = std::move(value); }

    /**
     *
Device user agent the simulated user will report.

     */
    inline void SetDeviceUserAgent(const char* value) { m_deviceUserAgentHasBeenSet = true; m_deviceUserAgent.assign(value); }

    /**
     *
Device user agent the simulated user will report.

     */
    inline GetMobileDeviceAccessEffectRequest& WithDeviceUserAgent(const Aws::String& value) { SetDeviceUserAgent(value); return *this;}

    /**
     *
Device user agent the simulated user will report.

     */
    inline GetMobileDeviceAccessEffectRequest& WithDeviceUserAgent(Aws::String&& value) { SetDeviceUserAgent(std::move(value)); return *this;}

    /**
     *
Device user agent the simulated user will report.

     */
    inline GetMobileDeviceAccessEffectRequest& WithDeviceUserAgent(const char* value) { SetDeviceUserAgent(value); return *this;}

  private:

    Aws::String m_organizationId;
    bool m_organizationIdHasBeenSet;

    Aws::String m_deviceType;
    bool m_deviceTypeHasBeenSet;

    Aws::String m_deviceModel;
    bool m_deviceModelHasBeenSet;

    Aws::String m_deviceOperatingSystem;
    bool m_deviceOperatingSystemHasBeenSet;

    Aws::String m_deviceUserAgent;
    bool m_deviceUserAgentHasBeenSet;
  };

} // namespace Model
} // namespace WorkMail
} // namespace Aws


text:
package com.devesion.commons.obd.adapter.command;

import com.devesion.commons.obd.adapter.command.at.AtCommand;
import com.devesion.commons.obd.adapter.command.diagnostic.DiagnosticCommand;

/**
 * OBD Command Visitor Interface.
 */
public interface ObdCommandVisitor {

	void visit(AtCommand command);

	void visit(DiagnosticCommand command);
}


text:
<?php namespace Phaza\LaravelPostgis\Schema\Grammars;

use Illuminate\Support\Fluent;
use Phaza\LaravelPostgis\Schema\Blueprint;
use Bosnadev\Database\Schema\Grammars\PostgresGrammar;

class PostgisGrammar extends PostgresGrammar
{
    /**
     * Adds a statement to add a point geometry column
     *
     * @param \Illuminate\Support\Fluent $column
     * @return string
     */
    public function typePoint(Fluent $column)
    {
        return 'GEOGRAPHY(POINT, 4326)';
    }

    /**
     * Adds a statement to add a point geometry column
     *
     * @param \Illuminate\Support\Fluent $column
     * @return string
     */
    public function typeMultipoint(Fluent $column)
    {
        return 'GEOGRAPHY(MULTIPOINT, 4326)';
    }

    /**
     * Adds a statement to add a polygon geometry column
     *
     * @param \Illuminate\Support\Fluent $column
     * @return string
     */
    public function typePolygon(Fluent $column)
    {
        return 'GEOGRAPHY(POLYGON, 4326)';
    }

    /**
     * Adds a statement to add a multipolygon geometry column
     *
     * @param \Illuminate\Support\Fluent $column
     * @return string
     */
    public function typeMultipolygon(Fluent $column)
    {
        return 'GEOGRAPHY(MULTIPOLYGON, 4326)';
    }

    /**
     * Adds a statement to add a linestring geometry column
     *
     * @param \Illuminate\Support\Fluent $column
     * @return string
     */
    public function typeLinestring(Fluent $column)
    {
        return 'GEOGRAPHY(LINESTRING, 4326)';
    }

    /**
     * Adds a statement to add a multilinestring geometry column
     *
     * @param \Illuminate\Support\Fluent $column
     * @return string
     */
    public function typeMultilinestring(Fluent $column)
    {
        return 'GEOGRAPHY(MULTILINESTRING, 4326)';
    }

    /**
     * Adds a statement to add a linestring geometry column
     *
     * @param \Illuminate\Support\Fluent $column
     * @return string
     */
    public function typeGeography(Fluent $column)
    {
        return 'GEOGRAPHY';
    }

    /**
     * Adds a statement to add a geometrycollection geometry column
     *
     * @param Blueprint $blueprint
     * @param Fluent $command
     * @return string
     */
    public function compileGeometrycollection(Blueprint $blueprint, Fluent $command)
    {
        $command->type = 'GEOMETRYCOLLECTION';

        return $this->compileGeometry($blueprint, $command);
    }

    /**
     * Adds a statement to create the postgis extension
     *
     * @param Blueprint $blueprint
     * @param Fluent $command
     * @return string
     */
    public function compileEnablePostgis(Blueprint $blueprint, Fluent $command)
    {
        return 'CREATE EXTENSION postgis';
    }

    /**
     * Adds a statement to drop the postgis extension
     *
     * @param Blueprint $blueprint
     * @param Fluent $command
     * @return string
     */
    public function compileDisablePostgis(Blueprint $blueprint, Fluent $command)
    {
        return 'DROP EXTENSION postgis';
    }

    /**
     * Adds a statement to add a geometry column
     *
     * @param Blueprint $blueprint
     * @param Fluent $command
     * @return string
     */
    protected function compileGeometry(Blueprint $blueprint, Fluent $command)
    {

        $dimensions = $command->dimensions ?: 2;
        $typmod = $command->typmod ? 'true' : 'false';
        $srid = $command->srid ?: 4326;

        return sprintf(
            "SELECT AddGeometryColumn('%s', '%s', %d, '%s', %d, %s)",
            $blueprint->getTable(),
            $command->column,
            $srid,
            strtoupper($command->type),
            $dimensions,
            $typmod
        );
    }
}


text:
/**Interface Answer Component for template*/
export interface AnswerComponent {
  data: any;
}


text:
<!DOCTYPE html>
<script src="../../../../../resources/testharness.js"></script>
<script src="../../../../../resources/testharnessreport.js"></script>
<script src="../../../../../fast/spatial-navigation/resources/snav-testharness.js"></script>

<body>
<button id="button" autofocus>button</button>

<script>
  let button = document.getElementById("button");

  promise_test(async () => {
    await snav.rAF();
    await snav.rAF();
    assert_equals(document.activeElement,
                  button,
                  "'button' should start focused.");
    assert_equals(window.internals.interestedElement,
                  button,
                  "'button' should start interested.");

    document.activeElement.blur()
    await snav.rAF();

    assert_equals(document.activeElement,
                  document.body,
                  "'body' should be focused.");
    assert_equals(window.internals.interestedElement,
                  button,
                  "'button' should still be interested.");

  }, 'Spat Nav does not pass interest to the body.');
</script>
</body>


text:
package RemoveDuplicatesfromSortedArray;

/**
 * Given a sorted array, remove the duplicates in place such that each element appear only once and
 * return the new length.
 *
 * Do not allocate extra space for another array, you must do this in place with constant memory.
 *
 * <pre>
 * For example,
 * Given input array nums = [1,1,2],
 * </pre>
 * Your function should return length = 2, with the first two elements of nums being 1 and 2
 * respectively. It doesn't matter what you leave beyond the new length.
 *
 * Subscribe to see which companies asked this question.
 */
class Solution {

    public int removeDuplicates(int[] nums) {
        int pos = 0;
        for (int i = 1; i < nums.length; i++) {
            if (nums[i] != nums[pos]) {
                nums[++pos] = nums[i];
            }
        }
        return pos + 1;
    }
}


text:
import { isString, omit, clone, isObject, isFunction } from 'lodash';

import SchemaType from './abstract';

const _types = {};

/**
 * SchemaType Manager
 */
class SchemaTypeManager
{
	/**
	 * Available Types
	 *
	 * @type {object}
	 */
	static get Types () {
		return clone(_types);
	}

	/**
	 * Register a Type
	 *
	 * @param {SchemaType} schemaType Type to register
	 *
	 * @return {SchemaTypeManager} The SchemaType Manager
	 */
	static register (schemaType) {
		if ((schemaType !== SchemaType) && !(schemaType.prototype instanceof SchemaType))
			throw new Error('SchemaTypeManager:register() Argument#1 must be a SchemaType subclass.');

		_types[schemaType.typeName] = schemaType;

		return this;
	}

	/**
	 * Get a Type by its name
	 *
	 * @param {string} typeName The Type name
	 *
	 * @return {SchemaType|undefined} The Type if exists
	 */
	static get (typeName) {
		return _types[typeName];
	}

	/**
	 * instanciate a type with its descriptor
	 *
	 * @param {object} [descriptor] The Type descriptor
	 *
	 * @return {SchemaType|undefined} The Type if exists
	 */
	static instanciate (descriptor) {
		if (isObject(descriptor)) {
			if (descriptor instanceof SchemaType) {
				return descriptor;
			}

			if (descriptor.prototype instanceof SchemaType) {
				return this.instanciate({
					_type: descriptor
				});
			}

			if (descriptor._type) {
				if (isString(descriptor._type)) {
					descriptor._type = _types[descriptor._type];
				}

				if (descriptor._type instanceof SchemaType) {
					return new Proxy(descriptor._type, {
						get: (target, key) => {

							switch (key) {
								case 'validator':
									return target.buildValidator(omit(descriptor, '_type'));
							}

							return target[key];
						}
					});
				}

				if (descriptor._type.prototype instanceof SchemaType) {
					return new descriptor._type(omit(descriptor, '_type'));
				}

				if (isFunction(descriptor._type)) {
					return this.instanciate({
						_type: 	     'object',
						_instanceOf: descriptor._type
					});
				}
			} else if (!('_type' in descriptor)) {
				return this.instanciate({
					_type: descriptor
				});
			}

			return;
		}

		return this.instanciate({
			_type: descriptor
		});
	}
}

export default SchemaTypeManager;


text:
@interface RXCSDK : NSObject<RXComponentRouteRegisterDelegate>
@end


text:
define(['require', 'angular', './base-url-module'], function (require, angular, app) {
	"use strict";
	app.config(function ($httpProvider) {
		$httpProvider.interceptors.push(function ($q, $rootElement) {
			var app_template_root = require.toUrl('../');
			return {
				'request': function (config) {
					config.url = config.url.replace(/(\:app_template_root)[\/?#:]|(\:app_template_root)$/, app_template_root);
					return config || $q.when(config);

				}

			};
		});
	});
});


text:
import { moduleFor, test } from 'ember-qunit';

moduleFor('route:wildcard', 'Unit | Route | wildcard', {
  // Specify the other units that are required for this test.
  // needs: ['controller:foo']
});

test('it exists', function(assert) {
  var route = this.subject();
  assert.ok(route);
});


text:
<?php

namespace Google\AdsApi\AdManager\v202208;

/**
 * This file was generated from WSDL. DO NOT EDIT.
 */
class DeleteLineItemCreativeAssociations extends \Google\AdsApi\AdManager\v202208\LineItemCreativeAssociationAction
{

    public function __construct()
    {

    }

}


text:
promise_test(async t => {
  const estimate = await navigator.storage.estimate()
  assert_equals(typeof estimate.usageDetails, 'object');
}, 'estimate() resolves to dictionary with usageDetails member');

promise_test(async t => {
  // We use 100KB here because db compaction usually happens every few MB
  // 100KB is large enough to avoid a false positive (small amounts of metadata
  // getting written for some random reason), and small enough to avoid
  // compaction with a reasonably high probability.
  const writeSize = 1024 * 100;
  const objectStoreName = 'store';
  const dbname = self.location.pathname;

  await indexedDB.deleteDatabase(dbname);
  let usageAfterWrite, usageBeforeWrite;
  // TODO(crbug.com/906867): Refactor this test to better deal with db/log
  //                         compaction flakiness
  // The for loop here is to help make this test less flaky.  The reason it is
  // flaky is that database and/or log compaction could happen in the middle of
  // this loop.  The problem is that this test runs in a large batch of tests,
  // and previous tests might have created a lot of garbage which could trigger
  // compaction.  Suppose the initial estimate shows 1MB usage before creating
  // the db.  Compaction could happen after this step and before we measure
  // usage at the end, meaning the 1MB could be wiped to 0, an extra 1024 * 100
  // is put in, and the actual increase in usage does not reach our expected
  // increase.  Loop 10 times here to be safe (and reduce the number of bot
  // builds that fail); all it takes is one iteration without compaction for
  // this to pass.
  for (let i = 0; i < 10; i++) {
    const db = await createDB(dbname, objectStoreName, t);
    let estimate = await navigator.storage.estimate();

    // If usage is 0, usageDetails does not include the usage (undefined)
    usageBeforeWrite = estimate.usageDetails.indexedDB || 0;

    const txn = db.transaction(objectStoreName, 'readwrite');
    const valueToStore = largeValue(writeSize, Math.random() * 255);
    txn.objectStore(objectStoreName).add(valueToStore, 1);

    await transactionPromise(txn);

    estimate = await navigator.storage.estimate();
    usageAfterWrite = estimate.usageDetails.indexedDB;
    db.close();

    if (usageAfterWrite - usageBeforeWrite >= writeSize) {
      break;
    }
  }

  assert_greater_than_equal(usageAfterWrite - usageBeforeWrite,
      writeSize);
}, 'estimate() usage details reflects increase in indexedDB after large ' +
   'value is stored');


text:
var expect = require('chai').expect;
var path = require('path');
var files = require(path.join('..', 'lib', 'files'));

describe('Files', function() {

    describe('getTaskFiles()', function() {
        it('should call back with an array of task files', function(done) {
            files.getTaskFiles(function(err, tasks) {
                expect(err).to.be.null;
                expect(tasks).to.be.an('array');
                done();
            });
        });
    });

    describe('getUserFiles()', function() {
        it('should call back with an array of user files', function(done) {
            files.getUserFiles(function(err, users) {
                expect(err).to.be.null;
                expect(users).to.be.an('array');
                done();
            });
        });
    });

});


text:
import sublime
from sublime_plugin import TextCommand

PANEL_NAME = "GitSavvy"

class GsDisplayPanelCommand(TextCommand):

    """
    Given a `msg` string, open a transient text panel at the bottom of the
    active window, and display the `msg` contents there.
    """

    def run(self, edit, msg=""):
        panel_view = self.view.window().create_output_panel(PANEL_NAME)
        panel_view.set_read_only(False)
        panel_view.erase(edit, sublime.Region(0, panel_view.size()))
        panel_view.insert(edit, 0, msg)
        panel_view.set_read_only(True)
        panel_view.show(0)
        self.view.window().run_command("show_panel", {"panel": "output.{}".format(PANEL_NAME)})


text:
// Copyright 2016 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.android;

import com.google.common.base.Preconditions;
import com.google.common.base.Stopwatch;
import com.google.common.collect.ImmutableList;
import com.google.devtools.build.android.Converters.PathConverter;
import com.google.devtools.build.android.Converters.UnvalidatedAndroidDirectoriesConverter;
import com.google.devtools.common.options.Option;
import com.google.devtools.common.options.OptionsBase;
import com.google.devtools.common.options.OptionsParser;
import java.nio.file.Path;
import java.util.concurrent.TimeUnit;
import java.util.logging.Logger;

/**
 * Parses android resource XML files from a directory and serializes the results to a protobuf.
 * Other actions that depend on the same resource directory can then load the data from a single
 * protobuf instead of reparsing multiple tiny XML files from source (proto loading is faster).
 */
public class AndroidResourceParsingAction {

  private static final Logger logger =
      Logger.getLogger(AndroidResourceParsingAction.class.getName());

  /**
   * Flag specifications for this action.
   */
  public static final class Options extends OptionsBase {

    @Option(name = "primaryData",
        defaultValue = "null",
        converter = UnvalidatedAndroidDirectoriesConverter.class,
        category = "input",
        help = "The resource and asset directories to parse and summarize in a symbols file."
            + " The expected format is resources[#resources]:assets[#assets]")
    public UnvalidatedAndroidDirectories primaryData;

    @Option(name = "output",
        defaultValue = "null",
        converter = PathConverter.class,
        category = "output",
        help = "Path to write the output protobuf.")
    public Path output;
  }

  public static void main(String[] args) throws Exception {
    OptionsParser optionsParser = OptionsParser.newOptionsParser(Options.class);
    optionsParser.parseAndExitUponError(args);
    Options options = optionsParser.getOptions(Options.class);

    Preconditions.checkNotNull(options.primaryData);
    Preconditions.checkNotNull(options.output);

    final Stopwatch timer = Stopwatch.createStarted();
    ParsedAndroidData parsedPrimary = ParsedAndroidData.from(options.primaryData);
    logger.fine(String.format("Walked XML tree at %dms", timer.elapsed(TimeUnit.MILLISECONDS)));
    UnwrittenMergedAndroidData unwrittenData = UnwrittenMergedAndroidData.of(
        null,
        parsedPrimary,
        ParsedAndroidData.from(ImmutableList.<DependencyAndroidData>of()));
    AndroidDataSerializer serializer = AndroidDataSerializer.create();
    unwrittenData.serializeTo(serializer);
    serializer.flushTo(options.output);
    logger.fine(String.format(
        "Finished parse + serialize in %dms", timer.elapsed(TimeUnit.MILLISECONDS)));
  }

}


text:
package cn.nec.nlc.example.jamesli.activitytest54prefheader;

import android.os.Bundle;
import android.preference.PreferenceActivity;
import android.preference.PreferenceFragment;
import android.preference.PreferenceManager;
import android.util.Log;
import android.widget.Button;

import java.util.List;

public class PreferenceWithHeaders extends PreferenceActivity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // add a button to the header list
        if (hasHeaders()) {
            Button button = new Button(this);
            button.setText("Some Action");
            setListFooter(button);
        }
    }

    // populate the activity with the top-level headers

    @Override
    public void onBuildHeaders(List<Header> target) {
        loadHeadersFromResource(R.xml.preference_headers, target);
    }

    // this fragment shows the preferences for the first header
    public static class Prefs1Fragment extends PreferenceFragment {
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            // Make sure default values are applied.  In a real app, you would
            // want this in a shared function that is used to retrieve the
            // SharedPreferences wherever they are needed.
            PreferenceManager.setDefaultValues(getActivity(), R.xml.advanced_preferences, false);
              // true if set back all to default value
            // load the preferences from xml resource
            addPreferencesFromResource(R.xml.fragmented_preferences);
        }
    }

    // this fragment contains a second-level set of preference that you can get to by tapping
    // an item in the first preference fragment
    public static class Prefs1FragmentInner extends PreferenceFragment {
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            // can retrieve arguments from preference xml
            Log.i("args", "Arguments: " + getArguments());
            // load the preferences from an XML resource
            addPreferencesFromResource(R.xml.fragmented_preferences_inner);

        }
    }

    // this fragment shows the preferences for the second header
    public static class Prefs2Fragment extends PreferenceFragment {
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            // can retrieve arguments from preference xml
            Log.i("args", "Arguments: " + getArguments());
            // load the preferences from an XML resource
            addPreferencesFromResource(R.xml.preference_dependencies);
        }
    }
}


text:
@implementation NSString (Stackoverflow)

-(NSArray *)toArray:(BOOL)isString{

    NSString *seperator = @",";

    if(!isString) seperator = SymbolString;

    NSArray *arr = [self componentsSeparatedByString:seperator];

    if(isString) return arr;

    NSMutableArray *arrM = [NSMutableArray arrayWithCapacity:arr.count];

    if(arr == nil || arr.count == 0) return nil;

    [arr enumerateObjectsUsingBlock:^(NSString *str, NSUInteger idx, BOOL *stop) {

        NSData *data = [[NSData alloc] initWithBase64EncodedString:str options:NSDataBase64DecodingIgnoreUnknownCharacters];

        [arrM addObject:data];
    }];

    return arrM;
}

-(unsigned long long)unsignedLongLongValue{

    return self.longLongValue;
}

@end


text:
cordova.define("org.apache.cordova.file.FileWriter", function(require, exports, module) {

var exec = require('cordova/exec'),
    FileError = require('./FileError'),
    ProgressEvent = require('./ProgressEvent');

/**
 * This class writes to the mobile device file system.
 *
 * For Android:
 *      The root directory is the root of the file system.
 *      To write to the SD card, the file name is "sdcard/my_file.txt"
 *
 * @constructor
 * @param file {File} File object containing file properties
 * @param append if true write to the end of the file, otherwise overwrite the file
 */
var FileWriter = function(file) {
    this.fileName = "";
    this.length = 0;
    if (file) {
        this.fileName = file.fullPath || file;
        this.length = file.size || 0;
    }
    // default is to write at the beginning of the file
    this.position = 0;

    this.readyState = 0; // EMPTY

    this.result = null;

    // Error
    this.error = null;

    // Event handlers
    this.onwritestart = null;   // When writing starts
    this.onprogress = null;     // While writing the file, and reporting partial file data
    this.onwrite = null;        // When the write has successfully completed.
    this.onwriteend = null;     // When the request has completed (either in success or failure).
    this.onabort = null;        // When the write has been aborted. For instance, by invoking the abort() method.
    this.onerror = null;        // When the write has failed (see errors).
};

// States
FileWriter.INIT = 0;
FileWriter.WRITING = 1;
FileWriter.DONE = 2;

/**
 * Abort writing file.
 */
FileWriter.prototype.abort = function() {
    // check for invalid state
    if (this.readyState === FileWriter.DONE || this.readyState === FileWriter.INIT) {
        throw new FileError(FileError.INVALID_STATE_ERR);
    }

    // set error
    this.error = new FileError(FileError.ABORT_ERR);

    this.readyState = FileWriter.DONE;

    // If abort callback
    if (typeof this.onabort === "function") {
        this.onabort(new ProgressEvent("abort", {"target":this}));
    }

    // If write end callback
    if (typeof this.onwriteend === "function") {
        this.onwriteend(new ProgressEvent("writeend", {"target":this}));
    }
};

/**
 * Writes data to the file
 *
 * @param data text or blob to be written
 */
FileWriter.prototype.write = function(data) {

    var that=this;
    var supportsBinary = (typeof window.Blob !== 'undefined' && typeof window.ArrayBuffer !== 'undefined');
    var isBinary;

    // Check to see if the incoming data is a blob
    if (data instanceof File || (supportsBinary && data instanceof Blob)) {
        var fileReader = new FileReader();
        fileReader.onload = function() {
            // Call this method again, with the arraybuffer as argument
            FileWriter.prototype.write.call(that, this.result);
        };
        if (supportsBinary) {
            fileReader.readAsArrayBuffer(data);
        } else {
            fileReader.readAsText(data);
        }
        return;
    }

    // Mark data type for safer transport over the binary bridge
    isBinary = supportsBinary && (data instanceof ArrayBuffer);

    // Throw an exception if we are already writing a file
    if (this.readyState === FileWriter.WRITING) {
        throw new FileError(FileError.INVALID_STATE_ERR);
    }

    // WRITING state
    this.readyState = FileWriter.WRITING;

    var me = this;

    // If onwritestart callback
    if (typeof me.onwritestart === "function") {
        me.onwritestart(new ProgressEvent("writestart", {"target":me}));
    }

    // Write file
    exec(
        // Success callback
        function(r) {
            // If DONE (cancelled), then don't do anything
            if (me.readyState === FileWriter.DONE) {
                return;
            }

            // position always increases by bytes written because file would be extended
            me.position += r;
            // The length of the file is now where we are done writing.

            me.length = me.position;

            // DONE state
            me.readyState = FileWriter.DONE;

            // If onwrite callback
            if (typeof me.onwrite === "function") {
                me.onwrite(new ProgressEvent("write", {"target":me}));
            }

            // If onwriteend callback
            if (typeof me.onwriteend === "function") {
                me.onwriteend(new ProgressEvent("writeend", {"target":me}));
            }
        },
        // Error callback
        function(e) {
            // If DONE (cancelled), then don't do anything
            if (me.readyState === FileWriter.DONE) {
                return;
            }

            // DONE state
            me.readyState = FileWriter.DONE;

            // Save error
            me.error = new FileError(e);

            // If onerror callback
            if (typeof me.onerror === "function") {
                me.onerror(new ProgressEvent("error", {"target":me}));
            }

            // If onwriteend callback
            if (typeof me.onwriteend === "function") {
                me.onwriteend(new ProgressEvent("writeend", {"target":me}));
            }
        }, "File", "write", [this.fileName, data, this.position, isBinary]);
};

/**
 * Moves the file pointer to the location specified.
 *
 * If the offset is a negative number the position of the file
 * pointer is rewound.  If the offset is greater than the file
 * size the position is set to the end of the file.
 *
 * @param offset is the location to move the file pointer to.
 */
FileWriter.prototype.seek = function(offset) {
    // Throw an exception if we are already writing a file
    if (this.readyState === FileWriter.WRITING) {
        throw new FileError(FileError.INVALID_STATE_ERR);
    }

    if (!offset && offset !== 0) {
        return;
    }

    // See back from end of file.
    if (offset < 0) {
        this.position = Math.max(offset + this.length, 0);
    }
    // Offset is bigger than file size so set position
    // to the end of the file.
    else if (offset > this.length) {
        this.position = this.length;
    }
    // Offset is between 0 and file size so set the position
    // to start writing.
    else {
        this.position = offset;
    }
};

/**
 * Truncates the file to the size specified.
 *
 * @param size to chop the file at.
 */
FileWriter.prototype.truncate = function(size) {
    // Throw an exception if we are already writing a file
    if (this.readyState === FileWriter.WRITING) {
        throw new FileError(FileError.INVALID_STATE_ERR);
    }

    // WRITING state
    this.readyState = FileWriter.WRITING;

    var me = this;

    // If onwritestart callback
    if (typeof me.onwritestart === "function") {
        me.onwritestart(new ProgressEvent("writestart", {"target":this}));
    }

    // Write file
    exec(
        // Success callback
        function(r) {
            // If DONE (cancelled), then don't do anything
            if (me.readyState === FileWriter.DONE) {
                return;
            }

            // DONE state
            me.readyState = FileWriter.DONE;

            // Update the length of the file
            me.length = r;
            me.position = Math.min(me.position, r);

            // If onwrite callback
            if (typeof me.onwrite === "function") {
                me.onwrite(new ProgressEvent("write", {"target":me}));
            }

            // If onwriteend callback
            if (typeof me.onwriteend === "function") {
                me.onwriteend(new ProgressEvent("writeend", {"target":me}));
            }
        },
        // Error callback
        function(e) {
            // If DONE (cancelled), then don't do anything
            if (me.readyState === FileWriter.DONE) {
                return;
            }

            // DONE state
            me.readyState = FileWriter.DONE;

            // Save error
            me.error = new FileError(e);

            // If onerror callback
            if (typeof me.onerror === "function") {
                me.onerror(new ProgressEvent("error", {"target":me}));
            }

            // If onwriteend callback
            if (typeof me.onwriteend === "function") {
                me.onwriteend(new ProgressEvent("writeend", {"target":me}));
            }
        }, "File", "truncate", [this.fileName, size]);
};

module.exports = FileWriter;
});


text:
package com.amee.domain.algorithm;

import com.amee.base.utils.XMLUtils;
import com.amee.domain.ObjectType;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;

/**
 * This class defines a global algorithm context that can be inherited by algorithms
 */
@Entity
@DiscriminatorValue("ALC")
public class AlgorithmContext extends AbstractAlgorithm {

    public AlgorithmContext() {
        super();
    }

    public AlgorithmContext(String content) {
        super(content);
    }

    public Element getIdentityElement(Document document) {
        return XMLUtils.getIdentityElement(document, this);
    }

    @Override
    public String getElementName() {
        return "AlgorithmContext";
    }

    public ObjectType getObjectType() {
        return ObjectType.ALC;
    }
}


text:
namespace Microsoft.Azure.Management.CosmosDB
{
    using Microsoft.Rest;
    using Microsoft.Rest.Azure;
    using Models;
    using System.Collections;
    using System.Collections.Generic;
    using System.Threading;
    using System.Threading.Tasks;

    /// <summary>
    /// Extension methods for DatabaseOperations.
    /// </summary>
    public static partial class DatabaseOperationsExtensions
    {
            /// <summary>
            /// Retrieves the metrics determined by the given filter for the given database
            /// account and database.
            /// </summary>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='resourceGroupName'>
            /// The name of the resource group. The name is case insensitive.
            /// </param>
            /// <param name='accountName'>
            /// Cosmos DB database account name.
            /// </param>
            /// <param name='databaseRid'>
            /// Cosmos DB database rid.
            /// </param>
            /// <param name='filter'>
            /// An OData filter expression that describes a subset of metrics to return.
            /// The parameters that can be filtered are name.value (name of the metric, can
            /// have an or of multiple names), startTime, endTime, and timeGrain. The
            /// supported operator is eq.
            /// </param>
            public static IEnumerable<Metric> ListMetrics(this IDatabaseOperations operations, string resourceGroupName, string accountName, string databaseRid, string filter)
            {
                return operations.ListMetricsAsync(resourceGroupName, accountName, databaseRid, filter).GetAwaiter().GetResult();
            }

            /// <summary>
            /// Retrieves the metrics determined by the given filter for the given database
            /// account and database.
            /// </summary>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='resourceGroupName'>
            /// The name of the resource group. The name is case insensitive.
            /// </param>
            /// <param name='accountName'>
            /// Cosmos DB database account name.
            /// </param>
            /// <param name='databaseRid'>
            /// Cosmos DB database rid.
            /// </param>
            /// <param name='filter'>
            /// An OData filter expression that describes a subset of metrics to return.
            /// The parameters that can be filtered are name.value (name of the metric, can
            /// have an or of multiple names), startTime, endTime, and timeGrain. The
            /// supported operator is eq.
            /// </param>
            /// <param name='cancellationToken'>
            /// The cancellation token.
            /// </param>
            public static async Task<IEnumerable<Metric>> ListMetricsAsync(this IDatabaseOperations operations, string resourceGroupName, string accountName, string databaseRid, string filter, CancellationToken cancellationToken = default(CancellationToken))
            {
                using (var _result = await operations.ListMetricsWithHttpMessagesAsync(resourceGroupName, accountName, databaseRid, filter, null, cancellationToken).ConfigureAwait(false))
                {
                    return _result.Body;
                }
            }

            /// <summary>
            /// Retrieves the usages (most recent data) for the given database.
            /// </summary>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='resourceGroupName'>
            /// The name of the resource group. The name is case insensitive.
            /// </param>
            /// <param name='accountName'>
            /// Cosmos DB database account name.
            /// </param>
            /// <param name='databaseRid'>
            /// Cosmos DB database rid.
            /// </param>
            /// <param name='filter'>
            /// An OData filter expression that describes a subset of usages to return. The
            /// supported parameter is name.value (name of the metric, can have an or of
            /// multiple names).
            /// </param>
            public static IEnumerable<Usage> ListUsages(this IDatabaseOperations operations, string resourceGroupName, string accountName, string databaseRid, string filter = default(string))
            {
                return operations.ListUsagesAsync(resourceGroupName, accountName, databaseRid, filter).GetAwaiter().GetResult();
            }

            /// <summary>
            /// Retrieves the usages (most recent data) for the given database.
            /// </summary>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='resourceGroupName'>
            /// The name of the resource group. The name is case insensitive.
            /// </param>
            /// <param name='accountName'>
            /// Cosmos DB database account name.
            /// </param>
            /// <param name='databaseRid'>
            /// Cosmos DB database rid.
            /// </param>
            /// <param name='filter'>
            /// An OData filter expression that describes a subset of usages to return. The
            /// supported parameter is name.value (name of the metric, can have an or of
            /// multiple names).
            /// </param>
            /// <param name='cancellationToken'>
            /// The cancellation token.
            /// </param>
            public static async Task<IEnumerable<Usage>> ListUsagesAsync(this IDatabaseOperations operations, string resourceGroupName, string accountName, string databaseRid, string filter = default(string), CancellationToken cancellationToken = default(CancellationToken))
            {
                using (var _result = await operations.ListUsagesWithHttpMessagesAsync(resourceGroupName, accountName, databaseRid, filter, null, cancellationToken).ConfigureAwait(false))
                {
                    return _result.Body;
                }
            }

            /// <summary>
            /// Retrieves metric definitions for the given database.
            /// </summary>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='resourceGroupName'>
            /// The name of the resource group. The name is case insensitive.
            /// </param>
            /// <param name='accountName'>
            /// Cosmos DB database account name.
            /// </param>
            /// <param name='databaseRid'>
            /// Cosmos DB database rid.
            /// </param>
            public static IEnumerable<MetricDefinition> ListMetricDefinitions(this IDatabaseOperations operations, string resourceGroupName, string accountName, string databaseRid)
            {
                return operations.ListMetricDefinitionsAsync(resourceGroupName, accountName, databaseRid).GetAwaiter().GetResult();
            }

            /// <summary>
            /// Retrieves metric definitions for the given database.
            /// </summary>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='resourceGroupName'>
            /// The name of the resource group. The name is case insensitive.
            /// </param>
            /// <param name='accountName'>
            /// Cosmos DB database account name.
            /// </param>
            /// <param name='databaseRid'>
            /// Cosmos DB database rid.
            /// </param>
            /// <param name='cancellationToken'>
            /// The cancellation token.
            /// </param>
            public static async Task<IEnumerable<MetricDefinition>> ListMetricDefinitionsAsync(this IDatabaseOperations operations, string resourceGroupName, string accountName, string databaseRid, CancellationToken cancellationToken = default(CancellationToken))
            {
                using (var _result = await operations.ListMetricDefinitionsWithHttpMessagesAsync(resourceGroupName, accountName, databaseRid, null, cancellationToken).ConfigureAwait(false))
                {
                    return _result.Body;
                }
            }

    }
}


text:
import os
from datetime import datetime

from django.test import TestCase
from django.core.urlresolvers import reverse
from django.conf import settings
from django.core.files.uploadedfile import SimpleUploadedFile

from .models import File, Link

class FileTestCase(TestCase):

    def setUp(self):
        self.path = os.path.join(settings.MEDIA_ROOT,
                                 datetime.now().strftime(File.UPLOAD_TO))

        if not os.path.isdir(self.path):
            os.makedirs(self.path)

        self.total_files = len(os.listdir(self.path))

    def tst_anonymous_user(self):
        response = self.client.get(reverse('index'))
        self.assertEqual(response.status_code, 200)

        response = self.client.get(reverse('files-list'))
        self.assertEqual(response.status_code, 302)

    def tst_authorization(self):
        data = {'username': 'qqq', 'password': 'qqq'}
        response = self.client.post(reverse('index'), data)
        self.assertEqual(response.status_code, 404)

    def tst_registration1(self):
        data = {'username': 'qqq', 'password': 'qqq', 'is_register': 1}
        response = self.client.post(reverse('index'), data)
        self.assertEqual(response.status_code, 200)
        self.assertTrue('sessionid' in response.cookies)

    def tst_authorized_user(self):
        response = self.client.get(reverse('index'))
        self.assertEqual(response.status_code, 200)

        response = self.client.get(reverse('files-list'))
        self.assertEqual(response.status_code, 200)
        self.assertEqual([], response.json())

    def tst_file_upload1(self):
        data = {'file': SimpleUploadedFile('xxx.txt', b'x' * 4096)}
        response = self.client.post(reverse('files-list'), data)
        self.assertEqual(response.status_code, 200)
        self.assertEqual(Link.objects.all().count(), 1)
        self.assertEqual(File.objects.all().count(), 1)
        with self.assertRaises(ValueError):
            response.json()
        self.assertEqual(len(os.listdir(self.path)) - self.total_files, 1)

    def tst_file_upload2(self):
        """Дубликат первого."""
        data = {'file': SimpleUploadedFile('qqq.txt', b'x' * 4096)}
        response = self.client.post(reverse('files-list'), data)
        self.assertEqual(response.status_code, 200)
        self.assertEqual(Link.objects.all().count(), 2)
        self.assertEqual(File.objects.all().count(), 1)
        self.assertEqual([['qqq', 'xxx.txt']], response.json())
        self.assertEqual(len(os.listdir(self.path)) - self.total_files, 1)

    def tst_file_upload3(self):
        """Дубликат первого, но на один байт больше (одинаковый MD5)."""
        data = {'file': SimpleUploadedFile('hhh.txt', b'x' * 4097)}
        response = self.client.post(reverse('files-list'), data)
        self.assertEqual(response.status_code, 200)
        self.assertEqual(Link.objects.all().count(), 3)
        self.assertEqual(File.objects.all().count(), 2)
        with self.assertRaises(ValueError):
            response.json()
        self.assertEqual(len(os.listdir(self.path)) - self.total_files, 2)

    def tst_file_download1(self):
        response = self.client.get(reverse('download',
                                   kwargs={'pk': 1, 'name': 'any.ext'}))
        self.assertEqual(response.status_code, 200)

    def tst_file_download2(self):
        """Анонимно."""
        self.client.cookies.load({'sessionid': ''})
        response = self.client.get(reverse('download',
                                   kwargs={'pk': 2, 'name': 'any.ext'}))
        self.assertEqual(response.status_code, 200)

    def tst_file_download404(self):
        """Несуществующий файл."""
        response = self.client.get(reverse('download',
                                   kwargs={'pk': 404, 'name': 'any.ext'}))
        self.assertEqual(response.status_code, 404)

    def tst_registration2(self):
        data = {'username': 'hhh', 'password': 'hhh', 'is_register': 1}
        response = self.client.post(reverse('index'), data)
        self.assertEqual(response.status_code, 200)
        self.assertTrue('sessionid' in response.cookies)

    def tst_file_upload4(self):
        data = {'file': SimpleUploadedFile('kkk.txt', b'q' * 4096)}
        response = self.client.post(reverse('files-list'), data)
        self.assertEqual(response.status_code, 200)
        self.assertEqual(Link.objects.all().count(), 4)
        self.assertEqual(File.objects.all().count(), 3)
        with self.assertRaises(ValueError):
            response.json()
        self.assertEqual(len(os.listdir(self.path)) - self.total_files, 3)

    def tst_file_upload5(self):
        """Дубликат первого и второго."""
        data = {'file': SimpleUploadedFile('mmm.txt', b'x' * 4096)}
        response = self.client.post(reverse('files-list'), data)
        self.assertEqual(response.status_code, 200)
        self.assertEqual(Link.objects.all().count(), 5)
        self.assertEqual(File.objects.all().count(), 3)
        self.assertEqual([['qqq', 'xxx.txt'], ['qqq', 'qqq.txt']], response.json())
        self.assertEqual(len(os.listdir(self.path)) - self.total_files, 3)

    def tst_file_delete5(self):
        """Удаление дубликата первого и второго."""
        response = self.client.delete(reverse('files-detail', kwargs={'pk': 5}))
        self.assertEqual(response.status_code, 204)
        self.assertEqual(Link.objects.all().count(), 4)
        self.assertEqual(File.objects.all().count(), 3)
        self.assertEqual(len(os.listdir(self.path)) - self.total_files, 3)

    def tst_file_delete4(self):
        response = self.client.delete(reverse('files-detail', kwargs={'pk': 4}))
        self.assertEqual(response.status_code, 204)
        self.assertEqual(Link.objects.all().count(), 3)
        self.assertEqual(File.objects.all().count(), 2)
        self.assertEqual(len(os.listdir(self.path)) - self.total_files, 2)

    def tst_file_delete404(self):
        """Удаление файла, которого нет."""
        response = self.client.delete(reverse('files-detail', kwargs={'pk': 404}))
        self.assertEqual(response.status_code, 404)

    def tearDown(self):
        for link in Link.objects.all():
            link.delete()
        self.assertEqual(Link.objects.all().count(), 0)
        self.assertEqual(File.objects.all().count(), 0)
        self.assertEqual(len(os.listdir(self.path)) - self.total_files, 0)

    def test_files(self):
        self.tst_anonymous_user()
        self.tst_authorization()
        self.tst_registration1()
        self.tst_authorized_user()
        self.tst_file_upload1()
        self.tst_file_upload2()
        self.tst_file_upload3()
        self.tst_file_download1()
        self.tst_file_download2()
        self.tst_file_download404()
        self.tst_registration2()
        self.tst_file_upload4()
        self.tst_file_upload5()
        self.tst_file_delete5()
        self.tst_file_delete4()
        self.tst_file_delete404()


text:
import { GrabLineLinked } from "./GrabLineLinked";
export class Grab {
    constructor() {
        this.distance = 100;
        this.lineLinked = new GrabLineLinked();
    }
    get line_linked() {
        return this.lineLinked;
    }
    set line_linked(value) {
        this.lineLinked = value;
    }
    load(data) {
        var _a;
        if (data !== undefined) {
            if (data.distance !== undefined) {
                this.distance = data.distance;
            }
            this.lineLinked.load((_a = data.lineLinked) !== null && _a !== void 0 ? _a : data.line_linked);
        }
    }
}


text:
var readline = require('readline');

var googleapis = require('googleapis');
var OAuth2Client = googleapis.OAuth2Client;

// Client ID and client secret are available at
// https://code.google.com/apis/console
var configGoogle = require('../access.secret').google;
var CLIENT_ID = configGoogle.client_id;
var CLIENT_SECRET = configGoogle.client_secret;
var REDIRECT_URL = configGoogle.redirect_url;

var rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

function getAccessToken(oauth2Client, callback) {
  // generate consent page url
  var url = oauth2Client.generateAuthUrl({
    access_type: 'offline',
    scope: 'https://www.googleapis.com/auth/analytics.readonly'
  });

  console.log('Visit the url: ', url);
  rl.question('Enter the code here:', function(code) {

    // request access token
    oauth2Client.getToken(code, function(err, tokens) {
      // set tokens to the client
      // TODO: tokens should be set by OAuth2 client.
      oauth2Client.credentials = tokens;
      callback && callback();
    });
  });
}

function getAnalytics(client, authClient) {

    var params = {
        'ids' : 'ga:9588813',
        'start-date' : 'yesterday',
        'end-date' : 'today',
        'metrics' : 'ga:pageviews,ga:uniquePageviews,ga:timeOnPage',
        'dimensions' : 'ga:pagePath',
        'max-results' : '10',
        'sort' : '-ga:pageviews'
    }

    googleapis
        .discover('analytics','v3')
        .execute(function(err, client) {
            var req1 = client.analytics.data.ga.get(params)
            .withAuthClient(authClient)
            req1.execute(function (err, response) {
                console.log(err);
                console.log(response);
            });
        });
}

// load google plus v1 API resources and methods
googleapis
  .discover('analytics','v3')
  .execute(function(err, client) {

  var oauth2Client =
    new OAuth2Client(CLIENT_ID, CLIENT_SECRET, REDIRECT_URL);

  // retrieve an access token
  getAccessToken(oauth2Client, function() {
    // retrieve user profile
    getAnalytics(client, oauth2Client);
  });

});


text:
from six import text_type as str

from subliminal.utils import hash_opensubtitles, hash_thesubdb, sanitize

def test_hash_opensubtitles(mkv):
    assert hash_opensubtitles(mkv['test1']) == '40b44a7096b71ec3'

def test_hash_opensubtitles_too_small(tmpdir):
    path = tmpdir.ensure('test_too_small.mkv')
    assert hash_opensubtitles(str(path)) is None

def test_hash_thesubdb(mkv):
    assert hash_thesubdb(mkv['test1']) == '054e667e93e254f8fa9f9e8e6d4e73ff'

def test_hash_thesubdb_too_small(tmpdir):
    path = tmpdir.ensure('test_too_small.mkv')
    assert hash_thesubdb(str(path)) is None

def test_sanitize():
    assert sanitize('Marvel\'s Agents of S.H.I.E.L.D.') == 'marvels agents of s h i e l d'


text:
<?php

/**
 * This code was generated by
 * \ / _    _  _|   _  _
 * | (_)\/(_)(_|\/| |(/_  v1.0.0
 * /       /
 */

namespace Twilio\Rest\Autopilot\V1\Assistant;

use Twilio\Exceptions\TwilioException;
use Twilio\InstanceContext;
use Twilio\Values;
use Twilio\Version;

/**
 * PLEASE NOTE that this class contains preview products that are subject to change. Use them with caution. If you currently do not have developer preview access, please contact help@twilio.com.
 */
class DialogueContext extends InstanceContext {
    /**
     * Initialize the DialogueContext
     *
     * @param \Twilio\Version $version Version that contains the resource
     * @param string $assistantSid The SID of the Assistant that is the parent of
     *                             the resource to fetch
     * @param string $sid The unique string that identifies the resource
     * @return \Twilio\Rest\Autopilot\V1\Assistant\DialogueContext
     */
    public function __construct(Version $version, $assistantSid, $sid) {
        parent::__construct($version);

        // Path Solution
        $this->solution = array('assistantSid' => $assistantSid, 'sid' => $sid, );

        $this->uri = '/Assistants/' . \rawurlencode($assistantSid) . '/Dialogues/' . \rawurlencode($sid) . '';
    }

    /**
     * Fetch a DialogueInstance
     *
     * @return DialogueInstance Fetched DialogueInstance
     * @throws TwilioException When an HTTP error occurs.
     */
    public function fetch() {
        $params = Values::of(array());

        $payload = $this->version->fetch(
            'GET',
            $this->uri,
            $params
        );

        return new DialogueInstance(
            $this->version,
            $payload,
            $this->solution['assistantSid'],
            $this->solution['sid']
        );
    }

    /**
     * Provide a friendly representation
     *
     * @return string Machine friendly representation
     */
    public function __toString() {
        $context = array();
        foreach ($this->solution as $key => $value) {
            $context[] = "$key=$value";
        }
        return '[Twilio.Autopilot.V1.DialogueContext ' . \implode(' ', $context) . ']';
    }
}


text:
#import "MDCTextInputController.h"

/**
 Material Design compliant text field. The logic for 'automagic' error states changes:
 underline color, underline text color.
 https://www.google.com/design/spec/components/text-fields.html#text-fields-single-line-text-field

 The placeholder is laid out inline and the character count is also inline to the right.

 Defaults:

 Active Color - Blue A700

 Border Fill Color - Clear
 Border Stroke Color - Clear

 Disabled Color = [UIColor lightGrayColor]

 Error Color - Red A400

 Floating Placeholder Color Active - Blue A700
 Floating Placeholder Color Normal - Black, 54% opacity

 Inline Placeholder Color - Black, 54% opacity

 Leading Underline Label Text Color - Black, 54% opacity

 Normal Color - Black, 54% opacity

 Rounded Corners - None

 Trailing Underline Label Text Color - Black, 54% opacity

 Underline Height Active - 0p
 Underline Height Normal - 0p

 Underline View Mode - While editing
 */
@interface MDCTextInputControllerLegacyFullWidth : NSObject <MDCTextInputController>

@end


text:
#include "NewParametricShaderNode.h"

/**
* Create a node.
*
* @param vert Vertex shader file name.
* @param frag Fragment shader file name.
* @return Created node
*/
NewParametricShaderNode* NewParametricShaderNode::create(const std::string &vert, const std::string& frag)
{
	auto node = new NewParametricShaderNode();
	node->init(vert, frag);
	node->autorelease();

	return node;
}

/**
* Build a parametric surface.
*/
NewParametricShaderNode::NewParametricShaderNode()
: ParametricMeshShaderNode(50, 50)
{
	_scale = 1.0f;

	// Compute vertices and normal vectors
//	computeVertexAndNormals(-M_PI/2, M_PI/2, -M_PI/2, M_PI/2);
//	computeVertexAndNormals(0, M_PI, 0, M_PI * 2);
//	computeVertexAndNormals(0, 2 * M_PI, 0, 1);
	computeVertexAndNormals(0, 2 * M_PI, 0, 2 * M_PI);

	for (int i = 0; i < _numVertices; i++) {
		log("[%d] Pos=(%.2f %.2f %.2f) N=(%.2f %.2f %.2f) uv=(%.2f %.2f)\n", i,
			_vertices[i].position[0], _vertices[i].position[1], _vertices[i].position[2],
			_vertices[i].normal[0], _vertices[i].normal[1], _vertices[i].normal[2],
			_vertices[i].texCoord[0], _vertices[i].texCoord[1]);
	}

	// Compute the number of indices
	_numIndices = (_sampleU - 1) * (_sampleV - 1) * 2 * 3;

	// Generate and fill in the index array.
	generateIndices();
}

NewParametricShaderNode::~NewParametricShaderNode()
{
}

/**
* Evaluate from 2-D to 3-D
*
* Ex. X-Y plane
*
* float x = u;
* float y = v;
* float z = 0;
*
* @param domain Domain
*/
Vec3 NewParametricShaderNode::evaluate(const Vec2& domain) const
{
	float u = domain.x, v = domain.y;

	const float major = 1;
	const float minor = 0.2f;
	float x = (major + minor * cos(v)) * cos(u);
	float y = (major + minor * cos(v)) * sin(u);
	float z = minor * sin(v);
	return Vec3(x, y, z);
}

/**
* Update per frames.
*
* @param dt Elapsed time
*/
void NewParametricShaderNode::update(float dt)
{
	_time += dt;

	_rotation3d.y += 0.1f * M_PI / 180;

	// Pass the current time (float value)
	getGLProgramState()->setUniformFloat("u_time", _time);
}

/**
* Draws the model
*
* @param transform Transform matrix
* @param flags Flags to draw
*/
void NewParametricShaderNode::onDraw(const Mat4 &transform, uint32_t flags)
{
	setCommon3dEnvironment();

	auto glProgramState = getGLProgramState();
	// Pass the position parameter to the vertex shader's attribute variable
	glProgramState->setVertexAttribPointer("a_position",
		3, GL_FLOAT, GL_FALSE, 44, _vertices[0].position);
	glProgramState->setVertexAttribPointer("a_normal",
		3, GL_FLOAT, GL_FALSE, 44, _vertices[0].normal);
	glProgramState->setVertexAttribPointer("a_texCoord",
		2, GL_FLOAT, GL_FALSE, 44, _vertices[0].texCoord);
	glProgramState->setVertexAttribPointer("a_tangent",
		3, GL_FLOAT, GL_FALSE, 44, _vertices[0].tangent);
	glProgramState->apply(transform);

	glEnable(GL_DEPTH_TEST);
	glCullFace(GL_BACK);
	//	glCullFace(GL_FRONT);
	glEnable(GL_CULL_FACE);

	// Alpha blenfing
//	glEnable(GL_BLEND);
//	glDisable(GL_BLEND);
//	glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
//	glBlendFunc(GL_ONE, GL_ONE);

	// Draw triangles using indices
	glDrawElements(GL_TRIANGLES, _numIndices, GL_UNSIGNED_SHORT, _indices);

//	glDisable(GL_BLEND);
	//	CC_INCREMENT_GL_DRAWN_BATCHES_AND_VERTICES(1, 3);
}


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

namespace Cake\Datasource;

use Cake\Collection\Collection;
use Countable;

/**
 * Generic ResultSet decorator. This will make any traversable object appear to
 * be a database result
 */
class ResultSetDecorator extends Collection implements ResultSetInterface
{
    /**
     * Make this object countable.
     *
     * Part of the Countable interface. Calling this method
     * will convert the underlying traversable object into an array and
     * get the count of the underlying data.
     *
     * @return int
     */
    public function count(): int
    {
        $iterator = $this->getInnerIterator();
        if ($iterator instanceof Countable) {
            return $iterator->count();
        }

        return count($this->toArray());
    }
}


text:
提示

    <input id='return_url' type='hidden' value='0'/>
    <input id='button_ok' class="btn" type="button" value='确定' onclick="ClossMessageBox('-1')"/>


text:
namespace OctoHook
{
	using System.Threading.Tasks;

	/// <summary>
	/// Interface implemented by async jobs triggered from
	/// GitHub webhooks, which leverage Octokit object model
	/// and take longer to execute.
	/// </summary>
	/// <remarks>
	/// This interface allows hooks that would otherwise cause
	/// timeout errors on the GitHub side to run successfully to
	/// completion, since the response to GitHub is an immediate
	/// success. Further logging at the destination service is
	/// required to actually determine execution outcome, so
	/// these hooks are a bit harder to diagnose.
	/// </remarks>
	/// <typeparam name="TEvent">Type of event processed by this webhook.</typeparam>
	public interface IOctoJob<TEvent>
	{
		/// <summary>
		/// Processes the specified event received by the webhook in
		/// an asynchronous fashion, from a background job scheduler
		/// after the webhook execution returns success to GitHub.
		/// </summary>
		Task ProcessAsync(TEvent @event);
	}
}


text:
/**
 * Package containing a data uri handler (needs to be nested like this to be picked up by the
 * java.protocol.handler.pkgs system property).
 */
package org.mapfish.print.url.data;


text:
-   node >= 16.15.1
-   npm >= 8.11.0
-   verify/update `.env` (or https://stackoverflow.com/questions/43069087/pass-shell-environment-variable-as-argument-in-npm-script)

## dev

1. `npm install` or `npm ci`
2. `npm start` or `NU_FE_CORE_URL=http://... npm start`
3. read logs

Note: `NU_FE_CORE_URL` should point to NU core frontend application (when running in development mode this is `http://localhost:3000`). By default, it is `/static` which is meant for production build.

## prod

1. `npm ci`
2. `cp -r client/.federated-types/nussknackerUi submodules/types/@remote` and `CI=true npm run build` or `NU_FE_CORE_URL=http://... npm run build`
3. wait for `dist(s)`


text:
using System;
using Xamarin.Forms;

namespace Reducto.Sample
{
    public class Navigator : INavigator
    {
        INavigation navigation;

        public Navigator(INavigation navigation)
        {
            this.navigation = navigation;
        }

        public System.Threading.Tasks.Task PopToRootAsync(bool animated)
        {
            return navigation.PopToRootAsync(animated);
        }

        public System.Threading.Tasks.Task PushAsync<Model>() where Model : ViewModel
        {
            ViewModel vm = (ViewModel)Activator.CreateInstance(typeof(Model));
            vm.Init();
            return navigation.PushAsync(vm.Page);
        }

        public System.Threading.Tasks.Task PushAsync<Model>(Func<Model> configureModel) where Model : ViewModel
        {
            var model = configureModel();
            model.Init();
            return navigation.PushAsync(model.Page);
        }
    }
}