text:
package com.amazonaws.codegen;

import com.amazonaws.codegen.model.config.customization.CustomizationConfig;
import com.amazonaws.codegen.model.config.customization.ShapeModifier;
import com.amazonaws.codegen.model.config.customization.ShapeModifier_ModifyModel;
import com.amazonaws.codegen.model.config.customization.ShapeSubstitution;
import com.amazonaws.codegen.model.intermediate.Example;
import com.amazonaws.codegen.model.intermediate.ServiceExamples;
import com.amazonaws.codegen.model.service.Input;
import com.amazonaws.codegen.model.service.Member;
import com.amazonaws.codegen.model.service.Operation;
import com.amazonaws.codegen.model.service.Output;
import com.amazonaws.codegen.model.service.ServiceModel;
import com.amazonaws.codegen.model.service.Shape;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * Transforms the examples so that they are in line with any shape related
 * customizations for the given service.
 */
public class ExamplesCustomizer {
    private static final ObjectMapper MAPPER = new ObjectMapper();
    private final ServiceModel serviceModel;
    private final CustomizationConfig customizationConfig;

    public ExamplesCustomizer(ServiceModel serviceModel, CustomizationConfig customizationConfig) {
        this.serviceModel = serviceModel;
        this.customizationConfig = customizationConfig;
    }

    /**
     * Apply the configured {@link CustomizationConfig} to the given service
     * examples.
     *
     * @param serviceExamples The service examples.
     *
     * @return The customized service examples.
     */
    public ServiceExamples applyCustomizationsToExamples(ServiceExamples serviceExamples) {
        if (customizationConfig == null) return serviceExamples;

        serviceExamples.getOperationExamples().entrySet()
                .forEach(e -> {
                    String operationName = e.getKey();
                    Operation operation = serviceModel.getOperation(operationName);
                    e.getValue().forEach(example -> applyCustomizationsToExample(example, operation));
                });
        return serviceExamples;
    }

    private Example applyCustomizationsToExample(Example example, Operation operation) {
        if (example == null) return null;

        System.out.println(String.format("Customizing operation example : %s", example.getId()));

        Input input = operation.getInput();
        if (input != null) {
            String inputShapeName = input.getShape();
            Shape inputShape = serviceModel.getShape(inputShapeName);
            JsonNode inputValue = example.getInput();

            example.setInput(applyCustomizationsToShapeJson(inputShapeName, inputShape, inputValue));
        }

        Output output = operation.getOutput();
        if (output != null) {
            String outputShapeName = output.getShape();
            Shape outputShape = serviceModel.getShape(outputShapeName);
            JsonNode outputValue = example.getOutput();

            example.setOutput(applyCustomizationsToShapeJson(outputShapeName, outputShape, outputValue));
        }

        return example;
    }

    /**
     * Recursively apply any declared customizations to this JSON value
     * according to the given shape and the customizations declared for the
     * shape.
     *
     * @param shapeName The name of the shape.
     * @param shape The shape of the JSON value.
     * @param valueNode The JSON value to customize.
     *
     * @return The customized JSON value.
     */
    private JsonNode applyCustomizationsToShapeJson(String shapeName, Shape shape, JsonNode valueNode) {
        // Don't bother going any further if we're not dealing with an array or
        // object JSON node; there's not much we can do to "massage" this value
        if (valueNode == null || !valueNode.isContainerNode()) {
            return valueNode;
        }

        // Apply modifications first
        valueNode = applyModificationsToShapeJson(shapeName, valueNode);

        ShapeSubstitution shapeSub = null;
        if (customizationConfig.getShapeSubstitutions() != null) {
            shapeSub = customizationConfig.getShapeSubstitutions().get(shapeName);
        }

        if (shapeSub != null) {
            String substituteShapeName = shapeSub.getEmitAsShape();
            Shape substituteShape = serviceModel.getShape(substituteShapeName);
            JsonNode substituteValue = valueNode;
            if (shapeSub.getEmitFromMember() != null) {
                substituteValue = valueNode.get(shapeSub.getEmitFromMember());
                if (substituteValue == null) {
                    System.err.println(String.format("Warning: Substituting shape '%s' for its"
                                    + " member '%s' as shape '%s' produced null value. Original"
                                    + " value: %s", shapeName, shapeSub.getEmitFromMember(),
                            substituteShapeName, valueNode.toString()));
                }
            }
            System.out.println(String.format("Substituting shape %s with %s. %s -> %s", shapeName,
                    substituteShapeName, valueNode.toString(), Objects.toString(substituteValue)));

            return applyCustomizationsToShapeJson(substituteShapeName, substituteShape, substituteValue);
        } else {
            switch (shape.getType()) {
                // Apply customizations to each member
                case "map":
                case "structure": {
                    if (shape.getMembers() == null) {
                        return valueNode;
                    }

                    ObjectNode obj = MAPPER.createObjectNode();

                    for (Map.Entry<String, Member> e : shape.getMembers().entrySet()) {
                        Member member = e.getValue();
                        String memberName = e.getKey();
                        String memberShapeName = member.getShape();
                        Shape memberShape = serviceModel.getShape(memberShapeName);
                        JsonNode memberValue = valueNode.get(memberName);

                        // Only set if it's not null, otherwise the generated
                        // sample code could potentially have lots of
                        // unnecessary 'withProperty(null)' calls.
                        if (memberValue != null) {
                            obj.set(memberName, applyCustomizationsToShapeJson(memberShapeName,
                                                    memberShape, memberValue));
                        }
                    }

                    return obj;
                }

                // Apply customizations to each element
                case "list": {
                    ArrayNode list = MAPPER.createArrayNode();

                    String memberShapeName = shape.getListMember().getShape();
                    Shape memberShape = serviceModel.getShape(memberShapeName);

                    for (JsonNode e : valueNode) {
                        // apply any customizations to the list elements
                        list.add(applyCustomizationsToShapeJson(memberShapeName, memberShape, e));
                    }

                    return list;
                }
                default:
                    throw new RuntimeException("Unknown shape type: " + shape.getType());
            }
        }
    }

    private JsonNode applyModificationsToShapeJson(String shapeName, JsonNode valueNode) {
        if (customizationConfig.getShapeModifiers() == null) return valueNode;

        ShapeModifier allShapeMode = customizationConfig.getShapeModifiers().get("*");
        ShapeModifier shapeMod = customizationConfig.getShapeModifiers().get(shapeName);

        valueNode = applyShapeModifier(valueNode, allShapeMode);
        valueNode = applyShapeModifier(valueNode, shapeMod);

        return valueNode;
    }

    /**
     * Apply any shape modifiers to the JSON value. This only takes care of
     * 'exclude' and 'emitPropertyName'.
     *
     * @param node The JSON node.
     * @param modifier The shape modifier.
     * @return The modified node.
     */
    private JsonNode applyShapeModifier(JsonNode node, ShapeModifier modifier) {
        if (node == null || modifier == null) {
            return node;
        }

        if (modifier.getExclude() == null && modifier.getModify() == null) {
            return node;
        }

        if (!node.isObject()) return node;

        final ObjectNode obj = (ObjectNode) node;

        ObjectNode modified = MAPPER.createObjectNode();
        // Filter any excluded members
        final List<String> excludes = modifier.getExclude() != null ? modifier.getExclude() : Collections.emptyList();
        obj.fieldNames().forEachRemaining(m -> {
            if (!excludes.contains(m)) {
                modified.set(m, obj.get(m));
            }
        });
        // Apply property renames
        final List<Map<String, ShapeModifier_ModifyModel>> modify = modifier.getModify() != null ? modifier.getModify() : Collections.emptyList();
        modify.forEach(memberMods ->
            memberMods.entrySet().forEach(memberMod -> {
                String memberName = memberMod.getKey();
                ShapeModifier_ModifyModel modelModify = memberMod.getValue();
                if (modelModify.getEmitPropertyName() != null) {
                    String newName = modelModify.getEmitPropertyName();
                    modified.set(newName, modified.get(memberName));
                    modified.remove(memberName);
                    memberName = newName;
                }
            })
        );

        return modified;
    }
}


text:
import React, { Component } from 'react'
import { opComponent } from '../../operate'

import SelfTable from '../../part/table'

export default class Account extends Component {
    render(){
        return (

账户管理

                <SelfTable columns={this.props.oriData.th} tableData={this.props.oriData.tableData} total={this.props.oriData.count} />

        )
    }
}

var basicConfig = {
    api: {
        list: {
            type: 'get',
            url: '/account/index'
        }
    },
    th: [{
        title: 'saction',
        dataIndex: 'saction'
    },{
        title: 'optName',
        dataIndex: 'optName'
    },{
        title: 'beforeModify',
        dataIndex: 'beforeModify'
    },{
        title: 'afterModify',
        dataIndex: 'afterModify'
    },{
        title: 'actionType',
        dataIndex: 'actionType'
    },{
        title: 'storeName',
        dataIndex: 'storeName'
    }]
}
export const OpAccount = opComponent(Account, basicConfig)

redpajama_set_name: RedPajamaGithub


text:
using System.Collections.Generic;
using System.Linq;

using Composite.C1Console.Security;
using Composite.Plugins.Elements.ElementProviders.BaseFunctionProviderElementProvider;

namespace CompositeC1Contrib.Security
{
    public class StandardFunctionSecurityAncestorProvider : ISecurityAncestorProvider
    {
        public IEnumerable<EntityToken> GetParents(EntityToken entityToken)
        {
            string fullname = entityToken.Id;

            if (fullname.Contains('.'))
            {
                fullname = fullname.Remove(fullname.LastIndexOf('.'));
            }

            string id = BaseFunctionProviderElementProvider.CreateId(fullname, "AllFunctionsElementProvider");

            yield return new BaseFunctionFolderElementEntityToken(id);
        }
    }
}


text:
from tornado import web
from tornado.wsgi import WSGIContainer
from notebook.base.handlers import IPythonHandler
from notebook.utils import url_path_join as ujoin
from notebook.base.handlers import path_regex

notebook_dir = None

def load_jupyter_server_extension(nb_app):

    global notebook_dir
    # notebook_dir should be root_dir of contents_manager
    notebook_dir = nb_app.contents_manager.root_dir

    web_app = nb_app.web_app
    base_url = web_app.settings['base_url']

    try:
        from .tensorboard_manager import manager
    except ImportError:
        nb_app.log.info("import tensorboard error, check tensorflow install")
        handlers = [
            (ujoin(
                base_url, r"/tensorboard.*"),
                TensorboardErrorHandler),
        ]
    else:
        web_app.settings["tensorboard_manager"] = manager
        from . import api_handlers

        handlers = [
            (ujoin(
                base_url, r"/tensorboard/(?P<name>\w+)%s" % path_regex),
                TensorboardHandler),
            (ujoin(
                base_url, r"/api/tensorboard"),
                api_handlers.TbRootHandler),
            (ujoin(
                base_url, r"/api/tensorboard/(?P<name>\w+)"),
                api_handlers.TbInstanceHandler),
        ]

    web_app.add_handlers('.*$', handlers)
    nb_app.log.info("jupyter_tensorboard extension loaded.")

class TensorboardHandler(IPythonHandler):

    @web.authenticated
    def get(self, name, path):

        if path == "":
            uri = self.request.path + "/"
            if self.request.query:
                uri += "?" + self.request.query
            self.redirect(uri, permanent=True)
            return

        self.request.path = (
            path if self.request.query
            else "%s?%s" % (path, self.request.query))

        manager = self.settings["tensorboard_manager"]
        if name in manager:
            tb_app = manager[name].tb_app
            WSGIContainer(tb_app)(self.request)
        else:
            raise web.HTTPError(404)

class TensorboardErrorHandler(IPythonHandler):
    pass


text:
from django.conf.urls import url
from django.views.generic import TemplateView

from . import views

urlpatterns = [
    url(r"^list_signup/$", views.list_signup, name="waitinglist_list_signup"),
    url(r"^ajax_list_signup/$", views.ajax_list_signup, name="waitinglist_ajax_list_signup"),
    url(r"^survey/thanks/$", TemplateView.as_view(template_name="waitinglist/thanks.html"), name="waitinglist_thanks"),
    url(r"^survey/(?P<code>.*)/$", views.survey, name="waitinglist_survey"),
    url(r"^success/$", TemplateView.as_view(template_name="waitinglist/success.html"), name="waitinglist_success"),
    url(r"^cohorts/$", views.cohort_list, name="waitinglist_cohort_list"),
    url(r"^cohorts/create/$", views.cohort_create, name="waitinglist_cohort_create"),
    url(r"^cohorts/cohort/(\d+)/$", views.cohort_detail, name="waitinglist_cohort_detail"),
    url(r"^cohorts/cohort/(\d+)/add_member/$", views.cohort_member_add, name="waitinglist_cohort_member_add"),
    url(r"^cohorts/cohort/(\d+)/send_invitations/$", views.cohort_send_invitations, name="waitinglist_cohort_send_invitations"),
]


text:
module Softlayer
  class Network
    class Component
      module Network
        module Vlan
          class Trunk < Softlayer::Entity
            attr_accessor :network_component_id
            attr_accessor :network_vlan_id
            attr_accessor :network_component
            attr_accessor :network_vlan

            class Representer < Softlayer::Entity::Representer
              include Representable::Hash
              include Representable::Coercion
              property :network_component_id, type: Integer
              property :network_vlan_id, type: Integer
            end
          end
        end
      end
    end
  end
end


text:
const component = msg => {
  console.log(msg);
};

export default component;


text:
package org.apache.flink.table.factories;

import org.apache.flink.annotation.PublicEvolving;
import org.apache.flink.table.connector.source.DynamicTableSource;
import org.apache.flink.table.sources.BatchTableSource;
import org.apache.flink.table.sources.TableSource;

import java.util.Map;

/**
 * A factory to create configured table source instances in a batch environment based on
 * string-based properties. See also {@link TableSourceFactory} for more information.
 *
 * @param <T> type of records that the factory produces
 *
 * @deprecated This interface has been replaced by {@link DynamicTableSourceFactory}. The new interface
 *             creates instances of {@link DynamicTableSource} and only works with the Blink planner.
 *             See FLIP-95 for more information.
 */
@Deprecated
@PublicEvolving
public interface BatchTableSourceFactory<T> extends TableSourceFactory<T> {

	/**
	 * Creates and configures a {@link BatchTableSource} using the given properties.
	 *
	 * @param properties normalized properties describing a batch table source.
	 * @return the configured batch table source.
	 */
	BatchTableSource<T> createBatchTableSource(Map<String, String> properties);

	/**
	 * Only create batch table source.
	 */
	@Override
	default TableSource<T> createTableSource(Map<String, String> properties) {
		return createBatchTableSource(properties);
	}
}


text:
class TumblrService < Service
  MAX_CHARACTERS = 1000

  def provider
    "tumblr"
  end

  def consumer_key
    AppConfig.services.tumblr.key
  end

  def consumer_secret
    AppConfig.services.tumblr.secret
  end

  def post(post, url='')
    body = build_tumblr_post(post, url)
    user_info = JSON.parse(client.get("/v2/user/info").body)
    blogs = user_info["response"]["user"]["blogs"].map { |blog| URI.parse(blog['url']) }
    tumblr_ids = {}
    blogs.each do |blog|
      resp = client.post("/v2/blog/#{blog.host}/post", body)
      if resp.code == "201"
        tumblr_ids[blog.host.to_s] = JSON.parse(resp.body)["response"]["id"]
      end
    post.tumblr_ids = tumblr_ids.to_json
    post.save
    end
  end

  def build_tumblr_post(post, url)
    { :type => 'text', :format => "markdown", :body => tumblr_template(post, url)  }
  end

  def tumblr_template(post, url)
    html = ''
    post.photos.each do |photo|
      html << "![photo](#{photo.url(:scaled_full)})\n\n"
    end
    html << post.message.html(mentioned_people: [])
    html << "\n\n[original post](#{url})"
  end

  def delete_post(post)
    if post.present? && post.tumblr_ids.present?
      Rails.logger.debug("event=delete_from_service type=tumblr sender_id=#{self.user_id}")
      tumblr_posts = JSON.parse(post.tumblr_ids)
      tumblr_posts.each do |blog_name,post_id|
        delete_from_tumblr(blog_name, post_id)
      end
    end
  end

  def delete_from_tumblr(blog_name, service_post_id)
    client.post("/v2/blog/#{blog_name}/post/delete", "id" => service_post_id)
  end

  private
  def client
    @consumer ||= OAuth::Consumer.new(consumer_key, consumer_secret, :site => 'http://api.tumblr.com')
    @client ||= OAuth::AccessToken.new(@consumer, self.access_token, self.access_secret)
  end
end


text:
//
//
// Copyright 2020 gRPC authors.
//
// 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.
//
//

#include <grpc/support/port_platform.h>

#include "src/core/ext/xds/xds_certificate_provider.h"

#include <utility>

#include "absl/functional/bind_front.h"
#include "absl/memory/memory.h"
#include "absl/types/optional.h"

#include <grpc/support/log.h>

#include "src/core/lib/channel/channel_args.h"
#include "src/core/lib/iomgr/error.h"
#include "src/core/lib/security/security_connector/ssl_utils.h"

namespace grpc_core {

namespace {

class RootCertificatesWatcher
    : public grpc_tls_certificate_distributor::TlsCertificatesWatcherInterface {
 public:
  // Takes a ref to \a parent instead of a raw pointer since the watcher is
  // owned by the root certificate distributor and not by \a parent. Note that
  // presently, the watcher is immediately deleted when
  // CancelTlsCertificatesWatch() is called, but that can potentially change in
  // the future.
  RootCertificatesWatcher(
      RefCountedPtr<grpc_tls_certificate_distributor> parent,
      std::string cert_name)
      : parent_(std::move(parent)), cert_name_(std::move(cert_name)) {}

  void OnCertificatesChanged(absl::optional<absl::string_view> root_certs,
                             absl::optional<PemKeyCertPairList>
                             /* key_cert_pairs */) override {
    if (root_certs.has_value()) {
      parent_->SetKeyMaterials(cert_name_, std::string(root_certs.value()),
                               absl::nullopt);
    }
  }

  void OnError(grpc_error_handle root_cert_error,
               grpc_error_handle identity_cert_error) override {
    if (!GRPC_ERROR_IS_NONE(root_cert_error)) {
      parent_->SetErrorForCert(cert_name_, root_cert_error /* pass the ref */,
                               absl::nullopt);
    }
    GRPC_ERROR_UNREF(identity_cert_error);
  }

 private:
  RefCountedPtr<grpc_tls_certificate_distributor> parent_;
  std::string cert_name_;
};

class IdentityCertificatesWatcher
    : public grpc_tls_certificate_distributor::TlsCertificatesWatcherInterface {
 public:
  // Takes a ref to \a parent instead of a raw pointer since the watcher is
  // owned by the root certificate distributor and not by \a parent. Note that
  // presently, the watcher is immediately deleted when
  // CancelTlsCertificatesWatch() is called, but that can potentially change in
  // the future.
  IdentityCertificatesWatcher(
      RefCountedPtr<grpc_tls_certificate_distributor> parent,
      std::string cert_name)
      : parent_(std::move(parent)), cert_name_(std::move(cert_name)) {}

  void OnCertificatesChanged(
      absl::optional<absl::string_view> /* root_certs */,
      absl::optional<PemKeyCertPairList> key_cert_pairs) override {
    if (key_cert_pairs.has_value()) {
      parent_->SetKeyMaterials(cert_name_, absl::nullopt, key_cert_pairs);
    }
  }

  void OnError(grpc_error_handle root_cert_error,
               grpc_error_handle identity_cert_error) override {
    if (!GRPC_ERROR_IS_NONE(identity_cert_error)) {
      parent_->SetErrorForCert(cert_name_, absl::nullopt,
                               identity_cert_error /* pass the ref */);
    }
    GRPC_ERROR_UNREF(root_cert_error);
  }

 private:
  RefCountedPtr<grpc_tls_certificate_distributor> parent_;
  std::string cert_name_;
};

}  // namespace

//
// XdsCertificateProvider::ClusterCertificateState
//

XdsCertificateProvider::ClusterCertificateState::~ClusterCertificateState() {
  if (root_cert_watcher_ != nullptr) {
    root_cert_distributor_->CancelTlsCertificatesWatch(root_cert_watcher_);
  }
  if (identity_cert_watcher_ != nullptr) {
    identity_cert_distributor_->CancelTlsCertificatesWatch(
        identity_cert_watcher_);
  }
}

bool XdsCertificateProvider::ClusterCertificateState::IsSafeToRemove() const {
  return !watching_root_certs_ && !watching_identity_certs_ &&
         root_cert_distributor_ == nullptr &&
         identity_cert_distributor_ == nullptr;
}

void XdsCertificateProvider::ClusterCertificateState::
    UpdateRootCertNameAndDistributor(
        const std::string& cert_name, absl::string_view root_cert_name,
        RefCountedPtr<grpc_tls_certificate_distributor> root_cert_distributor) {
  if (root_cert_name_ == root_cert_name &&
      root_cert_distributor_ == root_cert_distributor) {
    return;
  }
  root_cert_name_ = std::string(root_cert_name);
  if (watching_root_certs_) {
    // The root certificates are being watched. Swap out the watcher.
    if (root_cert_distributor_ != nullptr) {
      root_cert_distributor_->CancelTlsCertificatesWatch(root_cert_watcher_);
    }
    if (root_cert_distributor != nullptr) {
      UpdateRootCertWatcher(cert_name, root_cert_distributor.get());
    } else {
      root_cert_watcher_ = nullptr;
      xds_certificate_provider_->distributor_->SetErrorForCert(
          "",
          GRPC_ERROR_CREATE_FROM_STATIC_STRING(
              "No certificate provider available for root certificates"),
          absl::nullopt);
    }
  }
  // Swap out the root certificate distributor
  root_cert_distributor_ = std::move(root_cert_distributor);
}

void XdsCertificateProvider::ClusterCertificateState::
    UpdateIdentityCertNameAndDistributor(
        const std::string& cert_name, absl::string_view identity_cert_name,
        RefCountedPtr<grpc_tls_certificate_distributor>
            identity_cert_distributor) {
  if (identity_cert_name_ == identity_cert_name &&
      identity_cert_distributor_ == identity_cert_distributor) {
    return;
  }
  identity_cert_name_ = std::string(identity_cert_name);
  if (watching_identity_certs_) {
    // The identity certificates are being watched. Swap out the watcher.
    if (identity_cert_distributor_ != nullptr) {
      identity_cert_distributor_->CancelTlsCertificatesWatch(
          identity_cert_watcher_);
    }
    if (identity_cert_distributor != nullptr) {
      UpdateIdentityCertWatcher(cert_name, identity_cert_distributor.get());
    } else {
      identity_cert_watcher_ = nullptr;
      xds_certificate_provider_->distributor_->SetErrorForCert(
          "", absl::nullopt,
          GRPC_ERROR_CREATE_FROM_STATIC_STRING(
              "No certificate provider available for identity certificates"));
    }
  }
  // Swap out the identity certificate distributor
  identity_cert_distributor_ = std::move(identity_cert_distributor);
}

void XdsCertificateProvider::ClusterCertificateState::UpdateRootCertWatcher(
    const std::string& cert_name,
    grpc_tls_certificate_distributor* root_cert_distributor) {
  auto watcher = absl::make_unique<RootCertificatesWatcher>(
      xds_certificate_provider_->distributor_, cert_name);
  root_cert_watcher_ = watcher.get();
  root_cert_distributor->WatchTlsCertificates(std::move(watcher),
                                              root_cert_name_, absl::nullopt);
}

void XdsCertificateProvider::ClusterCertificateState::UpdateIdentityCertWatcher(
    const std::string& cert_name,
    grpc_tls_certificate_distributor* identity_cert_distributor) {
  auto watcher = absl::make_unique<IdentityCertificatesWatcher>(
      xds_certificate_provider_->distributor_, cert_name);
  identity_cert_watcher_ = watcher.get();
  identity_cert_distributor->WatchTlsCertificates(
      std::move(watcher), absl::nullopt, identity_cert_name_);
}

void XdsCertificateProvider::ClusterCertificateState::WatchStatusCallback(
    const std::string& cert_name, bool root_being_watched,
    bool identity_being_watched) {
  // We aren't specially handling the case where root_cert_distributor is same
  // as identity_cert_distributor. Always using two separate watchers
  // irrespective of the fact results in a straightforward design, and using a
  // single watcher does not seem to provide any benefit other than cutting down
  // on the number of callbacks.
  if (root_being_watched && !watching_root_certs_) {
    // We need to start watching root certs.
    watching_root_certs_ = true;
    if (root_cert_distributor_ == nullptr) {
      xds_certificate_provider_->distributor_->SetErrorForCert(
          cert_name,
          GRPC_ERROR_CREATE_FROM_STATIC_STRING(
              "No certificate provider available for root certificates"),
          absl::nullopt);
    } else {
      UpdateRootCertWatcher(cert_name, root_cert_distributor_.get());
    }
  } else if (!root_being_watched && watching_root_certs_) {
    // We need to cancel root certs watch.
    watching_root_certs_ = false;
    if (root_cert_distributor_ != nullptr) {
      root_cert_distributor_->CancelTlsCertificatesWatch(root_cert_watcher_);
      root_cert_watcher_ = nullptr;
    }
    GPR_ASSERT(root_cert_watcher_ == nullptr);
  }
  if (identity_being_watched && !watching_identity_certs_) {
    watching_identity_certs_ = true;
    if (identity_cert_distributor_ == nullptr) {
      xds_certificate_provider_->distributor_->SetErrorForCert(
          cert_name, absl::nullopt,
          GRPC_ERROR_CREATE_FROM_STATIC_STRING(
              "No certificate provider available for identity certificates"));
    } else {
      UpdateIdentityCertWatcher(cert_name, identity_cert_distributor_.get());
    }
  } else if (!identity_being_watched && watching_identity_certs_) {
    watching_identity_certs_ = false;
    if (identity_cert_distributor_ != nullptr) {
      identity_cert_distributor_->CancelTlsCertificatesWatch(
          identity_cert_watcher_);
      identity_cert_watcher_ = nullptr;
    }
    GPR_ASSERT(identity_cert_watcher_ == nullptr);
  }
}

//
// XdsCertificateProvider
//

XdsCertificateProvider::XdsCertificateProvider()
    : distributor_(MakeRefCounted<grpc_tls_certificate_distributor>()) {
  distributor_->SetWatchStatusCallback(
      absl::bind_front(&XdsCertificateProvider::WatchStatusCallback, this));
}

XdsCertificateProvider::~XdsCertificateProvider() {
  distributor_->SetWatchStatusCallback(nullptr);
}

UniqueTypeName XdsCertificateProvider::type() const {
  static UniqueTypeName::Factory kFactory("Xds");
  return kFactory.Create();
}

bool XdsCertificateProvider::ProvidesRootCerts(const std::string& cert_name) {
  MutexLock lock(&mu_);
  auto it = certificate_state_map_.find(cert_name);
  if (it == certificate_state_map_.end()) return false;
  return it->second->ProvidesRootCerts();
}

void XdsCertificateProvider::UpdateRootCertNameAndDistributor(
    const std::string& cert_name, absl::string_view root_cert_name,
    RefCountedPtr<grpc_tls_certificate_distributor> root_cert_distributor) {
  MutexLock lock(&mu_);
  auto it = certificate_state_map_.find(cert_name);
  if (it == certificate_state_map_.end()) {
    it = certificate_state_map_
             .emplace(cert_name,
                      absl::make_unique<ClusterCertificateState>(this))
             .first;
  }
  it->second->UpdateRootCertNameAndDistributor(cert_name, root_cert_name,
                                               root_cert_distributor);
  // Delete unused entries.
  if (it->second->IsSafeToRemove()) certificate_state_map_.erase(it);
}

bool XdsCertificateProvider::ProvidesIdentityCerts(
    const std::string& cert_name) {
  MutexLock lock(&mu_);
  auto it = certificate_state_map_.find(cert_name);
  if (it == certificate_state_map_.end()) return false;
  return it->second->ProvidesIdentityCerts();
}

void XdsCertificateProvider::UpdateIdentityCertNameAndDistributor(
    const std::string& cert_name, absl::string_view identity_cert_name,
    RefCountedPtr<grpc_tls_certificate_distributor> identity_cert_distributor) {
  MutexLock lock(&mu_);
  auto it = certificate_state_map_.find(cert_name);
  if (it == certificate_state_map_.end()) {
    it = certificate_state_map_
             .emplace(cert_name,
                      absl::make_unique<ClusterCertificateState>(this))
             .first;
  }
  it->second->UpdateIdentityCertNameAndDistributor(
      cert_name, identity_cert_name, identity_cert_distributor);
  // Delete unused entries.
  if (it->second->IsSafeToRemove()) certificate_state_map_.erase(it);
}

bool XdsCertificateProvider::GetRequireClientCertificate(
    const std::string& cert_name) {
  MutexLock lock(&mu_);
  auto it = certificate_state_map_.find(cert_name);
  if (it == certificate_state_map_.end()) return false;
  return it->second->require_client_certificate();
}

void XdsCertificateProvider::UpdateRequireClientCertificate(
    const std::string& cert_name, bool require_client_certificate) {
  MutexLock lock(&mu_);
  auto it = certificate_state_map_.find(cert_name);
  if (it == certificate_state_map_.end()) return;
  it->second->set_require_client_certificate(require_client_certificate);
}

std::vector<StringMatcher> XdsCertificateProvider::GetSanMatchers(
    const std::string& cluster) {
  MutexLock lock(&san_matchers_mu_);
  auto it = san_matcher_map_.find(cluster);
  if (it == san_matcher_map_.end()) return {};
  return it->second;
}

void XdsCertificateProvider::UpdateSubjectAlternativeNameMatchers(
    const std::string& cluster, std::vector<StringMatcher> matchers) {
  MutexLock lock(&san_matchers_mu_);
  if (matchers.empty()) {
    san_matcher_map_.erase(cluster);
  } else {
    san_matcher_map_[cluster] = std::move(matchers);
  }
}

void XdsCertificateProvider::WatchStatusCallback(std::string cert_name,
                                                 bool root_being_watched,
                                                 bool identity_being_watched) {
  MutexLock lock(&mu_);
  auto it = certificate_state_map_.find(cert_name);
  if (it == certificate_state_map_.end()) {
    it = certificate_state_map_
             .emplace(cert_name,
                      absl::make_unique<ClusterCertificateState>(this))
             .first;
  }
  it->second->WatchStatusCallback(cert_name, root_being_watched,
                                  identity_being_watched);
  // Delete unused entries.
  if (it->second->IsSafeToRemove()) certificate_state_map_.erase(it);
}

namespace {

void* XdsCertificateProviderArgCopy(void* p) {
  XdsCertificateProvider* xds_certificate_provider =
      static_cast<XdsCertificateProvider*>(p);
  return xds_certificate_provider->Ref().release();
}

void XdsCertificateProviderArgDestroy(void* p) {
  XdsCertificateProvider* xds_certificate_provider =
      static_cast<XdsCertificateProvider*>(p);
  xds_certificate_provider->Unref();
}

int XdsCertificateProviderArgCmp(void* p, void* q) {
  return QsortCompare(p, q);
}

const grpc_arg_pointer_vtable kChannelArgVtable = {
    XdsCertificateProviderArgCopy, XdsCertificateProviderArgDestroy,
    XdsCertificateProviderArgCmp};

}  // namespace

grpc_arg XdsCertificateProvider::MakeChannelArg() const {
  return grpc_channel_arg_pointer_create(
      const_cast<char*>(GRPC_ARG_XDS_CERTIFICATE_PROVIDER),
      const_cast<XdsCertificateProvider*>(this), &kChannelArgVtable);
}

RefCountedPtr<XdsCertificateProvider>
XdsCertificateProvider::GetFromChannelArgs(const grpc_channel_args* args) {
  XdsCertificateProvider* xds_certificate_provider =
      grpc_channel_args_find_pointer<XdsCertificateProvider>(
          args, GRPC_ARG_XDS_CERTIFICATE_PROVIDER);
  return xds_certificate_provider != nullptr ? xds_certificate_provider->Ref()
                                             : nullptr;
}

}  // namespace grpc_core


text:
package helpers

import (
	"encoding/json"
	"errors"
	"net/http"
	"net/http/httptest"
	"testing"
)

var (
	ErrInvalidToken = errors.New("invalid token")
	ErrUserNotFound = errors.New("account is not participant of the channel")
	ErrBodyNotSet   = errors.New("body is not set")
)

func setup(t *testing.T, fn func(s *httptest.Server)) {
	mux := http.NewServeMux()
	server := httptest.NewServer(mux)
	defer server.Close()
	mux.HandleFunc("/botchannel/token/user/someuser", ErrorHandler(ErrInvalidToken))
	mux.HandleFunc("/botchannel/validtoken/user/someuser", ErrorHandler(ErrUserNotFound))

	mux.HandleFunc("/botchannel/validtoken/user/floydpepper",
		func(w http.ResponseWriter, r *http.Request) {
			w.Header().Set("Content-Type", "application/json")
			w.WriteHeader(http.StatusOK)
			response := `{"data":{"channelId":"42"}, "error":null, "status":true}`
			w.Write([]byte(response))
		})

	fn(server)
}

func ErrorHandler(err error) func(http.ResponseWriter, *http.Request) {
	return func(w http.ResponseWriter, r *http.Request) {
		NewBadRequest(w, err)
	}
}

func setupPush(t *testing.T, fn func(s *httptest.Server)) {
	mux := http.NewServeMux()
	server := httptest.NewServer(mux)
	defer server.Close()
	mux.HandleFunc("/push/invalidtoken", ErrorHandler(ErrInvalidToken))
	mux.HandleFunc("/push/validtoken",
		func(w http.ResponseWriter, r *http.Request) {
			pr := new(PushRequest)
			err := json.NewDecoder(r.Body).Decode(pr)
			if err != nil {
				NewBadRequest(w, err)
				return
			}
			if pr.Body == "" {
				NewBadRequest(w, ErrBodyNotSet)
				return
			}

			w.Header().Set("Content-Type", "application/json")
			w.WriteHeader(http.StatusOK)
			response := `{"data":null, "status":true}`
			w.Write([]byte(response))

		})

	mux.HandleFunc("/botchannel/validtoken/user/floydpepper",
		func(w http.ResponseWriter, r *http.Request) {
			w.Header().Set("Content-Type", "application/json")
			w.WriteHeader(http.StatusOK)
			response := `{"data":{"channelId":"42"}, "error":null, "status":true}`
			w.Write([]byte(response))
		})

	fn(server)
}

func TestFetchBotChannelIntegration(t *testing.T) {
	setup(t, func(server *httptest.Server) {
		// test unknown user case
		_, err := FetchBotChannelId("someuser", "token", server.URL)
		if err == nil || err.Error() != ErrInvalidToken.Error() {
			t.Fatalf("expected '%s' error but got '%v'", ErrInvalidToken, err)
		}

		// test invalid token case
		_, err = FetchBotChannelId("someuser", "validtoken", server.URL)
		if err == nil || err.Error() != ErrUserNotFound.Error() {
			t.Fatalf("expected '%s' error but got '%s'", ErrUserNotFound, err)
		}

		// test valid username and token pair
		id, err := FetchBotChannelId("floydpepper", "validtoken", server.URL)
		if err != nil {
			t.Errorf("expected nil but got '%s'", err)
		}

		if id != 42 {
			t.Errorf("expected 42 as channel id but got %d", id)
		}
	})
}

func TestPush(t *testing.T) {
	setupPush(t, func(s *httptest.Server) {
		pr := &PushRequest{}
		token := "invalidtoken"

		err := Push(token, pr, s.URL)
		if err == nil || err.Error() != ErrInvalidToken.Error() {
			t.Errorf("expected '%s' but got '%v'", ErrInvalidToken, err)
		}

		token = "validtoken"
		err = Push(token, pr, s.URL)
		if err == nil || err.Error() != ErrBodyNotSet.Error() {
			t.Errorf("expected '%s' but got '%v'", ErrBodyNotSet, err)
		}
		pr.Body = "bodyshape"

		err = Push(token, pr, s.URL)
		if err != nil {
			t.Errorf("unexpected error: '%s'", err)
		}
	})
}

func NewBadRequest(w http.ResponseWriter, err error) {
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(http.StatusBadRequest)
	response := `{"description":"` + err.Error() + `", "error":"koding.BadRequest"}`
	w.Write([]byte(response))

}


text:
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

function assertEqArray(actual, expected) {
    if (actual.length != expected.length) {
        throw new Error(
            "array lengths not equal: got " +
            uneval(actual) + ", expected " + uneval(expected));
    }

    for (var i = 0; i < actual.length; ++i) {
        if (actual[i] != expected[i]) {
        throw new Error(
            "arrays not equal at element " + i + ": got " +
            uneval(actual) + ", expected " + uneval(expected));
        }
    }
}


text:
First you need to clone the project
```sh
$ git clone git@github.com:gabrielferreira/demo-ansible-docker-orchestration.git
$ cd demo-ansible-docker-orchestration
```
execute the command bellow to install Docker at the destination Host
```sh
$ ansible-playbook -i hosts install-docker.yml
```
execute the command bellow to build and run the Docker container
```sh
$ ansible-playbook -i hosts docker-image.yml
```

Now open your browser and enter the Docker URL **http://HOST_URL**

**It's Done**


text:
require 'pathname'

Puppet::Type.newtype(:dsc_xpsendpoint) do
  require Pathname.new(__FILE__).dirname + '../../' + 'puppet/type/base_dsc'
  require Pathname.new(__FILE__).dirname + '../../puppet_x/puppetlabs/dsc_type_helpers'

  @doc = %q{
    The DSC xPSEndpoint resource type.
    Automatically generated from
    'xPSDesiredStateConfiguration/DSCResources/MSFT_xPSSessionConfiguration/MSFT_xPSSessionConfiguration.schema.mof'

    To learn more about PowerShell Desired State Configuration, please
    visit https://technet.microsoft.com/en-us/library/dn249912.aspx.

    For more information about built-in DSC Resources, please visit
    https://technet.microsoft.com/en-us/library/dn249921.aspx.

    For more information about xDsc Resources, please visit
    https://github.com/PowerShell/DscResources.
  }

  validate do
      fail('dsc_name is a required attribute') if self[:dsc_name].nil?
    end

  def dscmeta_resource_friendly_name; 'xPSEndpoint' end
  def dscmeta_resource_name; 'MSFT_xPSSessionConfiguration' end
  def dscmeta_module_name; 'xPSDesiredStateConfiguration' end
  def dscmeta_module_version; '8.5.0.0' end

  newparam(:name, :namevar => true ) do
  end

  ensurable do
    newvalue(:exists?) { provider.exists? }
    newvalue(:present) { provider.create }
    newvalue(:absent)  { provider.destroy }
    defaultto { :present }
  end

  # Name:         PsDscRunAsCredential
  # Type:         MSFT_Credential
  # IsMandatory:  False
  # Values:       None
  newparam(:dsc_psdscrunascredential) do
    def mof_type; 'MSFT_Credential' end
    def mof_is_embedded?; true end
    desc "PsDscRunAsCredential"
    validate do |value|
      unless value.kind_of?(Hash)
        fail("Invalid value '#{value}'. Should be a hash")
      end
      PuppetX::Dsc::TypeHelpers.validate_MSFT_Credential("Credential", value)
    end
    munge do |value|
      PuppetX::Dsc::TypeHelpers.munge_sensitive_hash!(value)
    end
  end

  # Name:         Name
  # Type:         string
  # IsMandatory:  True
  # Values:       None
  newparam(:dsc_name) do
    def mof_type; 'string' end
    def mof_is_embedded?; false end
    desc "Name - Name of the PS Remoting Endpoint"
    isrequired
    validate do |value|
      unless value.kind_of?(String)
        fail("Invalid value '#{value}'. Should be a string")
      end
    end
  end

  # Name:         Ensure
  # Type:         string
  # IsMandatory:  False
  # Values:       ["Present", "Absent"]
  newparam(:dsc_ensure) do
    def mof_type; 'string' end
    def mof_is_embedded?; false end
    desc "Ensure - Whether to create the endpoint or delete it Valid values are Present, Absent."
    validate do |value|
      resource[:ensure] = value.downcase
      unless value.kind_of?(String)
        fail("Invalid value '#{value}'. Should be a string")
      end
      unless ['Present', 'present', 'Absent', 'absent'].include?(value)
        fail("Invalid value '#{value}'. Valid values are Present, Absent")
      end
    end
  end

  # Name:         StartupScript
  # Type:         string
  # IsMandatory:  False
  # Values:       None
  newparam(:dsc_startupscript) do
    def mof_type; 'string' end
    def mof_is_embedded?; false end
    desc "StartupScript - Path for the startup script"
    validate do |value|
      unless value.kind_of?(String)
        fail("Invalid value '#{value}'. Should be a string")
      end
    end
  end

  # Name:         RunAsCredential
  # Type:         MSFT_Credential
  # IsMandatory:  False
  # Values:       None
  newparam(:dsc_runascredential) do
    def mof_type; 'MSFT_Credential' end
    def mof_is_embedded?; true end
    desc "RunAsCredential - Credential for Running under different user context"
    validate do |value|
      unless value.kind_of?(Hash)
        fail("Invalid value '#{value}'. Should be a hash")
      end
      PuppetX::Dsc::TypeHelpers.validate_MSFT_Credential("RunAsCredential", value)
    end
    munge do |value|
      PuppetX::Dsc::TypeHelpers.munge_sensitive_hash!(value)
    end
  end

  # Name:         SecurityDescriptorSDDL
  # Type:         string
  # IsMandatory:  False
  # Values:       None
  newparam(:dsc_securitydescriptorsddl) do
    def mof_type; 'string' end
    def mof_is_embedded?; false end
    desc "SecurityDescriptorSDDL - SDDL for allowed users to connect to this endpoint"
    validate do |value|
      unless value.kind_of?(String)
        fail("Invalid value '#{value}'. Should be a string")
      end
    end
  end

  # Name:         AccessMode
  # Type:         string
  # IsMandatory:  False
  # Values:       ["Local", "Remote", "Disabled"]
  newparam(:dsc_accessmode) do
    def mof_type; 'string' end
    def mof_is_embedded?; false end
    desc "AccessMode - Whether the endpoint is remotely accessible or has local access only or no access Valid values are Local, Remote, Disabled."
    validate do |value|
      unless value.kind_of?(String)
        fail("Invalid value '#{value}'. Should be a string")
      end
      unless ['Local', 'local', 'Remote', 'remote', 'Disabled', 'disabled'].include?(value)
        fail("Invalid value '#{value}'. Valid values are Local, Remote, Disabled")
      end
    end
  end

  def builddepends
    pending_relations = super()
    PuppetX::Dsc::TypeHelpers.ensure_reboot_relationship(self, pending_relations)
  end
end

Puppet::Type.type(:dsc_xpsendpoint).provide :powershell, :parent => Puppet::Type.type(:base_dsc).provider(:powershell) do
  confine :true => (Gem::Version.new(Facter.value(:powershell_version)) >= Gem::Version.new('5.0.10586.117'))
  defaultfor :operatingsystem => :windows

  mk_resource_methods
end


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace ConApp.EventSample.EventDemo6
{
    /// <summary>
    /// 热水器
    /// </summary>
    public class Heater
    {
        public event EventHandler OnBoiled;
        private void RasieBoiledEvent()
        {
            if (OnBoiled == null)
            {
                Console.WriteLine("加热完成处理订阅事件为空");
            }
            else
            {
                OnBoiled(this, new EventArgs());
            }
        }
        private Thread heatThread;
        public void Begin()
        {
            heatTime = 5;
            heatThread = new Thread(new ThreadStart(Heat));
            heatThread.Start();
            Console.WriteLine("加热器已经开启", heatTime);

        }
        private int heatTime;
        private void Heat()
        {
            while (true)
            {
                Console.WriteLine("加热还需{0}秒", heatTime);

                if (heatTime == 0)
                {
                    RasieBoiledEvent();
                    return;
                }
                heatTime--;
                Thread.Sleep(1000);

            }
        }
    }
}


text:
from tornado.testing import gen_test
from . import BaseTestCase

class TestLocale(BaseTestCase):
    CHARSETS = [
        'big5', 'cp850', 'latin1', 'latin2', 'ascii', 'ujis', 'sjis',
        'hebrew', 'tis620', 'euckr', 'gb2312', 'greek', 'cp1250',
        'gbk', 'latin5', 'utf8', 'cp866', 'macroman', 'cp852', 'latin7',
        'utf8mb4', 'cp1251', 'cp1256', 'cp1257', 'cp932'
    ]

    @gen_test
    def test1(self):
        for charset in self.CHARSETS:
            with (yield self.pool.Connection()) as connection:
                yield connection.set_charset(charset)

                with connection.cursor() as cursor:
                    yield cursor.execute("SHOW VARIABLES LIKE 'character_set_client'")
                    data = cursor.fetchone()
                    self.assertEqual(data[1], charset)

    @gen_test
    def test_escape(self):
        with (yield self.pool.Connection()) as connection:
            s = connection.escape(r'"')
            self.assertEqual(s, '\'\\"\'')


text:
set :application, 'dash2-harvester'
set :repo_url, 'git@github.com:CDLUC3/dash2-harvester.git'
set :deploy_to, '/dash2/apps/dash2-harvester'

# Default value for linked_dirs is []
# set :linked_dirs, fetch(:linked_dirs, []).push('log', 'tmp/pids', 'tmp/cache', 'tmp/sockets', 'vendor/bundle', 'public/system')

set :linked_dirs, fetch(:linked_dirs, []).push('log', 'db')

# Default value for default_env is {}
# set :default_env, { path: "/dash2/apps/dash2-harvester/bin:$PATH" }

namespace :deploy do

end


text:
module OAuth2

  module Model

    class Authorization < ActiveRecord::Base
      self.table_name = :oauth2_authorizations

      belongs_to :oauth2_resource_owner, :polymorphic => true
      alias :owner  :oauth2_resource_owner
      alias :owner= :oauth2_resource_owner=

      belongs_to :client, :class_name => 'OAuth2::Model::Client'

      validates_presence_of :client, :owner

      validates_uniqueness_of :code,               :scope => :client_id, :allow_nil => true
      validates_uniqueness_of :refresh_token_hash, :scope => :client_id, :allow_nil => true
      validates_uniqueness_of :access_token_hash,                        :allow_nil => true

      attr_accessible nil if (defined?(ActiveRecord::VERSION) && ActiveRecord::VERSION::MAJOR <= 3) || defined?(ProtectedAttributes)

      class << self
        private :create, :new
      end

      extend Hashing
      hashes_attributes :access_token, :refresh_token

      def self.create_code(client: , additional_attributes: {}, predicate: nil)
        Lib::SecureCodeScheme.generate( attributes: code_gen_attributes(additional_attributes),
                                            predicate: predicate)
      end

      # When PKCE Atttributes (https://tools.ietf.org/html/rfc7636) are provided
      # the code generation will use them as apposed to an opaque code
      def self.code_gen_attributes(attr)
        if attr.keys.include? CODE_CHALLENGE
          {code_type: PKCE, code_challenge: attr[CODE_CHALLENGE], code_challenge_method: attr[CODE_CHALLENGE_METHOD]}
        else
          {code_type: OPAQUE}
        end
      end

      def self.create_access_token
        Lib::SecureCodeScheme.generate(predicate: ->(token) {
          hash = Lib::SecureCodeScheme.hashify(token)
          Helpers.count(self, :access_token_hash => hash).zero?
        })
      end

      def self.create_jwt_access_token(user)
        Lib::SecureCodeScheme.generate_id_token(user)
      end

      def self.create_refresh_token(client)
        # OAuth2.generate_id do |refresh_token|
        Lib::SecureCodeScheme.generate(predicate: ->(refresh_token) {
          hash = Lib::SecureCodeScheme.hashify(refresh_token)
          Helpers.count(client.authorizations, :refresh_token_hash => hash).zero?
        })
      end

      def self.for(owner, client, attributes = {})
        return nil unless owner and client

        unless client.is_a?(Client)
          raise ArgumentError, "The argument should be a #{Client}, instead it was a #{client.class}"
        end

        instance = owner.oauth2_authorization_for(client) ||
                   new do |authorization|
                     authorization.owner  = owner
                     authorization.client = client
                   end

        case attributes[RESPONSE_TYPE]
          when CODE
            instance.code ||= create_code(client: client, additional_attributes: attributes , predicate: nil)
          when TOKEN
            instance.access_token  ||= create_access_token
            instance.refresh_token ||= create_refresh_token(client)
          when CODE_AND_TOKEN
            instance.code = create_code(client: client, additional_attributes: attributes, predicate: nil)
            instance.access_token  ||= create_access_token
            instance.refresh_token ||= create_refresh_token(client)
        end

        if attributes[DURATION]
          instance.expires_at = Time.now + attributes[DURATION].to_i
        else
          instance.expires_at = nil
        end

        scopes = instance.scopes + (attributes[SCOPES] || [])
        scopes += attributes[SCOPE].split(/\s+/) if attributes[SCOPE]
        instance.scope = scopes.empty? ? nil : scopes.entries.join(' ')

        instance.save && instance

      rescue Object => error
        if Model.duplicate_record_error?(error)
          retry
        else
          raise error
        end
      end

      # This will only return an authorisation for JWT and non-JWT tokens
      def self.find_by_token_tuple(token_tuple)
        return nil if token_tuple.nil?

        if token_tuple[0] == :jwt
          find_by_jwt(token_tuple[1])
        else
          find_by_access_token_hash(Lib::SecureCodeScheme.hashify(token_tuple[1]))
        end
      end

      def self.find_by_jwt(jwt)
        auth = find_by(id_token: jwt)
        return nil if auth && auth.expired?
        auth
      rescue ActiveRecord::ActiveRecordError => e
        nil
      end

      def exchange!
        self.code          = nil
        self.access_token  = self.class.create_access_token
        self.refresh_token = nil
        save!
      end

      def exchange_for_token!(token_type:)
        self.code          = nil
        self.id_token      = self.class.create_jwt_access_token(owner)
        self.access_token  = self.class.create_access_token
        self.refresh_token = nil
        save!
      end

      def expired?
        return false unless expires_at
        expires_at < Time.now
      end

      def expires_in
        expires_at && (expires_at - Time.now).ceil
      end

      def generate_code(additional_attributes: {}, predicate: )
        # TODO: This is only called once, and the memorisation might effect the resending
        # of failure calls that use varying PKCE codes
        # Also, memorisation is expected in the tests
        if client.native_app?
          self.code = self.class.create_code(client: client, additional_attributes: additional_attributes, predicate: predicate)
        else
          self.code ||= self.class.create_code(client: client, additional_attributes: additional_attributes, predicate: predicate)
        end
        save && code
      end

      def generate_access_token
        self.access_token ||= self.class.create_access_token
        save && access_token
      end

      def grants_access?(user, *scopes)
        not expired? and user == owner and in_scope?(scopes)
      end

      def in_scope?(request_scope)
        [*request_scope].all?(&scopes.method(:include?))
      end

      def scopes
        scopes = scope ? scope.split(/\s+/) : []
        Set.new(scopes)
      end

    end

  end # module

end # module


text:
require "helper"
require "fluent/plugin/in_http_pull.rb"

require 'ostruct'

class HttpPullInputTestRequestMethod < Test::Unit::TestCase
  @stub_server = nil

  setup do
    @stub_server = StubServer.new
    @stub_server.start
  end

  teardown do
    @stub_server.shutdown
  end

  sub_test_case "request method" do
    TEST_INTERVAL_3_POST = %[
      tag test
      url http://localhost:3939/method_post

      interval 3s
      format json
      http_method post
    ]

    TEST_INTERVAL_3_DELETE = %[
      tag test
      url http://localhost:3939/method_delete

      interval 3s
      format json
      http_method delete
    ]

    test 'interval 3 with :post' do
      d = create_driver TEST_INTERVAL_3_POST
      assert_equal("test", d.instance.tag)
      assert_equal(3, d.instance.interval)

      d.run(timeout: 8) do
        sleep 7
      end
      assert_equal(2, d.events.size)

      d.events.each do |tag, time, record|
        assert_equal("test", tag)

        assert_equal({"url"=>"http://localhost:3939/method_post","status"=>200, "message"=>{"status"=>"OK"}}, record)
        assert(time.is_a?(Fluent::EventTime))
      end
    end

    test 'interval 3 with :delete' do
      d = create_driver TEST_INTERVAL_3_DELETE
      assert_equal("test", d.instance.tag)
      assert_equal(3, d.instance.interval)

      d.run(timeout: 8) do
        sleep 7
      end
      assert_equal(2, d.events.size)

      d.events.each do |tag, time, record|
        assert_equal("test", tag)

        assert_equal({"url"=>"http://localhost:3939/method_delete","status"=>200, "message"=>{"status"=>"OK"}}, record)
        assert(time.is_a?(Fluent::EventTime))
      end
    end
  end

  private

  def create_driver(conf)
    Fluent::Test::Driver::Input.new(Fluent::Plugin::HttpPullInput).configure(conf)
  end
end


text:
[![Slack Status](https://fork-cms.herokuapp.com/badge.svg)](https://fork-cms.herokuapp.com/)

You can find the documentation for Fork CMS here. A more user friendly version can be read on [http://docs.fork-cms.com](http://docs.fork-cms.com)

## Contributing

Want to help improving our documentation? Check out the dedicated article about contributing. See [contribute/03. documentation](docs/06. contribute/06. documentation.md) for details.

Questions? Feel free to discuss on our [Slack channel](https://fork-cms.herokuapp.com/)

## Table of Contents

### 1. Installation
1. [Download, upload & installation](docs/01. installation/01. installation.md)
1. [Installation Wizard](docs/01. installation/02. installation_wizard.md)
1. [Minimum requirements](docs/01. installation/03. minimum_requirements.md)
1. [Webservers](docs/01. installation/04. webservers.md)
1. [Upgrading](docs/01. installation/05. upgrading.md)
1. [Version control](docs/01. installation/06. version_control.md)
1. [Faq](docs/01. installation/07. faq.md)

### 2. Getting started
1. [Introduction](docs/02. getting started/01. introduction.md)
1. [Adding modules](docs/02. getting started/02. adding_modules.md)
1. [Adding a theme](docs/02. getting started/03. adding_a_theme.md)
1. [Spam protection](docs/02. getting started/04. spam_protection.md)
1. [Linking Facebook](docs/02. getting started/05. linking_facebook.md)
1. [Enable Twitter cards](docs/02. getting started/06. enable_twittercards.md)
1. [Configuring cronjobs](docs/02. getting started/07. configuring_cronjobs.md)
1. [Publish your website](docs/02. getting started/08. publish_your_website.md)

### 3. User guide
1. [Introduction](docs/03. user guide/01. introduction.md)
1. [Dashboard](docs/03. user guide/02. dashboard.md)
1. [Pages](docs/03. user guide/03. pages.md)
1. [The editor](docs/03. user guide/04. the_editor.md)
1. [Standard modules](docs/03. user guide/05. standard_modules.md)
1. [SEO](docs/03. user guide/06. seo.md)
1. [Marketing](docs/03. user guide/07. marketing.md)
1. [Mailmotor](docs/03. user guide/08. mailmotor.md)
1. [Settings](docs/03. user guide/09. settings.md)

### 4. Theming guide
1. [Introduction](docs/04. theming guide/01. introduction.md)
1. [What is a theme within fork?](docs/04. theming guide/02. what_is_a_theme_within_fork.md)
1. [Theme contents](docs/04. theming guide/03. theme_contents.md)
1. [Page templates, positions & blocks](docs/04. theming guide/04. page_templates_positions_and_blocks.md)
1. [Making a basic theme](docs/04. theming guide/05. making_a_basic_theme.md)
1. [Creating a template](docs/04. theming guide/06. creating_a_template.md)
1. [Locale and translations](docs/04. theming guide/07. locale_and_translations.md)
1. [Theme checklist](docs/04. theming guide/08. theme_checklist.md)

### 5. Module guide
1. [Introduction](docs/05. module guide/02. introduction.md)
1. [Applications & Library](docs/05. module guide/02. applications_and_library.md)
1. [Routing](docs/05. module guide/03. routing.md)
1. [Modeling your module](docs/05. module guide/04. modeling_your_module.md)
1. [Writing your module](docs/05. module guide/05. writing_your_module.md)
1. [Blocks and widgets](docs/05. module guide/06. blocks_and_widgets.md)
1. [Templates](docs/05. module guide/07. templates.md)
1. [Translations/Locale](docs/05. module guide/08. translations_or_locale.md)
1. [Forms](docs/05. module guide/09. forms.md)
1. [Data grids](docs/05. module guide/10. data_grids.md)
1. [Generate thumbnails based on folder](docs/05. module guide/11. generate_thumbnails_based_on_folder.md)
1. [Javascript](docs/05. module guide/12. javascript.md)
1. [Ajax](docs/05. module guide/13. ajax.md)
1. [Passing data from PHP to javascript](docs/05. module guide/14. passing_data_from_php_to_javascript.md)
1. [Cronjobs](docs/05. module guide/15. cronjobs.md)
1. [Module settings](docs/05. module guide/16. module_settings.md)
1. [Pagination](docs/05. module guide/17. pagination.md)
1. [Meta data & SEO](docs/05. module guide/18. meta_data_and_seo.md)
1. [Breadcrumbs](docs/05. module guide/19. breadcrumbs.md)
1. [Tags](docs/05. module guide/20. tags.md)
1. [Search](docs/05. module guide/21. search.md)
1. [Creating frontend-widgets](docs/05. module guide/22. creating_frontend_widgets.md)
1. [Events publish and subscribe](docs/05. module guide/25. events_publish_and_subscribe.md)
1. [Creating an installer](docs/05. module guide/26. creating_an_installer.md)
1. [Creating a module.zip file](docs/05. module guide/27. creating_a_module_zip_file.md)
1. [Implementing Twitter Cards](docs/05. module guide/28. twittercards.md)

### 6. Contribute
1. [Introduction](docs/06. contribute/01. introduction.md)
1. [Testing](docs/06. contribute/02. testing.md)
1. [Features](docs/06. contribute/03. features.md)
1. [Translations](docs/06. contribute/04. translations.md)
1. [User interface](docs/06. contribute/05. user_interface.md)
1. [Documentation](docs/06. contribute/06. documentation.md)
1. [Spreading the word](docs/06. contribute/07. spreading_the_word.md)
1. [Open sourcing your modules/themes](docs/06. contribute/08. open_sourcing_fork_cms_modules_and_themes.md)

### 7. Media Library
1. [Introduction](docs/07. media library/01. introduction.md)
1. [Integrating in your module](docs/07. media library/02. integrating in your module.md)
1. [Console commands](docs/07. media library/03. console commands.md)
1. [Cropper](docs/07. media library/04. cropper.md)


text:
module Tantot
  class Railtie < Rails::Railtie
    class RequestStrategy
      def initialize(app)
        @app = app
      end

      def call(env)
        Tantot.manager.run { @app.call(env) }
      end
    end

    console do |app|
      # Will sweep after every push (unfortunately)
      Tantot.config.sweep_on_push = true
    end

    initializer 'tantot.request_strategy' do |app|
      Tantot.logger.debug { "[Tantot] Installing Rails middleware" }
      app.config.middleware.insert_after(Rails::Rack::Logger, RequestStrategy)
    end

    config.to_prepare do
      Tantot.logger.debug { "[Tantot] Clearing registry" }
      Tantot.agent_registry.clear
    end
  end
end


text:
@interface introductoryPagesView : UIView

-(instancetype)initPagesViewWithFrame:(CGRect)frame Images:(NSArray *)images;

@end


text:
import * as React from 'react';
import '../style.css';

export default () => (

Hello world

);


text:
navbar top -->

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

                </button>

User Profile

Settings

                                Logout

                            <form id="logout-form" action="{{ url('/logout') }}" method="POST" style="display: none;">
                                {{ csrf_field() }}
                            </form>


text:
rm -rf cssTestData cssTestApps test.pid
mkdir cssTestData cssTestApps
./arangod -c arangod.conf --pid-file test.pid --log.requests-file req.log &
sleep 5
casperjs test standalone/compareAll.js
res=$?
kill `cat test.pid`
exit $res


text:
set -ex

while true; do
    sleep 1800
    indexer --all --rotate
done


text:
using CarpoolPlanner.NotificationService;
using NUnit.Framework;

namespace CarpoolPlanner.Tests.NotificationService
{
    [TestFixture]
    public class TwilioSmsClientTests
    {
        [Test]
        public void SplitMessage_ShouldNotSplit()
        {
            var messages = TwilioSmsClient.SplitMessage(@"Test message.", 160);

            foreach (var message in messages)
                Assert.That(message.Length, Is.AtMost(160), "Message is too long.");
            Assert.That(messages.Length, Is.EqualTo(1), "Wrong number of messages.");
        }

        [Test]
        public void SplitMessage_ShouldSplit_IfTooLong()
        {
            var messages = TwilioSmsClient.SplitMessage(@"Test very long message that is greater than 160 characters.
Lorum ipsum dolor sit amet consectetor adipiscing elit. Praesent commodo nisi nec turpis finibus, et interdum libero sollicitudin. Vestibulum ante ipsum metus.", 160);

            foreach (var message in messages)
                Assert.That(message.Length, Is.AtMost(160), "Message is too long.");
            Assert.That(messages.Length, Is.EqualTo(2), "Wrong number of messages.");
        }
    }
}


text:
case $(uname) in
Darwin)
    # commands for macOS go here
    brew install bat

    ;;
Linux)
    # commands for Linux go here
    if ! command -v bat &>/dev/null; then
        sudo apt install bat
    fi

    ;;
*) ;;
esac


text:
package com.sean.im.friend.action;

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

import com.sean.im.friend.entity.AdEntity;
import com.sean.im.server.constant.P;
import com.sean.persist.core.EntityDao;
import com.sean.persist.core.PersistContext;
import com.sean.persist.ext.Value;
import com.sean.service.annotation.ActionConfig;
import com.sean.service.core.Action;
import com.sean.service.core.Session;

@ActionConfig(description = "添加分组", authenticate = false,
mustParams = { P.adChatformLink, P.adChatformImgUrl })
public class UpdateAdChatformAction extends Action
{
	@Override
	public void execute(Session session) throws Exception
	{
		String adChatformLink = session.getParameter(P.adChatformLink);
		String adChatformImgUrl = session.getParameter(P.adChatformImgUrl);

		EntityDao<AdEntity> dao = PersistContext.CTX.getEntityDao(AdEntity.class);
		List<Value> vals = new ArrayList<>();
		vals.add(new Value("link", adChatformLink));
		vals.add(new Value("imgUrl", adChatformImgUrl));
		dao.update(1L, vals);
		session.success();
	}
}


text:
// F O R
// D E V E L O P M E N T  O N L Y
///////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////

/* since content security policy got more strict with manifest
   version 2 and I still want to load some stuff dynamically
   I need to get the hashes of used inline-scripts and add them
   to manifest.json - so far this is the only good workaround for
   this problem and to spare me some time, I'm generating the hashes
   while going (manually) through the background-page
*/
var csp_hashes = [], csp_result;

$(document).on('DOMNodeInserted', function(e){
	var target = e.target;

	if(
		(!$(target).attr('src')) &&
		(!$(target).attr('class')) &&
		($(target).prop('tagName') === 'SCRIPT')
	){
		target = target.innerHTML,
		target = sjcl.hash.sha256.hash(target),
		target = sjcl.codec.base64.fromBits(target);

		csp_hashes.indexOf(target) === -1 ? csp_hashes.push(target) : false;

		$.get('manifest.json', function(res){

			var csp_string = "'sha256-" + csp_hashes.join("' 'sha256-") + "'",
				csp_string = "script-src 'self' 'unsafe-eval' "+csp_string+";object-src 'self'"

			csp_result = res;
			csp_result.content_security_policy = csp_string;
		});
	}
});

function downloadManifest(){
	download(JSON.stringify(csp_result, null, "\t"), 'manifest.json', 'application/json')
}

///////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////

// Fix for warnings about sync requests (we are loading scripts inside html-templates)
// ToDo: remove when using fetch - since it shouldn't error out
$.ajaxPrefilter(function( options, original_Options, jqXHR ){ options.async = true; });

/*************************************************

MUTATION OBSERVER FOR MULTILANGUAGE

Because security-concerns blabla we need to
add mutlilang-text when DOM is updated/modified
(we can´t use placeholders inside html)
Now using Mutation Observer for better performance

*************************************************/
$(document).on("ready", function() {
	$('[data-i18n]').each(function() {
		var datavalue = $(this).data('i18n');
		$(this).prepend(browser.i18n.getMessage(datavalue));
	});

	// Listen for added elements and iterate over nodelist
	// only update added elements!
	var target = document.querySelector('.wrapper');

	var observer = new MutationObserver(function(mutation) {
		for (var m of mutation) {
			$(m.addedNodes).each(function(value, index) {

				var nodes = $(index).find('[data-i18n]');
				$(nodes).each(function() {
					var datavalue = $(this).data('i18n');
					$(this).prepend(browser.i18n.getMessage(datavalue));
				});

			});
		}
	});

	var config = { attributes: true, childList: true, subtree: true, characterData: true };
	observer.observe(target, config);
});

$(document).ready(function(){

	// Sidebar-Toggle - use AdminLTE framework
	toggleSidebar();

	// generate Database menu entries
	idb.opendb().then(function(db){
		var tables = Object.keys(db._allTables),
			tblstr = '';

		for(var i=0;i<tables.length;i++){ tblstr += '
'+tables[i]+'
'; }
		$('#loadDbContent').append(tblstr);

		// Events for Content-Loading + Menu
		var hash = window.location.hash;
		(hash === '') ? loadContent($('.sidebar-menu li a').get(0)) : loadContent($('a[href="'+hash+'"]')[0]);
	});

	$(window).on('hashchange', function(){ loadContent($('a[href="'+window.location.hash+'"]')[0]); });
	$('.sidebar-menu li a, .treeview-menu li a').on('click', function(){ loadContent(this); });

});

function loadContent(that){

	// Don't reload content - especially on hashchange which happens inside this function too
	if($(that).parent().is('.active')) return;

	// Get values to find out which menu-item was clicked
	var parent 		= $(that).parent().get(0),
		menuElem	= $('ul li:eq(0)', parent),
		treeView 	= $(parent).is('.treeview') || false,
		treeIndex	= $(that).closest('.sidebar-menu > li').index(),
		allMenus	= '.sidebar-menu li, .treeview-menu li',
		eid 		= (treeView) ? $('a', menuElem).attr('href') : $(that).attr('href');

	// Toggle active-class on menus
	if(treeView){
		$(allMenus).removeClass('active');
		$(parent).add(menuElem).addClass('active');
	}
	else if(!treeView){
		$(allMenus).add('.sidebar-menu > li:not(:eq('+treeIndex+'))').removeClass('active');
		$(parent).add(menuElem).add('.sidebar-menu > li:eq('+treeIndex+')').addClass('active');
	}

	// Toggle hashchange
	window.location.hash = eid;
	eid = eid.substr(1); // remove #

	// Load Content depending if it uses unique db string or not - remove leading db for function-call
	(/db/.test(eid)) ? loadDatabaseContent(eid.substr(2)) : $('.content-wrapper').load('/app_templates/'+eid+'.html');

}

function toggleSidebar(){

	// Ripped from https://github.com/almasaeed2010/AdminLTE/issues/896

	var $body = $('body');
	// On click, capture state and save it in localStorage
	$($.AdminLTE.options.sidebarToggleSelector).click(function () {
		localStorage.setItem('sidebar', $body.hasClass('sidebar-collapse') ? 1 : 0);
	});

	// On ready, read the set state and collapse if needed
	if (localStorage.getItem('sidebar') === '0') {
		$body.addClass('disable-animations sidebar-collapse');
		requestAnimationFrame(function () {
	  	$body.removeClass('disable-animations');
		});
	}
}

function updateProgress(percent, message){
	var percentage = Math.round(percent);

	$('#progress-bar span').css('width', percentage+'%');
	$('#progress-bar span').attr('data-value', percentage);

	if(message){
		$('#progress-bar + div').text(message);
	}

}


text:
<?xml version="1.0" encoding="utf-8"?>
<TableRow
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/tableRow1"
    android:layout_width="fill_parent"
    android:background="#FF000000"
    android:layout_marginBottom="1dp"
    android:layout_height="wrap_content" >

                <TextView
                    android:id="@+id/rLabel"
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_weight="1.5"
                    android:text="Label Name"
                    android:singleLine="true"
                    android:textAppearance="?android:attr/textAppearanceSmall"
                    android:textColor="#FFAAAAAA" />

                <TextView
                    android:id="@+id/rValue"
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:gravity="right"
                    android:text="0.00"
                    android:textColor="#FFFFFFFF"
                    android:textAppearance="?android:attr/textAppearanceSmall" />

</TableRow>


text:
package cache

import (
	"context"
	"encoding/json"
	"net/url"
	"strconv"
	"time"

	"myapp/entity"
	"myapp/sql"

	"github.com/mailgun/groupcache/v2"
)

// Service that cache will use to retrieve data.
type Service interface {
	RecordInfo() sql.Record
	GetByID(ctx context.Context, dest interface{}, id int64) error
	List(ctx context.Context, dest interface{}, opts sql.ListOptions) error
}

// Cache is a simple structure which holds the groupcache and the database service, exposes
// `GetByID` and `List` which returns cached (or stores new) items.
type Cache struct {
	service Service
	maxAge  time.Duration
	group   *groupcache.Group
}

// Size default size to use on groupcache, defaults to 3MB.
var Size int64 = 3 << (10 * 3)

// New returns a new cache service which exposes `GetByID` and `List` methods to work with.
// The "name" should be unique, "maxAge" for cache expiration.
func New(service Service, name string, maxAge time.Duration) *Cache {
	c := new(Cache)
	c.service = service
	c.maxAge = maxAge
	c.group = groupcache.NewGroup(name, Size, c)
	return c
}

const (
	prefixID   = "#"
	prefixList = "["
)

// Get implements the groupcache.Getter interface.
// Use `GetByID` and `List` instead.
func (c *Cache) Get(ctx context.Context, key string, dest groupcache.Sink) error {
	if len(key) < 2 { // empty or missing prefix+key, should never happen.
		return sql.ErrUnprocessable
	}

	var v interface{}

	prefix := key[0:1]
	key = key[1:]
	switch prefix {
	case prefixID:
		// Get by ID.
		id, err := strconv.ParseInt(key, 10, 64)
		if err != nil || id <= 0 {
			return err
		}

		switch c.service.RecordInfo().(type) {
		case *entity.Category:
			v = new(entity.Category)
		case *entity.Product:
			v = new(entity.Product)
		}

		err = c.service.GetByID(ctx, v, id)
		if err != nil {
			return err
		}

	case prefixList:
		// Get a set of records, list.
		q, err := url.ParseQuery(key)
		if err != nil {
			return err
		}
		opts := sql.ParseListOptions(q)

		switch c.service.RecordInfo().(type) {
		case *entity.Category:
			v = new(entity.Categories)
		case *entity.Product:
			v = new(entity.Products)
		}

		err = c.service.List(ctx, v, opts)
		if err != nil {
			return err
		}

	default:
		return sql.ErrUnprocessable
	}

	b, err := json.Marshal(v)
	if err != nil {
		return err
	}

	return dest.SetBytes(b, time.Now().Add(c.maxAge))
}

// GetByID binds an item to "dest" an item based on its "id".
func (c *Cache) GetByID(ctx context.Context, id string, dest *[]byte) error {
	return c.group.Get(ctx, prefixID+id, groupcache.AllocatingByteSliceSink(dest))
}

// List binds item to "dest" based on the "rawQuery" of `url.Values` for `ListOptions`.
func (c *Cache) List(ctx context.Context, rawQuery string, dest *[]byte) error {
	return c.group.Get(ctx, prefixList+rawQuery, groupcache.AllocatingByteSliceSink(dest))
}


text:
package eci

import (
	"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
	"github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses"
)

// DescribeContainerGroupPrice invokes the eci.DescribeContainerGroupPrice API synchronously
// api document: https://help.aliyun.com/api/eci/describecontainergroupprice.html
func (client *Client) DescribeContainerGroupPrice(request *DescribeContainerGroupPriceRequest) (response *DescribeContainerGroupPriceResponse, err error) {
	response = CreateDescribeContainerGroupPriceResponse()
	err = client.DoAction(request, response)
	return
}

// DescribeContainerGroupPriceWithChan invokes the eci.DescribeContainerGroupPrice API asynchronously
// api document: https://help.aliyun.com/api/eci/describecontainergroupprice.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) DescribeContainerGroupPriceWithChan(request *DescribeContainerGroupPriceRequest) (<-chan *DescribeContainerGroupPriceResponse, <-chan error) {
	responseChan := make(chan *DescribeContainerGroupPriceResponse, 1)
	errChan := make(chan error, 1)
	err := client.AddAsyncTask(func() {
		defer close(responseChan)
		defer close(errChan)
		response, err := client.DescribeContainerGroupPrice(request)
		if err != nil {
			errChan <- err
		} else {
			responseChan <- response
		}
	})
	if err != nil {
		errChan <- err
		close(responseChan)
		close(errChan)
	}
	return responseChan, errChan
}

// DescribeContainerGroupPriceWithCallback invokes the eci.DescribeContainerGroupPrice API asynchronously
// api document: https://help.aliyun.com/api/eci/describecontainergroupprice.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) DescribeContainerGroupPriceWithCallback(request *DescribeContainerGroupPriceRequest, callback func(response *DescribeContainerGroupPriceResponse, err error)) <-chan int {
	result := make(chan int, 1)
	err := client.AddAsyncTask(func() {
		var response *DescribeContainerGroupPriceResponse
		var err error
		defer close(result)
		response, err = client.DescribeContainerGroupPrice(request)
		callback(response, err)
		result <- 1
	})
	if err != nil {
		defer close(result)
		callback(nil, err)
		result <- 0
	}
	return result
}

// DescribeContainerGroupPriceRequest is the request struct for api DescribeContainerGroupPrice
type DescribeContainerGroupPriceRequest struct {
	*requests.RpcRequest
	OwnerId              requests.Integer `position:"Query" name:"OwnerId"`
	ResourceOwnerAccount string           `position:"Query" name:"ResourceOwnerAccount"`
	ResourceOwnerId      requests.Integer `position:"Query" name:"ResourceOwnerId"`
	OwnerAccount         string           `position:"Query" name:"OwnerAccount"`
	RegionId             string           `position:"Query" name:"RegionId"`
	Cpu                  requests.Float   `position:"Query" name:"Cpu"`
	Memory               requests.Float   `position:"Query" name:"Memory"`
}

// DescribeContainerGroupPriceResponse is the response struct for api DescribeContainerGroupPrice
type DescribeContainerGroupPriceResponse struct {
	*responses.BaseResponse
	RequestId string                                `json:"RequestId" xml:"RequestId"`
	PriceInfo DescribeContainerGroupPricePriceInfo0 `json:"PriceInfo" xml:"PriceInfo"`
}

type DescribeContainerGroupPricePriceInfo0 struct {
	Rules []DescribeContainerGroupPriceRule1 `json:"Rules" xml:"Rules"`
	Price DescribeContainerGroupPricePrice1  `json:"Price" xml:"Price"`
}

type DescribeContainerGroupPriceRule1 struct {
	RuleId      int64  `json:"RuleId" xml:"RuleId"`
	Description string `json:"Description" xml:"Description"`
}

type DescribeContainerGroupPricePrice1 struct {
	OriginalPrice float32                                  `json:"OriginalPrice" xml:"OriginalPrice"`
	DiscountPrice float32                                  `json:"DiscountPrice" xml:"DiscountPrice"`
	TradePrice    float32                                  `json:"TradePrice" xml:"TradePrice"`
	Currency      string                                   `json:"Currency" xml:"Currency"`
	DetailInfos   []DescribeContainerGroupPriceDetailInfo2 `json:"DetailInfos" xml:"DetailInfos"`
}

type DescribeContainerGroupPriceDetailInfo2 struct {
	Resource      string                             `json:"Resource" xml:"Resource"`
	OriginalPrice float32                            `json:"OriginalPrice" xml:"OriginalPrice"`
	DiscountPrice float32                            `json:"DiscountPrice" xml:"DiscountPrice"`
	TradePrice    float32                            `json:"TradePrice" xml:"TradePrice"`
	Rules         []DescribeContainerGroupPriceRule3 `json:"Rules" xml:"Rules"`
}

type DescribeContainerGroupPriceRule3 struct {
	RuleId      int64  `json:"RuleId" xml:"RuleId"`
	Description string `json:"Description" xml:"Description"`
}

// CreateDescribeContainerGroupPriceRequest creates a request to invoke DescribeContainerGroupPrice API
func CreateDescribeContainerGroupPriceRequest() (request *DescribeContainerGroupPriceRequest) {
	request = &DescribeContainerGroupPriceRequest{
		RpcRequest: &requests.RpcRequest{},
	}
	request.InitWithApiInfo("Eci", "2018-08-08", "DescribeContainerGroupPrice", "eci", "openAPI")
	return
}

// CreateDescribeContainerGroupPriceResponse creates a response to parse from DescribeContainerGroupPrice response
func CreateDescribeContainerGroupPriceResponse() (response *DescribeContainerGroupPriceResponse) {
	response = &DescribeContainerGroupPriceResponse{
		BaseResponse: &responses.BaseResponse{},
	}
	return
}


text:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">
        <Button
            android:id="@+id/btn_power_save"
            android:layout_width="150dp"
            android:layout_height="60dp"
            android:layout_margin="10dp"
            android:onClick="onClick"
            android:text="省电白名单"
            android:textAllCaps="false" />

        <Button
            android:id="@+id/btn_auto_start"
            android:layout_width="150dp"
            android:layout_height="60dp"
            android:layout_margin="10dp"
            android:onClick="onClick"
            android:text="自启动"
            android:textAllCaps="false" />

        <Button
            android:id="@+id/btn_double_process"
            android:layout_width="150dp"
            android:layout_height="60dp"
            android:layout_margin="10dp"
            android:onClick="onClick"
            android:text="双进程"
            android:textAllCaps="false" />

    </LinearLayout>
</ScrollView>


text:
<?php

namespace Symfony\Component\Config\Exception;

/**
 * Exception class for when a circular reference is detected when importing resources.
 *
 * @author Fabien Potencier <fabien@symfony.com>
 */
class FileLoaderImportCircularReferenceException extends LoaderLoadException
{
    public function __construct(array $resources, int $code = null, \Exception $previous = null)
    {
        $message = sprintf('Circular reference detected in "%s" ("%s" > "%s").', $this->varToString($resources[0]), implode('" > "', $resources), $resources[0]);

        \Exception::__construct($message, $code, $previous);
    }
}


text:
Install npm packages and compile JSX
```
npm install
grunt
```

If you are using Windows, run the following commands instead:
```
npm install --msvs_version=2013
grunt
```

Open the example in example/index.html.


text:
using autofill_assistant::password_change::TopIcon;

const gfx::VectorIcon& GetAssistantIconOrFallback() {
#if BUILDFLAG(GOOGLE_CHROME_BRANDING)
  return vector_icons::kAssistantIcon;
#else
  // Only developer builds will ever use this branch.
  return vector_icons::kProductIcon;
#endif
}

const gfx::VectorIcon& GetApcTopIconFromEnum(TopIcon icon, bool dark_mode) {
  if (!dark_mode) {
    switch (icon) {
      case TopIcon::TOP_ICON_UNSPECIFIED:
        return autofill_assistant::password_change::kUnspecifiedStateIcon;
      case TopIcon::TOP_ICON_OPEN_SITE_SETTINGS:
        return autofill_assistant::password_change::kOpenSiteSettingsIcon;
      case TopIcon::TOP_ICON_ENTER_OLD_PASSWORD:
        return autofill_assistant::password_change::kEnterOldPasswordIcon;
      case TopIcon::TOP_ICON_CHOOSE_NEW_PASSWORD:
        return autofill_assistant::password_change::kChooseNewPasswordIcon;
      case TopIcon::TOP_ICON_SAVE_NEW_PASSWORD:
        return autofill_assistant::password_change::kSaveNewPasswordIcon;
      case TopIcon::TOP_ICON_CHANGED_PASSWORD:
        return autofill_assistant::password_change::kChangedPasswordIcon;
      case TopIcon::TOP_ICON_PASSWORD_RESET_REQUESTED:
        return autofill_assistant::password_change::kPasswordResetRequestedIcon;
      case TopIcon::TOP_ICON_BAD_NEW_PASSWORD:
        return autofill_assistant::password_change::kBadNewPasswordIcon;
      case TopIcon::TOP_ICON_ERROR_OCCURRED:
        return autofill_assistant::password_change::kErrorOccurredIcon;
      case TopIcon::TOP_ICON_USER_ACTION_REQUIRED:
        return autofill_assistant::password_change::kUserActionRequiredIcon;
    }
  } else {
    switch (icon) {
      case TopIcon::TOP_ICON_UNSPECIFIED:
        return autofill_assistant::password_change::kUnspecifiedStateDarkIcon;
      case TopIcon::TOP_ICON_OPEN_SITE_SETTINGS:
        return autofill_assistant::password_change::kOpenSiteSettingsDarkIcon;
      case TopIcon::TOP_ICON_ENTER_OLD_PASSWORD:
        return autofill_assistant::password_change::kEnterOldPasswordDarkIcon;
      case TopIcon::TOP_ICON_CHOOSE_NEW_PASSWORD:
        return autofill_assistant::password_change::kChooseNewPasswordDarkIcon;
      case TopIcon::TOP_ICON_SAVE_NEW_PASSWORD:
        return autofill_assistant::password_change::kSaveNewPasswordDarkIcon;
      case TopIcon::TOP_ICON_CHANGED_PASSWORD:
        return autofill_assistant::password_change::kChangedPasswordDarkIcon;
      case TopIcon::TOP_ICON_PASSWORD_RESET_REQUESTED:
        return autofill_assistant::password_change::
            kPasswordResetRequestedDarkIcon;
      case TopIcon::TOP_ICON_BAD_NEW_PASSWORD:
        return autofill_assistant::password_change::kBadNewPasswordDarkIcon;
      case TopIcon::TOP_ICON_ERROR_OCCURRED:
        return autofill_assistant::password_change::kErrorOccurredDarkIcon;
      case TopIcon::TOP_ICON_USER_ACTION_REQUIRED:
        return autofill_assistant::password_change::kUserActionRequiredDarkIcon;
    }
  }
}


text:
'use strict';

exports.__esModule = true;
exports['default'] = bindConnector;

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }

var _bindConnectorMethod2 = require('./bindConnectorMethod');

var _bindConnectorMethod3 = _interopRequireDefault(_bindConnectorMethod2);

var _disposables = require('disposables');

function bindConnector(connector, handlerId) {
  var compositeDisposable = new _disposables.CompositeDisposable();
  var handlerConnector = {};

  Object.keys(connector).forEach(function (key) {
    var _bindConnectorMethod = _bindConnectorMethod3['default'](handlerId, connector[key]);

    var disposable = _bindConnectorMethod.disposable;
    var ref = _bindConnectorMethod.ref;

    compositeDisposable.add(disposable);
    handlerConnector[key] = function () {
      return ref;
    };
  });

  return {
    disposable: compositeDisposable,
    handlerConnector: handlerConnector
  };
}

module.exports = exports['default'];


text:
import { helper } from '@ember/component/helper';

export function combineValidators(validators) {
  return validators.reduce((previousValidator, currentValidator) => (
    (value) => {
      const currentValidatorResult = currentValidator(value);
      return currentValidatorResult === true ? previousValidator(value) : currentValidatorResult;
    }
  ), () => true);
}

export default helper(combineValidators);


text:
import os
import json

# create clustering.json and ranking.json for each folder

def create_output_folder_problem(output_folder, dict_file):
    for k, v in dict_file.iteritems():
        output_each_problem = output_folder + "/" + k
        if not os.path.exists(output_each_problem):
            os.makedirs(output_each_problem)

def write_cluster(dict_output, out_folder):
    list_all = []
    list_val = []
    for v in dict_output.values():
        list_val.append(v)
    set_val = set(list_val)

    for val in set_val:
        list_per_cluster = []
        for k, v in dict_output.iteritems():
            if val == v:
                list_per_cluster.append(k)
        list_all.append(list_per_cluster)

    list_all_output = []
    for i in xrange(len(list_all)):
        list_cluster = []
        for j in xrange(len(list_all[i])):
            dict_per_doc = {}
            dict_per_doc["document"] = list_all[i][j] + ".txt"
            list_cluster.append(dict_per_doc)
        list_all_output.append(list_cluster)

    out_path = out_folder + "/clustering.json"
    out_file = open(out_path, "w")

    json.dump(list_all_output, out_file, indent=4)
    return list_all_output

def write_ranking(comb_list, all_sim, out_folder):
    list_all_output = []
    for i in xrange(len(comb_list)):
        dict_sim_perpair = {}
        dict_sim_perpair["document1"] = comb_list[i][0]
        dict_sim_perpair["document2"] = comb_list[i][1]
        dict_sim_perpair["score"] = round(all_sim[i][0][0],6)
        list_all_output.append(dict_sim_perpair)
    out_path = out_folder + "/ranking.json"
    out_file = open(out_path, "w")

    json.dump(list_all_output, out_file, indent=4)
    return list_all_output


text:
<?php

# Copyright (c) 2010-2015 Yubico AB
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
#   * Redistributions of source code must retain the above copyright
#     notice, this list of conditions and the following disclaimer.
#
#   * Redistributions in binary form must reproduce the above
#     copyright notice, this list of conditions and the following
#     disclaimer in the documentation and/or other materials provided
#     with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

set_include_path(get_include_path() . PATH_SEPARATOR .
		 "/etc/yubico/val:/usr/share/yubikey-val");

require_once 'ykval-config.php';

function url2shortname ($url) {
  if (preg_match("/^[^\/]+\/\/([a-z0-9-]+)/", $url, $name)==0){
    echo "Cannot match URL hostname: " . $url . "\n";
    exit (1);
  }

  return $name[1];
}

$ksms = otp2ksmurls ("ccccccccfnkjtvvijktfrvvginedlbvudjhjnggndtck", 16);
$shortksms = array_map("url2shortname", $ksms);

if ($argc==2 && strcmp($argv[1], "autoconf") == 0) {
  print "yes\n";
  exit (0);
}

if ($argc==2 && strcmp($argv[1], "config") == 0) {

  echo "multigraph ykval_ksmlatency\n";
  echo "graph_title KSM latency\n";
  echo "graph_vlabel Average KSM Decrypt Latency (seconds)\n";
  echo "graph_category ykval\n";
  echo "graph_width 400\n";

  foreach ($shortksms as $shortksm) {
    echo "${shortksm}_avgwait.label ${shortksm}\n";
    echo "${shortksm}_avgwait.type GAUGE\n";
    echo "${shortksm}_avgwait.info Average wait time for KSM decrypt\n";
    echo "${shortksm}_avgwait.min 0\n";
    echo "${shortksm}_avgwait.draw LINE1\n";
  }

  exit (0);
}

echo "multigraph ykval_ksmlatency\n";
foreach ($ksms as $ksm) {
  $shortksm = url2shortname ($ksm);
  $time = `curl --silent --write-out '%{time_total}' --max-time 3 '$ksm' -o /dev/null`;
  if (preg_match("/^3\./", $time)) {
    $time = "timeout";
  }
  if (preg_match("/^0\.000/", $time)) {
    $time = "error";
  }
  echo "${shortksm}_avgwait.value $time\n";
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>S-Index</title>
<meta name="date" content="2017-06-20">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes

A B C D F G H I L M O P Q R S T U V

S

SecurityOrderElement - Class in conrad.weiser.robinhood.api.endpoint.orders.data

SecurityOrderElement() - Constructor for class conrad.weiser.robinhood.api.endpoint.orders.data.SecurityOrderElement

service - Variable in class conrad.weiser.robinhood.api.ApiMethod

setAccountNumber(String) - Method in class conrad.weiser.robinhood.api.ConfigurationManager

setAuthToken(String) - Method in class conrad.weiser.robinhood.api.ConfigurationManager

Method which registers the authToken for the user into the Configuration Manager

setAuthToken(String) - Method in class conrad.weiser.robinhood.api.RobinhoodApi

Deprecated.

setEndpointParameters() - Method in class conrad.weiser.robinhood.api.endpoint.orders.Orders

Method which sets up the basic parameters for the endpoint.

setMethod(RequestMethod) - Method in class conrad.weiser.robinhood.api.ApiMethod

Method to set the request method

setOrderParameters() - Method in class conrad.weiser.robinhood.api.endpoint.orders.methods.MakeLimitOrder

Method which sets the URLParameters for correctly so the order is ran as a
 Limit Buy order, given the settings from the constructor

setOrderSafe(boolean) - Method in class conrad.weiser.robinhood.api.endpoint.orders.Orders

setRatelimit(int) - Method in class conrad.weiser.robinhood.api.ConfigurationManager

Set a new ratelimit (in milliseconds)

setReturnType(Type) - Method in class conrad.weiser.robinhood.api.ApiMethod

Method to set what return type this method requires

setUrlBase(String) - Method in class conrad.weiser.robinhood.api.ApiMethod

Method which sets the URL base.

SourceOfFunds - Enum in conrad.weiser.robinhood.api.endpoint.account.data.enums

A B C D F G H I L M O P Q R S T U V

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes


text:
#include <stdint.h>
#include <expat.h>

#ifdef __cplusplus
extern "C" {
#endif

struct sharedstringlist {
  XML_Char** strings;
  size_t numstrings;
};

struct sharedstringlist* sharedstringlist_create ();
void sharedstringlist_destroy (struct sharedstringlist* sharedstrings);
size_t sharedstringlist_size (struct sharedstringlist* sharedstrings);
int sharedstringlist_add_buffer (struct sharedstringlist* sharedstrings, const XML_Char* data, size_t datalen);
int sharedstringlist_add_string (struct sharedstringlist* sharedstrings, const XML_Char* data);
const XML_Char* sharedstringlist_get (struct sharedstringlist* sharedstrings, size_t index);

////////////////////////////////////////////////////////////////////////

struct shared_strings_callback_data {
  XML_Parser xmlparser;
  struct sharedstringlist* sharedstrings;
  int insst;
  int insi;
  int intext;
  XML_Char* text;
  size_t textlen;
  XML_Char* skiptag;                    //tag to skip
  size_t skiptagcount;                  //nesting level for current tag to skip
  XML_StartElementHandler skip_start;   //start handler to set after skipping
  XML_EndElementHandler skip_end;       //end handler to set after skipping
  XML_CharacterDataHandler skip_data;   //data handler to set after skipping
};

void shared_strings_callback_data_initialize (struct shared_strings_callback_data* data, struct sharedstringlist* sharedstrings);
void shared_strings_callback_data_cleanup (struct shared_strings_callback_data* data);
void shared_strings_callback_skip_tag_start (void* callbackdata, const XML_Char* name, const XML_Char** atts);
void shared_strings_callback_skip_tag_end (void* callbackdata, const XML_Char* name);
void shared_strings_callback_find_sharedstringtable_start (void* callbackdata, const XML_Char* name, const XML_Char** atts);
void shared_strings_callback_find_sharedstringtable_end (void* callbackdata, const XML_Char* name);
void shared_strings_callback_find_shared_stringitem_start (void* callbackdata, const XML_Char* name, const XML_Char** atts);
void shared_strings_callback_find_shared_stringitem_end (void* callbackdata, const XML_Char* name);
void shared_strings_callback_find_shared_string_start (void* callbackdata, const XML_Char* name, const XML_Char** atts);
void shared_strings_callback_find_shared_string_end (void* callbackdata, const XML_Char* name);
void shared_strings_callback_string_data (void* callbackdata, const XML_Char* buf, int buflen);

#ifdef __cplusplus
}
#endif

#endif


text:
/**
 * 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 org.jivesoftware.smackx.pubsub;

import org.jivesoftware.smackx.pubsub.util.XmlUtils;

/**
 * Represents an unsubscribe element.
 *
 * @author Robin Collier
 */
public class UnsubscribeExtension extends NodeExtension
{
	protected String jid;
	protected String id;

	public UnsubscribeExtension(String subscriptionJid)
	{
		this(subscriptionJid, null, null);
	}

	public UnsubscribeExtension(String subscriptionJid, String nodeId)
	{
		this(subscriptionJid, nodeId, null);
	}

	public UnsubscribeExtension(String jid, String nodeId, String subscriptionId)
	{
		super(PubSubElementType.UNSUBSCRIBE, nodeId);
		this.jid = jid;
		id = subscriptionId;
	}

	public String getJid()
	{
		return jid;
	}

	public String getId()
	{
		return id;
	}

	@Override
	public String toXML()
	{
		StringBuilder builder = new StringBuilder("<");
		builder.append(getElementName());
		XmlUtils.appendAttribute(builder, "jid", jid);

		if (getNode() != null)
			XmlUtils.appendAttribute(builder, "node", getNode());

		if (id != null)
			XmlUtils.appendAttribute(builder, "subid", id);

		builder.append("/>");
		return builder.toString();
	}

}