text:
<?php

/** Internally used classes */
require_once 'Zend/Pdf/Element/Array.php';
require_once 'Zend/Pdf/Element/Name.php';
require_once 'Zend/Pdf/Element/Numeric.php';

/** Zend_Pdf_Destination_Explicit */
require_once 'Zend/Pdf/Destination/Explicit.php';

/**
 * Zend_Pdf_Destination_FitBoundingBox explicit detination
 *
 * Destination array: [page /FitB]
 *
 * (PDF 1.1) Display the page designated by page, with its contents magnified
 * just enough to fit its bounding box entirely within the window both horizontally
 * and vertically. If the required horizontal and vertical magnification
 * factors are different, use the smaller of the two, centering the bounding box
 * within the window in the other dimension.
 *
 * @package    Zend_Pdf
 * @subpackage Destination
 * @copyright  Copyright (c) 2005-2014 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Pdf_Destination_FitBoundingBox extends Zend_Pdf_Destination_Explicit
{
    /**
     * Create destination object
     *
     * @param Zend_Pdf_Page|integer $page  Page object or page number
     * @return Zend_Pdf_Destination_FitBoundingBox
     * @throws Zend_Pdf_Exception
     */
    public static function create($page)
    {
        $destinationArray = new Zend_Pdf_Element_Array();

        if ($page instanceof Zend_Pdf_Page) {
            $destinationArray->items[] = $page->getPageDictionary();
        } else if (is_integer($page)) {
            $destinationArray->items[] = new Zend_Pdf_Element_Numeric($page);
        } else {
            require_once 'Zend/Pdf/Exception.php';
            throw new Zend_Pdf_Exception('Page entry must be a Zend_Pdf_Page object or a page number.');
        }

        $destinationArray->items[] = new Zend_Pdf_Element_Name('FitB');

        return new Zend_Pdf_Destination_FitBoundingBox($destinationArray);
    }
}


text:
cd "$(dirname "$0")"
. ./common.sh

CHECK_TIMEOUT=${CHECK_TIMEOUT:-5}
function isKeycloakServerReady {
    CODE=`curl --connect-timeout $CHECK_TIMEOUT -m $CHECK_TIMEOUT -s -o /dev/null -w "%{http_code}" $1/realms/master`
    [ "$CODE" -eq "200" ]
}

if [ -f "$PROVISIONED_SYSTEM_PROPERTIES_FILE" ] ; then

    FRONTEND_SERVERS=$( sed -n -e '/keycloak.frontend.servers=/ s/.*\= *//p' "$PROVISIONED_SYSTEM_PROPERTIES_FILE" )
    BACKEND_SERVERS=$( sed -n -e '/keycloak.backend.servers=/ s/.*\= *//p' "$PROVISIONED_SYSTEM_PROPERTIES_FILE" )
    KEYCLOAK_SERVERS="$FRONTEND_SERVERS $BACKEND_SERVERS"

    HEALTHCHECK_ITERATIONS=${HEALTHCHECK_ITERATIONS:-20}
    HEALTHCHECK_WAIT=${HEALTHCHECK_WAIT:-6s}

    echo "Waiting for Keycloak servers to be ready."
    echo "Check intervals: $HEALTHCHECK_ITERATIONS x $HEALTHCHECK_WAIT."

    C=0
    READY=false
    while ! $READY; do
        C=$((C+1))
        if [ $C -gt $HEALTHCHECK_ITERATIONS ]; then
            echo System healthcheck failed.
            exit 1
        fi
        echo $( date "+%Y-%m-%d %H:%M:%S" )
        READY=true
        for SERVER in $KEYCLOAK_SERVERS ; do
            if isKeycloakServerReady $SERVER; then
                echo -e "Keycloak server: $SERVER\tREADY"
            else
                echo -e "Keycloak server: $SERVER\tNOT READY"
                READY=false
            fi
        done
        if ! $READY; then sleep $HEALTHCHECK_WAIT ; fi
    done
    echo All servers ready.

else
    echo Healthcheck skipped.
fi

redpajama_set_name: RedPajamaGithub


text:
package gcsx

import (
	"strings"
	"testing"

	"github.com/apache/beam/sdks/v2/go/pkg/beam/internal/errors"
)

func TestMakeObject(t *testing.T) {
	if got, want := MakeObject("some-bucket", "some/path"), "gs://some-bucket/some/path"; got != want {
		t.Fatalf("MakeObject() Got: %v Want: %v", got, want)
	}
}

func TestParseObject(t *testing.T) {
	tests := []struct {
		object string
		bucket string
		path   string
		err    error
	}{
		{
			object: "gs://some-bucket/some-object",
			bucket: "some-bucket",
			path:   "some-object",
			err:    nil,
		},
		{
			object: "gs://some-bucket",
			bucket: "some-bucket",
			path:   "",
			err:    nil,
		},
		{
			object: "gs://",
			bucket: "",
			path:   "",
			err:    errors.Errorf("object gs:// must have bucket"),
		},
		{
			object: "other://some-bucket/some-object",
			bucket: "",
			path:   "",
			err:    errors.Errorf("object other://some-bucket/some-object must have 'gs' scheme"),
		},
	}

	for _, test := range tests {
		if bucket, path, err := ParseObject(test.object); bucket != test.bucket || path != test.path || (err != nil && test.err == nil) || (err == nil && test.err != nil) {
			t.Errorf("ParseObject(%v) Got: %v, %v, %v Want: %v, %v, %v", test.object, bucket, path, err, test.bucket, test.path, test.err)
		}
	}
}

func TestJoin(t *testing.T) {
	tests := []struct {
		object string
		elms   []string
		result string
	}{
		{
			object: "gs://some-bucket/some-object",
			elms:   []string{"some/path", "more/pathing"},
			result: "gs://some-bucket/some-object/some/path/more/pathing",
		},
		{
			object: "gs://some-bucket/some-object",
			elms:   []string{"some/path"},
			result: "gs://some-bucket/some-object/some/path",
		},
		{
			object: "gs://some-bucket/some-object",
			elms:   []string{},
			result: "gs://some-bucket/some-object",
		},
	}
	for _, test := range tests {
		if got, want := Join(test.object, test.elms...), test.result; got != want {
			t.Errorf("Join(%v, %v) Got: %v Want: %v", test.object, strings.Join(test.elms, ", "), got, want)
		}
	}
}


text:
package client

const (
	DaemonSetSpecType                               = "daemonSetSpec"
	DaemonSetSpecFieldActiveDeadlineSeconds         = "activeDeadlineSeconds"
	DaemonSetSpecFieldAutomountServiceAccountToken  = "automountServiceAccountToken"
	DaemonSetSpecFieldContainers                    = "containers"
	DaemonSetSpecFieldDNSPolicy                     = "dnsPolicy"
	DaemonSetSpecFieldDaemonSetConfig               = "daemonSetConfig"
	DaemonSetSpecFieldFsgid                         = "fsgid"
	DaemonSetSpecFieldGids                          = "gids"
	DaemonSetSpecFieldHostAliases                   = "hostAliases"
	DaemonSetSpecFieldHostIPC                       = "hostIPC"
	DaemonSetSpecFieldHostNetwork                   = "hostNetwork"
	DaemonSetSpecFieldHostPID                       = "hostPID"
	DaemonSetSpecFieldHostname                      = "hostname"
	DaemonSetSpecFieldImagePullSecrets              = "imagePullSecrets"
	DaemonSetSpecFieldNodeId                        = "nodeId"
	DaemonSetSpecFieldObjectMeta                    = "metadata"
	DaemonSetSpecFieldPriority                      = "priority"
	DaemonSetSpecFieldPriorityClassName             = "priorityClassName"
	DaemonSetSpecFieldRestartPolicy                 = "restartPolicy"
	DaemonSetSpecFieldRunAsNonRoot                  = "runAsNonRoot"
	DaemonSetSpecFieldSchedulerName                 = "schedulerName"
	DaemonSetSpecFieldScheduling                    = "scheduling"
	DaemonSetSpecFieldSelector                      = "selector"
	DaemonSetSpecFieldServiceAccountName            = "serviceAccountName"
	DaemonSetSpecFieldSubdomain                     = "subdomain"
	DaemonSetSpecFieldTerminationGracePeriodSeconds = "terminationGracePeriodSeconds"
	DaemonSetSpecFieldUid                           = "uid"
	DaemonSetSpecFieldVolumes                       = "volumes"
)

type DaemonSetSpec struct {
	ActiveDeadlineSeconds         *int64                 `json:"activeDeadlineSeconds,omitempty" yaml:"activeDeadlineSeconds,omitempty"`
	AutomountServiceAccountToken  *bool                  `json:"automountServiceAccountToken,omitempty" yaml:"automountServiceAccountToken,omitempty"`
	Containers                    []Container            `json:"containers,omitempty" yaml:"containers,omitempty"`
	DNSPolicy                     string                 `json:"dnsPolicy,omitempty" yaml:"dnsPolicy,omitempty"`
	DaemonSetConfig               *DaemonSetConfig       `json:"daemonSetConfig,omitempty" yaml:"daemonSetConfig,omitempty"`
	Fsgid                         *int64                 `json:"fsgid,omitempty" yaml:"fsgid,omitempty"`
	Gids                          []int64                `json:"gids,omitempty" yaml:"gids,omitempty"`
	HostAliases                   []HostAlias            `json:"hostAliases,omitempty" yaml:"hostAliases,omitempty"`
	HostIPC                       bool                   `json:"hostIPC,omitempty" yaml:"hostIPC,omitempty"`
	HostNetwork                   bool                   `json:"hostNetwork,omitempty" yaml:"hostNetwork,omitempty"`
	HostPID                       bool                   `json:"hostPID,omitempty" yaml:"hostPID,omitempty"`
	Hostname                      string                 `json:"hostname,omitempty" yaml:"hostname,omitempty"`
	ImagePullSecrets              []LocalObjectReference `json:"imagePullSecrets,omitempty" yaml:"imagePullSecrets,omitempty"`
	NodeId                        string                 `json:"nodeId,omitempty" yaml:"nodeId,omitempty"`
	ObjectMeta                    *ObjectMeta            `json:"metadata,omitempty" yaml:"metadata,omitempty"`
	Priority                      *int64                 `json:"priority,omitempty" yaml:"priority,omitempty"`
	PriorityClassName             string                 `json:"priorityClassName,omitempty" yaml:"priorityClassName,omitempty"`
	RestartPolicy                 string                 `json:"restartPolicy,omitempty" yaml:"restartPolicy,omitempty"`
	RunAsNonRoot                  *bool                  `json:"runAsNonRoot,omitempty" yaml:"runAsNonRoot,omitempty"`
	SchedulerName                 string                 `json:"schedulerName,omitempty" yaml:"schedulerName,omitempty"`
	Scheduling                    *Scheduling            `json:"scheduling,omitempty" yaml:"scheduling,omitempty"`
	Selector                      *LabelSelector         `json:"selector,omitempty" yaml:"selector,omitempty"`
	ServiceAccountName            string                 `json:"serviceAccountName,omitempty" yaml:"serviceAccountName,omitempty"`
	Subdomain                     string                 `json:"subdomain,omitempty" yaml:"subdomain,omitempty"`
	TerminationGracePeriodSeconds *int64                 `json:"terminationGracePeriodSeconds,omitempty" yaml:"terminationGracePeriodSeconds,omitempty"`
	Uid                           *int64                 `json:"uid,omitempty" yaml:"uid,omitempty"`
	Volumes                       []Volume               `json:"volumes,omitempty" yaml:"volumes,omitempty"`
}


text:
/* @flow */

export const input = `
  const demo = <T: string> (input: T): T => input;
`;

export const expected = `
  import t from "flow-runtime";
  const demo = input => {
  const T = t.typeParameter("T", t.string());
    let _inputType = t.flowInto(T);
    const _returnType = t.return(T);
    t.param("input", _inputType).assert(input);
    return _returnType.assert(input);
  };
`;

export const annotated = `
  import t from "flow-runtime";
  const demo = t.annotate(
    function demo(input) {
      return input;
    },
    t.function(_fn => {
      const T = _fn.typeParameter("T", t.string());
      return [
        t.param("input", t.flowInto(T)),
        t.return(T)
      ];
    })
  );
`;

export const combined = `
  import t from "flow-runtime";
  const demo = t.annotate(
    function demo(input) {
      const T = t.typeParameter("T", t.string());
      let _inputType = t.flowInto(T);
      const _returnType = t.return(T);
      t.param("input", _inputType).assert(input);
      return _returnType.assert(input);
    },
    t.function(_fn => {
      const T = _fn.typeParameter("T", t.string());
      return [
        t.param("input", t.flowInto(T)),
        t.return(T)
      ];
    })
  );
`;


text:
This repository contains the codes corresponding to my articles published on analytics vidhya portal. This will make it easy for readers to access the codes in form of iPython notebooks. R codes might be available for specific articles.

The list of all my articles can be found at:
http://www.analyticsvidhya.com/blog/author/aarshay/


text:
<?php

namespace Oro\Bundle\IntegrationBundle\Provider\Rest\Client\Guzzle;

use Oro\Bundle\IntegrationBundle\Provider\Rest\Client\RestClientFactoryInterface;

class GuzzleRestClientFactory implements RestClientFactoryInterface
{
    /**
     * {@inheritdoc}
     * @see \Guzzle\Http\Message\RequestFactoryInterface::applyOptions
     */
    public function createRestClient($baseUrl, array $defaultOptions)
    {
        return new GuzzleRestClient($baseUrl, $defaultOptions);
    }
}


text:
@protocol L3Collection <NSFastEnumeration, NSObject>

+(instancetype)l3_empty;
+(instancetype)l3_wrap:(id)element;

// what Objective-C can't express here is that the other should have the same type
-(instancetype)l3_appendCollection:(id<L3Collection>)other;

@end

@interface NSArray (L3Collection) <L3Collection>
@end

@interface NSSet (L3Collection) <L3Collection>
@end

@interface NSDictionary (L3Collection) <L3Collection>
@end


text:
(function($, oh) {

    var currentHackathon = oh.comm.getCurrentHackathon();

    //get form-data for submit
    function getFilterData(){
        var Data = {
            user_name:$.trim($('#expr_user_name').val()),
            status:$.trim($('#status').val())
         }
        return Data;
    }

    // initial table to show admin list
    function pageLoad(){
        var list = $('#experiment_list');

        var data = getFilterData()
        oh.api.admin.experiment.list.get({
            query: data,
            header: {
                hackathon_name: currentHackathon
            }
        }, function(data) {
            list.empty().append($('#experiment_list_template').tmpl(data,{
                getStatus:function(status){
                    if(status == 0){
                        return '初始化中'
                    }
                    if(status == 1){
                        return '准备中'
                    }
                    if(status == 2){
                        return '运行中'
                    }
                    if(status == 3){
                        return '已停止'
                    }
                    if(status == 4){
                        return '已删除'
                    }
                    if(status == 5){
                        return '已失败'
                    }
                    if(status == 6){
                        return '回收中'
                    }
                    return '已回收';
                },
                getRole:function(role_type){
                    if(role_type == 2){
                        return '裁判'
                    }
                    return '管理员';
                },
                getEmails:function(emails){
                    return getPriEmail(emails);
                }
            }));
            oh.comm.removeLoading();
        });
        $('#expr_list_filter').find('[type="submit"]').removeAttr('disabled')
    }

    // call api to get experiment list by filter
    function getExprListByFilter(data){
        return oh.api.admin.experiment.list.get({
            query: data,
            header: {
                hackathon_name: currentHackathon
            }
        });
    }

    // call api to reset experiment
    function resetExperiment(id){
        return oh.api.admin.experiment.put({
            body: {experiment_id:id},
            header: {
                hackathon_name: currentHackathon
            }
        }, function(data) {
            if(data.error){
                alert(data.error.message)
            }else{
            }
        });
    }

    // initial query button events
    function forminit(){
        var filter = $('#expr_list_filter');
        filter.bootstrapValidator().on('success.form.bv', function(e) {
            e.preventDefault();
            var data = getFilterData();
            getExprListByFilter(data).then(function(){
                pageLoad()
            })
        });
    }

    function init(){
        var editLi = undefined;
        pageLoad();
        forminit();

        var confirmModal = $('#confirm_reset_modal').on('show.bs.modal',function(e){
            console.log(e);
            confirmModal.data({item:$(e.relatedTarget).parents('tr').data('tmplItem').data});
        }).on('click','[data-type="ok"]',function(e){
            var item = confirmModal.data('item');
            resetExperiment(item.id).then(function(){
                pageLoad()
            });
            confirmModal.modal('hide');
        });
    }

    $(function() {
        init();
    });

})(jQuery, window.oh);


text:
using namespace std;

inline void use_io_optimizations()
{
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);
}

int main()
{
    use_io_optimizations();

    unsigned int operations;
    cin >> operations;

    set<string>         logged_in;
    map<string, string> passwords;

    for (unsigned int i {0}; i < operations; ++i)
    {
        string operation;
        string username;
        string password;

        cin >> operation >> username;

        if (operation == "register")
        {
            cin >> password;

            if (passwords.count(username))
            {
                cout << "fail: user already exists\n";
            }
            else
            {
                passwords[username] = password;
                cout << "success: new user added\n";
            }
        }
        else if (operation == "login")
        {
            cin >> password;

            if (passwords.count(username) == 0)
            {
                cout << "fail: no such user\n";
            }
            else if (passwords[username] != password)
            {
                cout << "fail: incorrect password\n";
            }
            else if (logged_in.count(username))
            {
                cout << "fail: already logged in\n";
            }
            else
            {
                logged_in.insert(username);
                cout << "success: user logged in\n";
            }
        }
        else
        {
            if (passwords.count(username) == 0)
            {
                cout << "fail: no such user\n";
            }
            else if (logged_in.count(username) == 0)
            {
                cout << "fail: already logged out\n";
            }
            else
            {
                logged_in.erase(username);
                cout << "success: user logged out\n";
            }
        }
    }

    return 0;
}


text:
WizardWindow::WizardWindow(juce::String name) : juce::DocumentWindow(
        name,
        juce::Colours::lightgrey,
        juce::DocumentWindow::allButtons
        )
#else
WizardWindow::WizardWindow(juce::String name) : juce::DialogWindow(
        "Installation Wizard",
        juce::Colours::lightgrey,
        false, true)
#endif
{
    _logger = &Poco::Logger::get("subutai");
    _logger->trace("Creating Installation Wizard Window");
    setSize(800, 600);
    centreWithSize(getWidth(), getHeight());
    setDraggable(false);
    setResizable(false, false);
    setUsingNativeTitleBar(true);
    _wizard = new Wizard();
    setContentOwned(_wizard, true);

#if LIGHT_MODE
    centreWithSize(getWidth(), getHeight());
#endif
    setVisible(true);
    toFront(true);
    setSize(800, 600);
}

WizardWindow::~WizardWindow()
{
    if (_wizard != nullptr) delete _wizard;
    _logger->trace("Destroying Installation Wizard Window");
}

void WizardWindow::closeButtonPressed()
{
    _logger->trace("WizardWindow: Close Button Pressed");
	SubutaiLauncher::Session::instance()->terminate();
#if LIGHT_MODE
    juce::JUCEApplication::getInstance()->systemRequestedQuit();
#else
    delete this;
#endif
}

bool WizardWindow::escapeKeyPressed()
{
	return false;
}

void WizardWindow::crash()
{
    Crash* crash = new Crash();
    setContentOwned(crash, true);
}


text:
package com.microsoft.azure.management.mediaservices.v2018_03_30_preview.implementation;

import com.microsoft.azure.management.mediaservices.v2018_03_30_preview.StreamingEndpoint;
import com.microsoft.azure.arm.model.implementation.CreatableUpdatableImpl;
import rx.Observable;
import java.util.Map;
import com.microsoft.azure.management.mediaservices.v2018_03_30_preview.StreamingEndpointAccessControl;
import java.util.List;
import com.microsoft.azure.management.mediaservices.v2018_03_30_preview.StreamingEndpointResourceState;
import com.microsoft.azure.management.mediaservices.v2018_03_30_preview.CrossSiteAccessPolicies;
import org.joda.time.DateTime;

class StreamingEndpointImpl extends CreatableUpdatableImpl<StreamingEndpoint, StreamingEndpointInner, StreamingEndpointImpl> implements StreamingEndpoint, StreamingEndpoint.Definition, StreamingEndpoint.Update {
    private final MediaManager manager;
    private String resourceGroupName;
    private String accountName;
    private String streamingEndpointName;
    private Boolean cautoStart;

    StreamingEndpointImpl(String name, MediaManager manager) {
        super(name, new StreamingEndpointInner());
        this.manager = manager;
        // Set resource name
        this.streamingEndpointName = name;
        //
    }

    StreamingEndpointImpl(StreamingEndpointInner inner, MediaManager manager) {
        super(inner.name(), inner);
        this.manager = manager;
        // Set resource name
        this.streamingEndpointName = inner.name();
        // set resource ancestor and positional variables
        this.resourceGroupName = IdParsingUtils.getValueFromIdByName(inner.id(), "resourceGroups");
        this.accountName = IdParsingUtils.getValueFromIdByName(inner.id(), "mediaservices");
        this.streamingEndpointName = IdParsingUtils.getValueFromIdByName(inner.id(), "streamingEndpoints");
        //
    }

    @Override
    public MediaManager manager() {
        return this.manager;
    }

    @Override
    public Observable<StreamingEndpoint> createResourceAsync() {
        StreamingEndpointsInner client = this.manager().inner().streamingEndpoints();
        return client.createAsync(this.resourceGroupName, this.accountName, this.streamingEndpointName, this.inner(), this.cautoStart)
            .map(innerToFluentMap(this));
    }

    @Override
    public Observable<StreamingEndpoint> updateResourceAsync() {
        StreamingEndpointsInner client = this.manager().inner().streamingEndpoints();
        return client.updateAsync(this.resourceGroupName, this.accountName, this.streamingEndpointName, this.inner())
            .map(innerToFluentMap(this));
    }

    @Override
    protected Observable<StreamingEndpointInner> getInnerAsync() {
        StreamingEndpointsInner client = this.manager().inner().streamingEndpoints();
        return client.getAsync(this.resourceGroupName, this.accountName, this.streamingEndpointName);
    }

    @Override
    public boolean isInCreateMode() {
        return this.inner().id() == null;
    }

    @Override
    public StreamingEndpointAccessControl accessControl() {
        return this.inner().accessControl();
    }

    @Override
    public String availabilitySetName() {
        return this.inner().availabilitySetName();
    }

    @Override
    public Boolean cdnEnabled() {
        return this.inner().cdnEnabled();
    }

    @Override
    public String cdnProfile() {
        return this.inner().cdnProfile();
    }

    @Override
    public String cdnProvider() {
        return this.inner().cdnProvider();
    }

    @Override
    public DateTime created() {
        return this.inner().created();
    }

    @Override
    public CrossSiteAccessPolicies crossSiteAccessPolicies() {
        return this.inner().crossSiteAccessPolicies();
    }

    @Override
    public List<String> customHostNames() {
        return this.inner().customHostNames();
    }

    @Override
    public String description() {
        return this.inner().description();
    }

    @Override
    public DateTime freeTrialEndTime() {
        return this.inner().freeTrialEndTime();
    }

    @Override
    public String hostName() {
        return this.inner().hostName();
    }

    @Override
    public String id() {
        return this.inner().id();
    }

    @Override
    public DateTime lastModified() {
        return this.inner().lastModified();
    }

    @Override
    public String location() {
        return this.inner().location();
    }

    @Override
    public Long maxCacheAge() {
        return this.inner().maxCacheAge();
    }

    @Override
    public String name() {
        return this.inner().name();
    }

    @Override
    public String provisioningState() {
        return this.inner().provisioningState();
    }

    @Override
    public StreamingEndpointResourceState resourceState() {
        return this.inner().resourceState();
    }

    @Override
    public int scaleUnits() {
        return this.inner().scaleUnits();
    }

    @Override
    public Map<String, String> tags() {
        return this.inner().getTags();
    }

    @Override
    public String type() {
        return this.inner().type();
    }

    @Override
    public StreamingEndpointImpl withExistingMediaservice(String resourceGroupName, String accountName) {
        this.resourceGroupName = resourceGroupName;
        this.accountName = accountName;
        return this;
    }

    @Override
    public StreamingEndpointImpl withAutoStart(Boolean autoStart) {
        this.cautoStart = autoStart;
        return this;
    }

    @Override
    public StreamingEndpointImpl withAccessControl(StreamingEndpointAccessControl accessControl) {
        this.inner().withAccessControl(accessControl);
        return this;
    }

    @Override
    public StreamingEndpointImpl withAvailabilitySetName(String availabilitySetName) {
        this.inner().withAvailabilitySetName(availabilitySetName);
        return this;
    }

    @Override
    public StreamingEndpointImpl withCdnEnabled(Boolean cdnEnabled) {
        this.inner().withCdnEnabled(cdnEnabled);
        return this;
    }

    @Override
    public StreamingEndpointImpl withCdnProfile(String cdnProfile) {
        this.inner().withCdnProfile(cdnProfile);
        return this;
    }

    @Override
    public StreamingEndpointImpl withCdnProvider(String cdnProvider) {
        this.inner().withCdnProvider(cdnProvider);
        return this;
    }

    @Override
    public StreamingEndpointImpl withCrossSiteAccessPolicies(CrossSiteAccessPolicies crossSiteAccessPolicies) {
        this.inner().withCrossSiteAccessPolicies(crossSiteAccessPolicies);
        return this;
    }

    @Override
    public StreamingEndpointImpl withCustomHostNames(List<String> customHostNames) {
        this.inner().withCustomHostNames(customHostNames);
        return this;
    }

    @Override
    public StreamingEndpointImpl withDescription(String description) {
        this.inner().withDescription(description);
        return this;
    }

    @Override
    public StreamingEndpointImpl withLocation(String location) {
        this.inner().withLocation(location);
        return this;
    }

    @Override
    public StreamingEndpointImpl withMaxCacheAge(Long maxCacheAge) {
        this.inner().withMaxCacheAge(maxCacheAge);
        return this;
    }

    @Override
    public StreamingEndpointImpl withScaleUnits(int scaleUnits) {
        this.inner().withScaleUnits(scaleUnits);
        return this;
    }

    @Override
    public StreamingEndpointImpl withTags(Map<String, String> tags) {
        this.inner().withTags(tags);
        return this;
    }

}


text:
#ifndef ___ARCH_ARM_SRC_COMMON_UP_ARCH_H
#define ___ARCH_ARM_SRC_COMMON_UP_ARCH_H

/****************************************************************************
 * Included Files
 ****************************************************************************/

#include <nuttx/config.h>
#ifndef __ASSEMBLY__
# include <stdint.h>
#endif

/****************************************************************************
 * Pre-processor Definitions
 ****************************************************************************/

/****************************************************************************
 * Inline Functions
 ****************************************************************************/

#ifndef __ASSEMBLY__

# define getreg8(a)           (*(volatile uint8_t *)(a))
# define putreg8(v,a)         (*(volatile uint8_t *)(a) = (v))
# define getreg32(a)          (*(volatile uint32_t *)(a))
# define putreg32(v,a)        (*(volatile uint32_t *)(a) = (v))

/* Some compiler options will convert short loads and stores into byte loads
 * and stores.  We don't want this to happen for IO reads and writes!
 */

/* # define getreg16(a)       (*(volatile uint16_t *)(a)) */
static inline uint16_t getreg16(unsigned int addr)
{
  uint16_t retval;
 __asm__ __volatile__("\tldrh %0, [%1]\n\t" : "=r"(retval) : "r"(addr));
  return retval;
}

/* define putreg16(v,a)       (*(volatile uint16_t *)(a) = (v)) */
static inline void putreg16(uint16_t val, unsigned int addr)
{
 __asm__ __volatile__("\tstrh %0, [%1]\n\t": : "r"(val), "r"(addr));
}

/****************************************************************************
 * Public Function Prototypes
 ****************************************************************************/

#undef EXTERN
#if defined(__cplusplus)
#define EXTERN extern "C"
extern "C"
{
#else
#define EXTERN extern
#endif

/* Atomic modification of registers */

void modifyreg8(unsigned int addr, uint8_t clearbits, uint8_t setbits);
void modifyreg16(unsigned int addr, uint16_t clearbits, uint16_t setbits);
void modifyreg32(unsigned int addr, uint32_t clearbits, uint32_t setbits);

#undef EXTERN
#if defined(__cplusplus)
}
#endif

#endif /* __ASSEMBLY__ */
#endif  /* ___ARCH_ARM_SRC_COMMON_UP_ARCH_H */


text:
import React from 'react';
import Label from 'ps-react/Label';

/** Optional label */
export default function ExampleOptional() {
  return <Label htmlFor="test" label="test" />
}


text:
package br.com.controlefinanceiro.serializer;

import java.io.IOException;

import org.bson.types.ObjectId;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;

public class NoObjectIdSerializer extends JsonSerializer<ObjectId> {
    @Override
    public void serialize(ObjectId value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException {
        jgen.writeString(value.toHexString());
    }
}


text:
"""
Author: AsherYang
Email:  1181830457@qq.com
Date:   2017/7/24
Desc:   get category 获取分类接口,返回网络数据

"""
import sys

sys.path.append('../')

from db.CategoryDao import CategoryDao
from db.AttributeDao import AttributeDao
from db.DbCategory import DbCategory
from db.DbAttribute import DbAttribute
from net.NetCategory import NetCategory
from net.NetDiscover import NetDiscover
from constant import CategoryShowType

class GetCategory:
    def __init__(self):
        self.cateDao = CategoryDao()
        self.attrDao = AttributeDao()

    """
    从数据库获取商品分类
    """
    def getCategoryListFromDb(self):
        print '--- getCategoryFromDb start ---'
        results = self.cateDao.queryAllCateFromDb()
        print results
        if results is None:
            return None
        categoryList = []
        for row in results:
            category = self.convertDbRow2Cate(row)
            if not category:
                continue
            categoryList.append(category)
        return categoryList

    """
    根据cate_code 从数据库中获取商品分类信息
    """
    def getCategoryFromDb(self, cate_code):
        result = self.cateDao.queryCateByCode(cateCode=cate_code)
        if not result:
            return None
        return self.convertDbRow2Cate(result)

    """
    保存单个商品分类进数据库
    """
    def saveCategoryToDb(self, category=None):
        print '--- saveCategoryToDb start ---'
        if category is None:
            print "category is None could not save to db."
            return False
        return self.cateDao.saveOrUpdateToDb(category)

    """
    更新单个商品分类信息
    """
    def updateCategoryToDb(self, category=None):
        if not category:
            return False
        return self.cateDao.updateToDb(cate=category)

    """
    获取数据库所有的分类, 包括二级分类
    """
    def doGetCategory(self):
        dbCateList = self.getCategoryListFromDb()
        if dbCateList:
            return self.convertCateDb2Net(dbCateList)
        else:
            return None

    """
    获取首页展示的分类列表,对应API:api/mall/discoverList
    """
    def getHomeDiscoverList(self, page_num=1, page_size=10):
        result = self.cateDao.queryCateListByShowType(CategoryShowType.TYPE_SHOW_HOME, page_num, page_size)
        if result is None:
            print 'there is no TYPE_SHOW_HOME category, please add it.'
            return None
        dbCateIds = []
        dbCateList = []
        for row in result:
            dbCate = self.convertDbRow2Cate(row)
            if not dbCate:
                continue
            dbCateList.append(dbCate)
            cate_id = dbCate.cate_id
            if cate_id not in dbCateIds:
                dbCateIds.append(cate_id)
        # query cate attributes
        attrResult = self.attrDao.queryCateAttrList(dbCateIds)
        if not attrResult:
            return None
        dbAttrList = []
        for row in attrResult:
            dbAttr = self.convertDbRow2Attr(row)
            if not dbAttr:
                continue
            dbAttrList.append(dbAttr)
        # category not have brand_name
        return self.convertHomeDiscover2Net(dbCateList, dbAttrList)

    """
    获取首页展示的分类总数量
    """
    def getHomeDiscoverCount(self):
        homeDiscoverCount = self.cateDao.queryCateCountByShowType(CategoryShowType.TYPE_SHOW_HOME)
        return homeDiscoverCount

    # =========================== 转换开始 ===================================== #

    """
    将数据库查询的结果,对应设置给dbCategory 实体bean,并将单个 cate 返回出去
    """
    def convertDbRow2Cate(self, dbCateRowResult):
        if not dbCateRowResult:
            return None
        category = DbCategory()
        dbSingleRow = dbCateRowResult[0]
        row_id = dbSingleRow['_id']
        cate_id = dbSingleRow['cate_id']
        cate_code = dbSingleRow['cate_code']
        parent_code = dbSingleRow['parent_code']
        cate_logo = dbSingleRow['cate_logo']
        cate_name = dbSingleRow['cate_name']
        cate_show_type = dbSingleRow['cate_show_type']
        category.cate_id = cate_id
        category.cate_code = cate_code
        category.parent_code = parent_code
        category.cate_logo = cate_logo
        category.cate_name = cate_name
        category.cate_show_type = cate_show_type
        return category

    """
    将数据库查询的结果,对应设置给DbAttributey 实体bean,并将单个 attr 返回出去
    """
    def convertDbRow2Attr(self, dbAttrRowResult):
        if not dbAttrRowResult:
            return None
        dbAttr = DbAttribute()
        row_id = dbAttrRowResult[0]
        cate_id = dbAttrRowResult[1]
        goods_id = dbAttrRowResult[2]
        attr_market_year = dbAttrRowResult[3]
        attr_size = dbAttrRowResult[4]
        attr_color = dbAttrRowResult[5]
        dbAttr.cate_id = cate_id
        dbAttr.goods_id = goods_id
        dbAttr.attr_market_year = attr_market_year
        dbAttr.attr_size = attr_size
        dbAttr.attr_color = attr_color
        return dbAttr

    """
    将商品分类数据库数据转换为网络数据,提供API数据
    """
    def convertCateDb2Net(self, dbCateList):
        if not dbCateList:
            return None
        categoryList = []
        for dbCate in dbCateList:
            netCate = NetCategory()
            netCate.id = dbCate.cate_id
            netCate.code = dbCate.cate_code
            netCate.parent_code = dbCate.parent_code
            netCate.name = dbCate.cate_name
            netCate.logo = dbCate.cate_logo
            categoryList.append(netCate)
        return categoryList

    """
    将商品分类数据库数据转换为用于首页展示的网络数据,提供API
    """
    def convertHomeDiscover2Net(self, dbCateList, dbAttrList):
        if not dbCateList or not dbAttrList:
            return None
        netDiscoverList = []
        for dbCate in dbCateList:
            netDiscover = NetDiscover()
            netDiscover.code = dbCate.cate_code
            netDiscover.logo = dbCate.cate_logo
            netDiscover.id = dbCate.cate_id
            for dbAttr in dbAttrList:
                if dbCate.cate_id == dbAttr.cate_id:
                    # 分类没有厂家名称
                    # netDiscover.brand_name = dbAttr.brand_name
                    netDiscover.attr_market_year = dbAttr.attr_market_year
                    break
            netDiscoverList.append(netDiscover)
        return netDiscoverList
    # =========================== 转换结束 ===================================== #

if __name__ == '__main__':
    getCate = GetCategory()
    getCate.doGetCategory()
    # categoryNetList = getCategoryFromNet()
    # saveCategoryToDb(categoryNetList)


text:
'use strict';

var gulp            = require( 'gulp' );
var connect         = require( 'gulp-connect' );
var mainBowerFiles  = require( 'main-bower-files' );
var inject          = require( 'gulp-inject' );
var angularFilesort = require( 'gulp-angular-filesort' );

var path   = require( '../../paths.js' );
var error  = require( '../../error-handler.js' );

gulp.task( 'inject', function( )
{

	var injectOptions =
	{
		relative: true,
		addRootSlash: false
	};

	var bowerInjectOptions =
	{
		relative: true,
		addRootSlash: false,
		starttag: '<!-- inject:bower:{{ext}} -->'
	};

	var target = gulp.src( path.to.destination + '/index.html' );

	var appJsSource    = gulp.src( [ path.to.destination + '/**/*.js', '!' + path.to.destination + '/bower/**/*.*' ] );
	var sortedAppJs    = appJsSource.pipe( angularFilesort(  ) );

	var bowerSource    = gulp.src( [ path.to.bower.scripts ], { read: false } );
	var bowerCssSource = gulp.src( [ path.to.bower.css ], { read: false } );

	var mainCssSource  = gulp.src( [ path.to.main.css.source ], { read: false } );

	return target
		.pipe( inject( bowerCssSource, bowerInjectOptions ) )
		.pipe( inject( mainCssSource, injectOptions ) )
		.pipe( inject( bowerSource, bowerInjectOptions ) )
		.pipe( inject( sortedAppJs, injectOptions ) )
		.on( 'error', error.handler )

		.pipe( gulp.dest( path.to.destination ) )
		.pipe( connect.reload(  ) );
} );


text:
import { HoverEvent } from '$lib/classes/Snippets/HoverEvent';
import { GroupSnippet } from '../classes/Snippets/SnippetTypes/GroupSnippet';
import { KeybindSnippet } from '../classes/Snippets/SnippetTypes/KeybindSnippet';
import { LinebreakSnippet } from '../classes/Snippets/SnippetTypes/LinebreakSnippet';
import { NBTSnippet, NBTType } from '../classes/Snippets/SnippetTypes/NBTSnippet';
import { PagebreakSnippet } from '../classes/Snippets/SnippetTypes/PagebreakSnippet';
import { ScoreboardObjectiveSnippet } from '../classes/Snippets/SnippetTypes/ScoreboardObjectiveSnippet';
import { SelectorSnippet } from '../classes/Snippets/SnippetTypes/SelectorSnippet';
import type { Snippet } from '../classes/Snippets/SnippetTypes/Snippet';
import { TextSnippet } from '../classes/Snippets/SnippetTypes/TextSnippet';
import { TranslateSnippet } from '../classes/Snippets/SnippetTypes/TranslateSnippet';
import { CommandType, FeatureType, isFeatureAvailable } from '../data/templates';
import type { Version } from './versions';
import { versionAtLeast } from './versions';

function compile_section(
	section_snippets: Snippet[],
	type: CommandType,
	version: Version
): Record<string, unknown>[] {
	const results: Record<string, unknown>[] = [];
	for (const snippet of section_snippets) {
		const pending = {};

		if (snippet instanceof TextSnippet) {
			pending['text'] = snippet.text;
		} else if (snippet instanceof SelectorSnippet) {
			pending['selector'] = snippet.selector;
		} else if (snippet instanceof ScoreboardObjectiveSnippet) {
			pending['score'] = {
				name: snippet.score_name,
				objective: snippet.score_objective
			};

			if (snippet.score_value !== null) {
				pending['score']['value'] = snippet.score_value;
			}
		} else if (snippet instanceof NBTSnippet) {
			if (!isFeatureAvailable(type, version, FeatureType.nbtComponent)) {
				continue;
			}

			if (
				snippet.type == NBTType.storage &&
				!isFeatureAvailable(type, version, FeatureType.nbtStorageComponent)
			) {
				continue;
			}

			pending['nbt'] = snippet.nbt;
			// this works because of how enums
			// work in TypeScript
			pending[NBTType[snippet.type]] = snippet.storage;
			if (snippet.interpret) {
				pending['interpret'] = snippet.interpret;
			}
		} else if (snippet instanceof KeybindSnippet) {
			pending['keybind'] = snippet.keybind;
		} else if (snippet instanceof TranslateSnippet) {
			pending['translate'] = snippet.translate;
			if (snippet.parameters.length > 0) {
				pending['with'] = compile_section(snippet.parameters, type, version);
			}
		} else if (snippet instanceof GroupSnippet) {
			pending['text'] = '';
			pending['extra'] = compile_section(snippet.children, type, version);
		}

		/* Style Transfer */
		if (snippet.bold) pending['bold'] = true;
		if (snippet.italic) pending['italic'] = true;
		if (snippet.underlined) pending['underlined'] = true;
		if (snippet.strikethrough) pending['strikethrough'] = true;
		if (snippet.obfuscated) pending['obfuscated'] = true;
		if (snippet.color != 'none') pending['color'] = snippet.color;

		if (snippet.font) {
			if (isFeatureAvailable(type, version, FeatureType.font)) {
				pending['font'] = snippet.font;
			} else {
				console.warn(`Skipping font attribute, since ${version} doesn't qualify.`);
			}
		}

		if (snippet.insertion.length > 0) {
			pending['insertion'] = snippet.insertion;
		}

		// If the clicking feature is available and
		// it is not a sign with more than one snippet
		// in this section, process the click event
		if (snippet.click_event_type != 'none') {
			if (
				isFeatureAvailable(type, version, FeatureType.clicking) &&
				!(type == CommandType.sign && section_snippets.length > 1)
			) {
				pending['clickEvent'] = {
					action: snippet.click_event_type,
					value: snippet.click_event_value
				};
			}
		}

		if (isFeatureAvailable(type, version, FeatureType.hovering)) {
			if (snippet.hover_event_type == 'show_text') {
				const recursive_result = compile_section(
					snippet.hover_event_children,
					CommandType.hovertext,
					version
				);
				const contents_key = versionAtLeast(version, '1.16') ? 'contents' : 'value'
				pending['hoverEvent'] = {
					action: snippet.hover_event_type,
					[contents_key]: recursive_result
				};
			} else if (snippet.hover_event_type != 'none') {
				if (versionAtLeast(version, '1.16')) {
					try {
						pending['hoverEvent'] = {
							action: snippet.hover_event_type,
							contents: JSON.parse(snippet.hover_event_value)
						};
					} catch (error) {
						pending['hoverEvent'] = {
							action: HoverEvent.show_text,
							contents: `Cannot parse as JSON:\n${snippet.hover_event_value}`
						};
					}
				} else {
					pending['hoverEvent'] = {
						action: snippet.hover_event_type,
						value: snippet.hover_event_value
					};
				}
			}
		}

		const keys = Object.keys(pending);
		if (keys.length === 1 && keys[0] === 'text') {
			results.push(pending['text']);
		} else {
			results.push(pending);
		}
	}
	return results;
}

export function compile_section_list(
	sections: Snippet[][],
	type: CommandType,
	version: Version
): string {
	// Depending on whether a sign click
	// event is used, sections may be single
	// tellraw snippets instead of normal arrays
	type BaseType = string | Record<string, unknown>;
	type FullType = BaseType | BaseType[];

	const results = Array<FullType>();

	for (const section_snippets of sections) {
		const section_results = ['', ...compile_section(section_snippets, type, version)];

		// If there are 2 elements
		// (the first element is always "")
		// then replace it all with that one blob
		if (section_results.length == 2) {
			results.push(section_results[1]);
		} else {
			results.push(section_results);
		}
	}

	if (type == CommandType.book) {
		return JSON.stringify(
			results.map((e) => {
				return JSON.stringify(e);
			})
		);
	} else if (type == CommandType.sign) {
		let ret = '';
		if (results.length >= 1) {
			const l1 = JSON.stringify(results[0]);
			ret = ret.concat(`Text1:${JSON.stringify(l1)}`);

			if (results.length >= 2) {
				const l2 = JSON.stringify(results[1]);
				ret = ret.concat(`,Text2:${JSON.stringify(l2)}`);

				if (results.length >= 3) {
					const l3 = JSON.stringify(results[2]);
					ret = ret.concat(`,Text3:${JSON.stringify(l3)}`);

					if (results.length >= 4) {
						const l4 = JSON.stringify(results[3]);
						ret = ret.concat(`,Text4:${JSON.stringify(l4)}`);
					}
				}
			}
		}

		return ret;
	} else if (results.length > 0) {
		return JSON.stringify(results[0]);
	} else {
		console.error('No elements case identified to compile this');
		return '';
	}
}

/**
 * Compile a set of snippets to a final string
 * @param snippets Snippets to compile
 * @param command Command to inject compiled text into
 * @param type Command type (books, tellraw, signs, etc.)
 * @param version Minecraft version compiling for
 * @returns Compiled string to run in Minecraft
 */
export function compile(
	snippets: Array<Snippet>,
	command: string,
	type: CommandType,
	version: Version,
	litSign: boolean
): string {
	const section_list = Array<Array<Snippet>>();
	const unprocessed = [...snippets];

	if (isFeatureAvailable(type, version, FeatureType.pages) || type == CommandType.sign) {
		while (unprocessed.length > 0) {
			const applyLinebreaks = type == CommandType.sign;

			const index = unprocessed.findIndex((s) => {
				return s instanceof PagebreakSnippet || (applyLinebreaks && s instanceof LinebreakSnippet);
			});

			if (index == -1) {
				section_list.push(unprocessed.splice(0, unprocessed.length));
			} else {
				section_list.push(unprocessed.splice(0, index));
			}
			unprocessed.splice(0, 1);
		}
	} else {
		section_list.push(
			unprocessed.filter((e) => {
				return !(e instanceof PagebreakSnippet);
			})
		);
	}

	let results = compile_section_list(section_list, type, version);
	if (litSign && isFeatureAvailable(type, version, FeatureType.litSign)) {
		results = `${results},GlowingText:1b`;
	}

	if (!command) {
		console.error("Command isn't available", command);
		return '';
	}

	if (command.indexOf('%s') === -1) {
		// error
		console.error('No %s to replace');
		return results;
	} else {
		return command.replace('%s', results);
	}
}