text:
"""Creates a directory with with the unpacked contents of the remoting webapp.

The directory will contain a copy-of or a link-to to all remoting webapp
resources.  This includes HTML/JS and any plugin binaries. The script also
massages resulting files appropriately with host plugin data. Finally,
a zip archive for all of the above is produced.
"""

# Python 2.5 compatibility
from __future__ import with_statement

import argparse
import io
import os
import platform
import re
import shutil
import subprocess
import sys
import time
import zipfile

# Update the module path, assuming that this script is in src/remoting/webapp,
# and that the google_api_keys module is in src/google_apis. Note that
# sys.path[0] refers to the directory containing this script.
if __name__ == '__main__':
  sys.path.append(
      os.path.abspath(os.path.join(sys.path[0], '../../google_apis')))
import google_api_keys

def findAndReplace(filepath, findString, replaceString):
  """Does a search and replace on the contents of a file."""
  oldFilename = os.path.basename(filepath) + '.old'
  oldFilepath = os.path.join(os.path.dirname(filepath), oldFilename)
  os.rename(filepath, oldFilepath)
  with open(oldFilepath) as input:
    with open(filepath, 'w') as output:
      for s in input:
        output.write(s.replace(findString, replaceString))
  os.remove(oldFilepath)

def createZip(zip_path, directory):
  """Creates a zipfile at zip_path for the given directory."""
  zipfile_base = os.path.splitext(os.path.basename(zip_path))[0]
  zip = zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED)
  for (root, dirs, files) in os.walk(directory):
    for f in files:
      full_path = os.path.join(root, f)
      rel_path = os.path.relpath(full_path, directory)
      zip.write(full_path, os.path.join(zipfile_base, rel_path))
  zip.close()

def replaceString(destination, placeholder, value):
  findAndReplace(os.path.join(destination, 'plugin_settings.js'),
                 "'" + placeholder + "'", "'" + value + "'")

def replaceBool(destination, placeholder, value):
  # Look for a "!!" in the source code so the expession we're
  # replacing looks like a boolean to the compiler.  A single "!"
  # would satisfy the compiler but might confused human readers.
  findAndReplace(os.path.join(destination, 'plugin_settings.js'),
                 "!!'" + placeholder + "'", 'true' if value else 'false')

def parseBool(boolStr):
  """Tries to parse a string as a boolean value.

  Returns a bool on success; raises ValueError on failure.
  """
  lower = boolStr.lower()
  if lower in ['0', 'false']: return False
  if lower in ['1', 'true']: return True
  raise ValueError('not a boolean string {!r}'.format(boolStr))

def getenvBool(name, defaultValue):
  """Gets an environment value as a boolean."""
  rawValue = os.environ.get(name)
  if rawValue is None:
    return defaultValue
  try:
    return parseBool(rawValue)
  except ValueError:
    raise Exception('Value of ${} must be boolean!'.format(name))

def processJinjaTemplate(input_file, include_paths, output_file, context):
  jinja2_path = os.path.normpath(
      os.path.join(os.path.abspath(__file__),
                   '../../../third_party/jinja2'))
  sys.path.append(os.path.split(jinja2_path)[0])
  import jinja2
  (template_path, template_name) = os.path.split(input_file)
  include_paths = [template_path] + include_paths
  env = jinja2.Environment(loader=jinja2.FileSystemLoader(include_paths))
  template = env.get_template(template_name)
  rendered = template.render(context)
  io.open(output_file, 'w', encoding='utf-8').write(rendered)

def getClientPluginType(webapp_type):
  if webapp_type in ['v1', 'v2']:
    return 'native'
  elif webapp_type in ['v2_pnacl', 'shared_module']:
    return 'pnacl'
  elif webapp_type is 'app_remoting':
    return ''

def buildWebApp(buildtype, version, destination, zip_path,
                manifest_template, webapp_type, appid, app_client_id, app_name,
                app_description, app_capabilities, manifest_key, files,
                files_listfile, locales_listfile, jinja_paths,
                service_environment, use_gcd):
  """Does the main work of building the webapp directory and zipfile.

  Args:
    buildtype: the type of build ("Official", "Release" or "Dev").
    destination: A string with path to directory where the webapp will be
                 written.
    zipfile: A string with path to the zipfile to create containing the
             contents of |destination|.
    manifest_template: jinja2 template file for manifest.
    webapp_type: webapp type:
                 For DesktopRemoting: "v1", "v2" or "v2_pnacl"
                 For AppRemoting: "app_remoting" or "shared_module"
    appid: A string with the Remoting Application Id (only used for app
           remoting webapps). If supplied, it defaults to using the
           test API server.
    app_client_id: The OAuth2 client ID for the webapp.
    app_name: A string with the name of the application.
    app_description: A string with the description of the application.
    app_capabilities: A set of strings naming the capabilities that should be
                      enabled for this application.
    manifest_key: The manifest key for the webapp.
    files: An array of strings listing the paths for resources to include
           in this webapp.
    files_listfile: The name of a file containing a list of files, one per
                    line, identifying the resources to include in this webapp.
                    This is an alternate to specifying the files directly via
                    the 'files' option. The files listed in this file are
                    appended to the files passed via the 'files' option, if any.
    locales_listfile: The name of a file containing a list of locales, one per
                      line, which are copied, along with their directory
                      structure, from the _locales directory down.
    jinja_paths: An array of paths to search for {%include} directives in
                 addition to the directory containing the manifest template.
    service_environment: Used to point the webapp to one of the
                         dev/test/staging/vendor/prod/prod-testing environments
    use_gcd: True if GCD support should be enabled.
  """

  # Load the locales files from the locales_listfile.
  if not locales_listfile:
    raise Exception('You must specify a locales_listfile')
  locales = []
  with open(locales_listfile) as input:
    for s in input:
      locales.append(s.rstrip())

  # Load the files from the files_listfile.
  if files_listfile:
    with open(files_listfile) as input:
      for s in input:
        files.append(s.rstrip())

  # Ensure a fresh directory.
  try:
    shutil.rmtree(destination)
  except OSError:
    if os.path.exists(destination):
      raise
    else:
      pass
  os.makedirs(destination, 0775)

  if buildtype != 'Official' and buildtype != 'Release' and buildtype != 'Dev':
    raise Exception('Unknown buildtype: ' + buildtype)

  jinja_context = {
    'webapp_type': webapp_type,
    'buildtype': buildtype,
  }

  # Copy all the files.
  for current_file in files:
    destination_file = os.path.join(destination, os.path.basename(current_file))

    # Process *.jinja2 files as jinja2 templates
    if current_file.endswith(".jinja2"):
      destination_file = destination_file[:-len(".jinja2")]
      processJinjaTemplate(current_file, jinja_paths,
                           destination_file, jinja_context)
    else:
      shutil.copy2(current_file, destination_file)

  # Copy all the locales, preserving directory structure
  destination_locales = os.path.join(destination, '_locales')
  os.mkdir(destination_locales, 0775)
  remoting_locales = os.path.join(destination, 'remoting_locales')
  os.mkdir(remoting_locales, 0775)
  for current_locale in locales:
    extension = os.path.splitext(current_locale)[1]
    if extension == '.json':
      locale_id = os.path.split(os.path.split(current_locale)[0])[1]
      destination_dir = os.path.join(destination_locales, locale_id)
      destination_file = os.path.join(destination_dir,
                                      os.path.split(current_locale)[1])
      os.mkdir(destination_dir, 0775)
      shutil.copy2(current_locale, destination_file)
    elif extension == '.pak':
      destination_file = os.path.join(remoting_locales,
                                      os.path.split(current_locale)[1])
      shutil.copy2(current_locale, destination_file)
    else:
      raise Exception('Unknown extension: ' + current_locale)

  is_app_remoting_webapp = webapp_type == 'app_remoting'
  is_app_remoting_shared_module = webapp_type == 'shared_module'
  is_app_remoting = is_app_remoting_webapp or is_app_remoting_shared_module
  is_prod_service_environment = service_environment == 'vendor' or \
                                service_environment == 'prod' or \
                                service_environment == 'prod-testing'
  is_desktop_remoting = not is_app_remoting

  # Set client plugin type.
  if not is_app_remoting_webapp:
    client_plugin = getClientPluginType(webapp_type)
    findAndReplace(os.path.join(destination, 'plugin_settings.js'),
                 "'CLIENT_PLUGIN_TYPE'", "'" + client_plugin + "'")

  # Allow host names for google services/apis to be overriden via env vars.
  oauth2AccountsHost = os.environ.get(
      'OAUTH2_ACCOUNTS_HOST', 'https://accounts.google.com')
  oauth2ApiHost = os.environ.get(
      'OAUTH2_API_HOST', 'https://www.googleapis.com')
  directoryApiHost = os.environ.get(
      'DIRECTORY_API_HOST', 'https://www.googleapis.com')
  remotingApiHost = os.environ.get(
      'REMOTING_API_HOST', 'https://remoting-pa.googleapis.com')

  if is_app_remoting:
    appRemotingApiHost = os.environ.get(
        'APP_REMOTING_API_HOST', None)

  if is_app_remoting_webapp:
    appRemotingApplicationId = os.environ.get(
        'APP_REMOTING_APPLICATION_ID', None)

    # Release/Official builds are special because they are what we will upload
    # to the web store.  The checks below will validate that prod builds are
    # being generated correctly (no overrides) and with the correct buildtype.
    # They also verify that folks are not accidentally building dev/test/staging
    # apps for release (no impersonation) instead of dev.
    if is_prod_service_environment and buildtype == 'Dev':
      raise Exception("Prod environment cannot be built for 'dev' builds")

    if buildtype != 'Dev':
      if not is_prod_service_environment:
        raise Exception('Invalid service_environment targeted for '
                        + buildtype + ': ' + service_environment)
      if appid != None:
        raise Exception('Cannot pass in an appid for '
                        + buildtype + ' builds: ' + service_environment)
      if appRemotingApiHost != None:
        raise Exception('Cannot set APP_REMOTING_API_HOST env var for '
                        + buildtype + ' builds')
      if appRemotingApplicationId != None:
        raise Exception('Cannot set APP_REMOTING_APPLICATION_ID env var for '
                        + buildtype + ' builds')

    # If an Application ID was set (either from service_environment variable or
    # from a command line argument), hardcode it, otherwise get it at runtime.
    effectiveAppId = appRemotingApplicationId or appid
    if effectiveAppId:
      appRemotingApplicationId = "'" + effectiveAppId + "'"
    else:
      appRemotingApplicationId = "chrome.i18n.getMessage('@@extension_id')"
    findAndReplace(os.path.join(destination, 'arv_main.js'),
                   "'APP_REMOTING_APPLICATION_ID'", appRemotingApplicationId)

  oauth2BaseUrl = oauth2AccountsHost + '/o/oauth2'
  oauth2ApiBaseUrl = oauth2ApiHost + '/oauth2'
  directoryApiBaseUrl = directoryApiHost + '/chromoting/v1'
  telemetryApiBaseUrl = remotingApiHost + '/v1/events'

  if is_app_remoting:
    # Set the apiary endpoint and then set the endpoint version
    if not appRemotingApiHost:
      if is_prod_service_environment:
        appRemotingApiHost = 'https://www.googleapis.com'
      else:
        appRemotingApiHost = 'https://www-googleapis-test.sandbox.google.com'

    # TODO(garykac) Currently, the shared module is always set up for the
    # dev service_environment. Update build so that the dev environment can
    # be controlled by the app stub rather than hard-coded into the shared
    # module.
    if service_environment == 'dev' or is_app_remoting_shared_module:
      appRemotingServicePath = '/appremoting/v1beta1_dev'
    elif service_environment == 'test':
      appRemotingServicePath = '/appremoting/v1beta1'
    elif service_environment == 'staging':
      appRemotingServicePath = '/appremoting/v1beta1_staging'
    elif service_environment == 'vendor':
      appRemotingServicePath = '/appremoting/v1beta1_vendor'
    elif service_environment == 'prod':
      appRemotingServicePath = '/appremoting/v1beta1'
    elif service_environment == 'prod-testing':
      appRemotingServicePath = '/appremoting/v1beta1_prod_testing'
    else:
      raise Exception('Unknown service environment: ' + service_environment)
    appRemotingApiBaseUrl = appRemotingApiHost + appRemotingServicePath
  else:
    appRemotingApiBaseUrl = ''

  # TODO(garykac) replaceString (et al.) implictly update plugin_settings.js,
  # which doesn't exist for the app stub. We need to move app-specific
  # AppRemoting options into arv_main.js.
  if not is_app_remoting_webapp:
    replaceBool(destination, 'USE_GCD', use_gcd)
    replaceString(destination, 'OAUTH2_BASE_URL', oauth2BaseUrl)
    replaceString(destination, 'OAUTH2_API_BASE_URL', oauth2ApiBaseUrl)
    replaceString(destination, 'DIRECTORY_API_BASE_URL', directoryApiBaseUrl)
    replaceString(destination, 'TELEMETRY_API_BASE_URL', telemetryApiBaseUrl)
    if is_app_remoting:
      replaceString(destination, 'APP_REMOTING_API_BASE_URL',
                    appRemotingApiBaseUrl)

  # Substitute hosts in the manifest's CSP list.
  # Ensure we list the API host only once if it's the same for multiple APIs.
  googleApiHosts = ' '.join(set([oauth2ApiHost, directoryApiHost]))

  # WCS and the OAuth trampoline are both hosted on talkgadget. Split them into
  # separate suffix/prefix variables to allow for wildcards in manifest.json.
  talkGadgetHostSuffix = os.environ.get(
      'TALK_GADGET_HOST_SUFFIX', 'talkgadget.google.com')
  talkGadgetHostPrefix = os.environ.get(
      'TALK_GADGET_HOST_PREFIX', 'https://chromoting-client.')
  oauth2RedirectHostPrefix = os.environ.get(
      'OAUTH2_REDIRECT_HOST_PREFIX', 'https://chromoting-oauth.')

  # Use a wildcard in the manifest.json host specs if the prefixes differ.
  talkGadgetHostJs = talkGadgetHostPrefix + talkGadgetHostSuffix
  talkGadgetBaseUrl = talkGadgetHostJs + '/talkgadget/'
  if talkGadgetHostPrefix == oauth2RedirectHostPrefix:
    talkGadgetHostJson = talkGadgetHostJs
  else:
    talkGadgetHostJson = 'https://*.' + talkGadgetHostSuffix

  # Set the correct OAuth2 redirect URL.
  oauth2RedirectHostJs = oauth2RedirectHostPrefix + talkGadgetHostSuffix
  oauth2RedirectHostJson = talkGadgetHostJson
  oauth2RedirectPath = '/talkgadget/oauth/chrome-remote-desktop'
  oauth2RedirectBaseUrlJs = oauth2RedirectHostJs + oauth2RedirectPath
  oauth2RedirectBaseUrlJson = oauth2RedirectHostJson + oauth2RedirectPath
  if buildtype == 'Official':
    oauth2RedirectUrlJs = ("'" + oauth2RedirectBaseUrlJs +
                           "/rel/' + chrome.i18n.getMessage('@@extension_id')")
    oauth2RedirectUrlJson = oauth2RedirectBaseUrlJson + '/rel/*'
  else:
    oauth2RedirectUrlJs = "'" + oauth2RedirectBaseUrlJs + "/dev'"
    oauth2RedirectUrlJson = oauth2RedirectBaseUrlJson + '/dev*'
  thirdPartyAuthUrlJs = oauth2RedirectBaseUrlJs + '/thirdpartyauth'
  thirdPartyAuthUrlJson = oauth2RedirectBaseUrlJson + '/thirdpartyauth*'
  xmppServer = os.environ.get('XMPP_SERVER', 'talk.google.com:443')

  if not is_app_remoting_webapp:
    replaceString(destination, 'TALK_GADGET_URL', talkGadgetBaseUrl)
    findAndReplace(os.path.join(destination, 'plugin_settings.js'),
                   "'OAUTH2_REDIRECT_URL'", oauth2RedirectUrlJs)

    # Configure xmpp server and directory bot settings in the plugin.
    replaceBool(
        destination, 'XMPP_SERVER_USE_TLS',
        getenvBool('XMPP_SERVER_USE_TLS', True))
    replaceString(destination, 'XMPP_SERVER', xmppServer)
    replaceString(destination, 'DIRECTORY_BOT_JID',
                  os.environ.get('DIRECTORY_BOT_JID',
                                 'remoting@bot.talk.google.com'))
    replaceString(destination, 'THIRD_PARTY_AUTH_REDIRECT_URL',
                  thirdPartyAuthUrlJs)

  # Set the correct API keys.
  # For overriding the client ID/secret via env vars, see google_api_keys.py.
  apiClientId = google_api_keys.GetClientID('REMOTING')
  apiClientSecret = google_api_keys.GetClientSecret('REMOTING')
  apiKey = google_api_keys.GetAPIKeyRemoting()

  if is_app_remoting_webapp and buildtype != 'Dev':
    if not app_client_id:
      raise Exception('Invalid app_client_id passed in: "' +
          app_client_id + '"')
    apiClientIdV2 = app_client_id + '.apps.googleusercontent.com'
  else:
    apiClientIdV2 = google_api_keys.GetClientID('REMOTING_IDENTITY_API')

  if not is_app_remoting_webapp:
    replaceString(destination, 'API_CLIENT_ID', apiClientId)
    replaceString(destination, 'API_CLIENT_SECRET', apiClientSecret)
    replaceString(destination, 'API_KEY', apiKey)

  # Write the application capabilities.
  if is_app_remoting_webapp:
    appCapabilities = ','.join(
        ['remoting.ClientSession.Capability.' + x for x in app_capabilities])
    findAndReplace(os.path.join(destination, 'arv_main.js'),
                   "'APPLICATION_CAPABILITIES'", appCapabilities)

  # Use a consistent extension id for dev builds.
  # AppRemoting builds always use the dev app id - the correct app id gets
  # written into the manifest later.
  if is_app_remoting_webapp:
    if buildtype != 'Dev':
      if not manifest_key:
        raise Exception('Invalid manifest_key passed in: "' +
            manifest_key + '"')
      manifestKey = '"key": "' + manifest_key + '",'
    else:
      manifestKey = '"key": "remotingdevbuild",'
  elif buildtype != 'Official':
    # TODO(joedow): Update the chromoting webapp GYP entries to include keys.
    manifestKey = '"key": "remotingdevbuild",'
  else:
    manifestKey = ''

  # Generate manifest.
  if manifest_template:
    context = {
        'webapp_type': webapp_type,
        'FULL_APP_VERSION': version,
        'MANIFEST_KEY_FOR_UNOFFICIAL_BUILD': manifestKey,
        'OAUTH2_REDIRECT_URL': oauth2RedirectUrlJson,
        'TALK_GADGET_HOST': talkGadgetHostJson,
        'THIRD_PARTY_AUTH_REDIRECT_URL': thirdPartyAuthUrlJson,
        'REMOTING_IDENTITY_API_CLIENT_ID': apiClientIdV2,
        'OAUTH2_BASE_URL': oauth2BaseUrl,
        'OAUTH2_API_BASE_URL': oauth2ApiBaseUrl,
        'DIRECTORY_API_BASE_URL': directoryApiBaseUrl,
        'TELEMETRY_API_BASE_URL':telemetryApiBaseUrl ,
        'APP_REMOTING_API_BASE_URL': appRemotingApiBaseUrl,
        'OAUTH2_ACCOUNTS_HOST': oauth2AccountsHost,
        'GOOGLE_API_HOSTS': googleApiHosts,
        'APP_NAME': app_name,
        'APP_DESCRIPTION': app_description,
        'OAUTH_GDRIVE_SCOPE': '',
        'USE_GCD': use_gcd,
        'XMPP_SERVER': xmppServer,
    }
    if 'GOOGLE_DRIVE' in app_capabilities:
      context['OAUTH_GDRIVE_SCOPE'] = ('"https://docs.google.com/feeds/", '
                                       '"https://www.googleapis.com/auth/drive",')
    processJinjaTemplate(manifest_template,
                         jinja_paths,
                         os.path.join(destination, 'manifest.json'),
                         context)

  # Make the zipfile.
  createZip(zip_path, destination)

  return 0

def main():
  parser = argparse.ArgumentParser()
  parser.add_argument('buildtype')
  parser.add_argument('version')
  parser.add_argument('destination')
  parser.add_argument('zip_path')
  parser.add_argument('manifest_template')
  parser.add_argument('webapp_type')
  parser.add_argument('files', nargs='*', metavar='file', default=[])
  parser.add_argument('--app_name', metavar='NAME')
  parser.add_argument('--app_description', metavar='TEXT')
  parser.add_argument('--app_capabilities',
                      nargs='*', default=[], metavar='CAPABILITY')
  parser.add_argument('--appid')
  parser.add_argument('--app_client_id', default='')
  parser.add_argument('--manifest_key', default='')
  parser.add_argument('--files_listfile', default='', metavar='PATH')
  parser.add_argument('--locales_listfile', default='', metavar='PATH')
  parser.add_argument('--jinja_paths', nargs='*', default=[], metavar='PATH')
  parser.add_argument('--service_environment', default='', metavar='ENV')
  parser.add_argument('--use_gcd', choices=['0', '1'], default='0')

  args = parser.parse_args()
  args.use_gcd = (args.use_gcd != '0')
  args.app_capabilities = set(args.app_capabilities)
  return buildWebApp(**vars(args))

if __name__ == '__main__':
  sys.exit(main())


text:
bitcoinjs-db-reset(1) -- delete all data
========================================

## SYNOPSIS

    bitcoinjs db-reset [--config=<path>]

## OPTIONS

  * `-c` <file>, `--config`=<file>:
    Path to config file.

  * `-h`, `--help`:
    Inline command help.

## DESCRIPTION

Delete's all collections (tables) from the mongodb database. You need
to run this command if you want to switch networks.

Note that it is recommended that you reset the database and
re-download the block chain when upgrading bitcoin-p2p.

redpajama_set_name: RedPajamaGithub


text:
var MongoClient = require('mongodb').MongoClient;
var assert = require('assert');

var insertDocuments = function(db, callback) {
    var collection = db.collection('documents');
    collection.insert([
        {a : 1}, {a : 2}, {a : 3}
    ], function(err, result) {
        assert.equal(err, null);
        assert.equal(3, result.result.n);
        assert.equal(3, result.ops.length);
        console.log("--Inserted 3 documents into the document collection");
        callback(result);
    });
};

var updateDocument = function(db, callback) {
    var collection = db.collection('documents');
    collection.update({ a : 2 }, { $set: { b : 1 } }, function(err, result) {
        assert.equal(err, null);
        assert.equal(1, result.result.n);
        console.log("--Updated the document with the field a equal to 2");
        callback(result);
    });
};

var removeDocument = function(db, callback) {
    var collection = db.collection('documents');
    collection.remove({ a : 3 }, function(err, result) {
        assert.equal(err, null);
        assert.equal(1, result.result.n);
        console.log("--Removed the document with the field a equal to 3");
        callback(result);
    });
};

var findDocuments = function(db, callback) {
    // Get the documents collection
    var collection = db.collection('documents');
    // Find some documents
    collection.find({}).toArray(function(err, docs) {
        assert.equal(err, null);
        assert.equal(2, docs.length);
        console.log("--Found the following records");
        console.dir(docs);
        callback(docs);
    });
};

var url = 'mongodb://localhost:27017/myproject';
MongoClient.connect(url, function(err, db) {
    assert.equal(null, err);
    console.log("Connected correctly to server");

    insertDocuments(db, function (){
        updateDocument(db, function(){
            removeDocument(db, function() {
                findDocuments(db, function(){
                    db.close();
                });
            });
        });
    });

});


text:
#include <tvm/relay/op.h>
#include <tvm/relay/attrs/transform.h>
#include <tvm/ir_operator.h>
#include <vector>
#include "../op_common.h"

namespace tvm {
namespace relay {

/* relay.expand_dims */

TVM_REGISTER_NODE_TYPE(ExpandDimsAttrs);

bool ExpandDimsRel(const Array<Type>& types,
                   int num_inputs,
                   const Attrs& attrs,
                   const TypeReporter& reporter) {
  // `types` contains: [data, result]
  CHECK_EQ(types.size(), 2);
  const auto* data = types[0].as<TensorTypeNode>();
  if (data == nullptr) {
    return false;
  }
  const auto* param = attrs.as<ExpandDimsAttrs>();
  const int ndim = static_cast<int>(data->shape.size());
  const int axis = param->axis;
  const int num_newaxis = param->num_newaxis;
  CHECK(num_newaxis >= 0)
    << "expand_dims only accepts `num_newaxis >= 0`"
    << ", but got num_newaxis = " << num_newaxis;
  CHECK(-ndim - 1 <= axis && axis <= ndim)
    << "expand_dims only accepts `axis` in [-data.ndim - 1, data.ndim]"
    << ", but got axis = " << axis
    << ", and data.ndim = " << ndim;
  const int pivot = axis < 0 ? ndim + axis + 1 : axis;
  std::vector<IndexExpr> oshape;
  oshape.reserve(ndim + num_newaxis);
  for (int i = 0; i < pivot; ++i) {
    oshape.emplace_back(data->shape[i]);
  }
  for (int i = 0; i < num_newaxis; ++i) {
    oshape.emplace_back(1);
  }
  for (int i = pivot; i < ndim; ++i) {
    oshape.emplace_back(data->shape[i]);
  }
  reporter->Assign(types[1], TensorTypeNode::make(oshape, data->dtype));
  return true;
}

Expr MakeExpandDims(Expr data,
                    int axis,
                    int num_newaxis) {
  auto attrs = make_node<ExpandDimsAttrs>();
  attrs->axis = axis;
  attrs->num_newaxis = num_newaxis;
  static const Op& op = Op::Get("expand_dims");
  return CallNode::make(op, {data}, Attrs(attrs), {});
}

TVM_REGISTER_API("relay.op._make.expand_dims")
.set_body([](const TVMArgs& args, TVMRetValue* rv) {
    runtime::detail::unpack_call<Expr, 3>(MakeExpandDims, args, rv);
});

RELAY_REGISTER_OP("expand_dims")
.describe(R"code(Insert `num_newaxis` axises at the position given by `axis`

- **data**: The input data to the operator.

)code" TVM_ADD_FILELINE)
.set_num_inputs(1)
.add_argument("data", "Tensor", "The input tensor.")
.set_support_level(1)
.add_type_rel("ExpandDims", ExpandDimsRel);

/* relay.concatenate */

TVM_REGISTER_NODE_TYPE(ConcatenateAttrs);

bool ConcatenateRel(const Array<Type>& types,
                    int num_inputs,
                    const Attrs& attrs,
                    const TypeReporter& reporter) {
  // types: [data, result]
  CHECK_EQ(types.size(), 2);
  const auto* tensor_tuple = types[0].as<TupleTypeNode>();
  if (tensor_tuple == nullptr) {
    return false;
  }
  const auto* param = attrs.as<ConcatenateAttrs>();
  const auto& first = Downcast<TensorType>(tensor_tuple->fields[0]);
  // Sanity check: ndim and dtype.
  const int ndim = static_cast<int>(first->shape.size());
  const DataType dtype = first->dtype;
  for (const Type& ele : tensor_tuple->fields) {
    const auto& e = Downcast<TensorType>(ele);
    int e_ndim = static_cast<int>(e->shape.size());
    const DataType& e_dtype = e->dtype;
    CHECK_EQ(e_ndim, ndim) << "relay.concatenate requires all tensors have the same ndim";
    CHECK_EQ(e_dtype, dtype) << "relay.concatenate requires all tensors have the same dtype";
  }
  // Sanity check: axis
  int axis = param->axis;
  CHECK(-ndim <= axis && axis < ndim)
    << "concatenate only accepts `axis` in [-ndim, ndim)"
    << ", but got axis = " << axis
    << ", and ndim = " << ndim;
  axis = axis < 0 ? ndim + axis : axis;
  // Calculate shape
  std::vector<IndexExpr>&& oshape = AsVector(first->shape);
  IndexExpr &concat_dim = oshape[axis];
  for (int i = 1; i < static_cast<int>(tensor_tuple->fields.size()); ++i) {
    const auto& e = Downcast<TensorType>(tensor_tuple->fields[i]);
    concat_dim += e->shape[axis];
  }
  reporter->Assign(types[1], TensorTypeNode::make(oshape, dtype));
  return true;
}

Expr MakeConcatenate(Expr data,
                     int axis) {
  auto attrs = make_node<ConcatenateAttrs>();
  attrs->axis = axis;
  static const Op& op = Op::Get("concatenate");
  return CallNode::make(op, {data}, Attrs(attrs), {});
}

TVM_REGISTER_API("relay.op._make.concatenate")
.set_body([](const TVMArgs& args, TVMRetValue* rv) {
    runtime::detail::unpack_call<Expr, 2>(MakeConcatenate, args, rv);
});

RELAY_REGISTER_OP("concatenate")
.describe(R"code(Concatenate the input tensors along the given axis.

- **data** : A list of tensors.

- **axis** : The axis along which the tensors are concatenated.

)code" TVM_ADD_FILELINE)
.set_num_inputs(1)
.add_argument("data", "Tensor", "The input list of tensors.")
.set_support_level(1)
.add_type_rel("Concatenate", ConcatenateRel);

/* relay.transpose */

bool TransposeRel(const Array<Type>& types,
                  int num_inputs,
                  const Attrs& attrs,
                  const TypeReporter& reporter) {
  // types: [data, result]
  CHECK_EQ(types.size(), 2);
  const auto* data = types[0].as<TensorTypeNode>();
  if (data == nullptr) {
    return false;
  }
  const auto* param = attrs.as<TransposeAttrs>();
  const int ndim = data->shape.size();
  const Array<IndexExpr>& axes = param->axes;
  // check dimension match
  CHECK(axes.empty() || static_cast<int>(axes.size()) == ndim)
    << "Dimension mismatch: axes has " << axes.size() << " elements"
    << ", but data.ndim = " << ndim;
  // construct int_axes
  std::vector<int> int_axes;
  int_axes.reserve(ndim);
  if (axes.empty()) {
    for (int i = ndim - 1; i >= 0; --i) {
      int_axes.push_back(i);
    }
  } else {
    std::vector<int> axis_used(ndim, 0);
    for (const IndexExpr& e : axes) {
      const int64_t *axis_ptr = as_const_int(e);
      CHECK(axis_ptr != nullptr);
      int axis = *axis_ptr;
      // sanity check for axis and ndim
      CHECK(-ndim <= axis && axis < ndim)
        << "transpose only allows each `axis` in `axes` in range [-data.ndim, data.ndim)"
        << ", but got axis = " << axis
        << ", and data.ndim = " << ndim;
      axis = axis < 0 ? axis + ndim : axis;
      // sanity check for duplication
      CHECK(!axis_used[axis]) << "Duplicate axes in transpose: " << axis;
      axis_used[axis] = 1;
      int_axes.push_back(axis);
    }
  }
  std::vector<IndexExpr> oshape;
  oshape.reserve(ndim);
  for (int axis : int_axes) {
    oshape.push_back(data->shape[axis]);
  }
  reporter->Assign(types[1], TensorTypeNode::make(oshape, data->dtype));
  return true;
}

Expr MakeTranspose(Expr data,
                   Array<IndexExpr> axes) {
  auto attrs = make_node<TransposeAttrs>();
  attrs->axes = std::move(axes);
  static const Op& op = Op::Get("transpose");
  return CallNode::make(op, {data}, Attrs(attrs), {});
}

TVM_REGISTER_API("relay.op._make.transpose")
.set_body([](const TVMArgs& args, TVMRetValue* rv) {
    runtime::detail::unpack_call<Expr, 2>(MakeTranspose, args, rv);
});

RELAY_REGISTER_OP("transpose")
.describe(R"code(Permutes the dimensions of an array.

- **data**: The input data to the operator.

- **axes**: The target axes order, reverse order if not specified.

)code" TVM_ADD_FILELINE)
.set_num_inputs(1)
.add_argument("data", "Tensor", "The input tensor.")
.set_support_level(3)
.add_type_rel("Transpose", TransposeRel);

/* relay.reshape */

bool ReshapeRel(const Array<Type>& types,
                int num_inputs,
                const Attrs& attrs,
                const TypeReporter& reporter) {
  // types: [data, result]
  CHECK_EQ(types.size(), 2);
  const auto* data = types[0].as<TensorTypeNode>();
  if (data == nullptr) {
    return false;
  }
  const auto* param = attrs.as<ReshapeAttrs>();
  reporter->Assign(types[1], TensorTypeNode::make(param->newshape, data->dtype));
  return true;
}

Expr MakeReshape(Expr data,
                 Array<IndexExpr> newshape) {
  auto attrs = make_node<ReshapeAttrs>();
  attrs->newshape = std::move(newshape);
  static const Op& op = Op::Get("reshape");
  return CallNode::make(op, {data}, Attrs(attrs), {});
}

TVM_REGISTER_API("relay.op._make.reshape")
.set_body([](const TVMArgs& args, TVMRetValue* rv) {
    runtime::detail::unpack_call<Expr, 2>(MakeReshape, args, rv);
});

RELAY_REGISTER_OP("reshape")
.describe(R"code(Reshapes the input array.

Example::

To give user more convenience in without doing manual shape inference,
some dimensions of the shape can take special values from the set {0, -1, -2, -3, -4}.
The significance of each is explained below:

- ``0``  copy this dimension from the input to the output shape.

Example::

- data.shape = (2,3,4), newshape = (4,0,2), result.shape = (4,3,2)
- data.shape = (2,3,4), newshape = (2,0,0), result.shape = (2,3,4)

- ``-1`` infers the dimension of the output shape by using the remainder of the input dimensions
keeping the size of the new array same as that of the input array.
At most one dimension of shape can be -1.

Example::

- data.shape = (2,3,4), newshape = (6,1,-1), result.shape = (6,1,4)
- data.shape = (2,3,4), newshape = (3,-1,8), result.shape = (3,1,8)
- data.shape = (2,3,4), newshape = (-1,), result.shape = (24,)

- ``-2`` copy all/remainder of the input dimensions to the output shape.

Example::

- data.shape = (2,3,4), newshape = (-2,), result.shape = (2,3,4)
- data.shape = (2,3,4), newshape = (2,-2), result.shape = (2,3,4)
- data.shape = (2,3,4), newshape = (-2,1,1), result.shape = (2,3,4,1,1)

- ``-3`` use the product of two consecutive dimensions of the input shape as the output dimension.

Example::

- data.shape = (2,3,4), newshape = (-3,4), result.shape = (6,4)
- data.shape = (2,3,4,5), newshape = (-3,-3), result.shape = (6,20)
- data.shape = (2,3,4), newshape = (0,-3), result.shape = (2,12)
- data.shape = (2,3,4), newshape = (-3,-2), result.shape = (6,4)

- ``-4`` split one dimension of the input into two dimensions passed subsequent to -4 in shape (can contain -1).

Example::

- data.shape = (2,3,4), newshape = (-4,1,2,-2), result.shape =(1,2,3,4)
- data.shape = (2,3,4), newshape = (2,-4,-1,3,-2), result.shape = (2,1,3,4)

)code" TVM_ADD_FILELINE)
.set_num_inputs(1)
.add_argument("data", "Tensor", "The input tensor.")
.set_support_level(3)
.add_type_rel("Reshape", ReshapeRel);

}  // namespace relay
}  // namespace tvm


text:
package namesilo

import (
	"fmt"
	"net/http"
)

// TokenTransport HTTP transport for API authentication.
type TokenTransport struct {
	apiKey string

	// Transport is the underlying HTTP transport to use when making requests.
	// It will default to http.DefaultTransport if nil.
	Transport http.RoundTripper
}

// NewTokenTransport Creates a HTTP transport for API authentication.
func NewTokenTransport(apiKey string) (*TokenTransport, error) {
	if apiKey == "" {
		return nil, fmt.Errorf("credentials missing: API key")
	}

	return &TokenTransport{apiKey: apiKey}, nil
}

// RoundTrip executes a single HTTP transaction
func (t *TokenTransport) RoundTrip(req *http.Request) (*http.Response, error) {
	enrichedReq := &http.Request{}
	*enrichedReq = *req

	enrichedReq.Header = make(http.Header, len(req.Header))
	for k, s := range req.Header {
		enrichedReq.Header[k] = append([]string(nil), s...)
	}

	if t.apiKey != "" {
		query := enrichedReq.URL.Query()
		query.Set("version", "1")
		query.Set("type", "xml")
		query.Set("key", t.apiKey)
		enrichedReq.URL.RawQuery = query.Encode()
	}

	return t.transport().RoundTrip(enrichedReq)
}

// Client Creates a new HTTP client
func (t *TokenTransport) Client() *http.Client {
	return &http.Client{Transport: t}
}

func (t *TokenTransport) transport() http.RoundTripper {
	if t.Transport != nil {
		return t.Transport
	}
	return http.DefaultTransport
}


text:
import os
import shimehari
import unittest
from werkzeug.routing import Rule
from shimehari.testsuite import ShimehariTestCase
from shimehari.configuration import ConfigManager, Config
from shimehari.routing import Router, Resource
from shimehari.controllers import ApplicationController

testConfig = Config('development', {'AUTO_SETUP': False, 'SERVER_NAME': 'localhost', 'PREFERRED_URL_SCHEME': 'https'})

class TestController(ApplicationController):
    def index(self, *args, **kwargs):
        return 'Shimehari nomitai.'

class ShimehariAppTestCase(ShimehariTestCase):
    def testGotFirstRequest(self):
        ConfigManager.addConfig(testConfig)
        app = shimehari.Shimehari(__name__)
        self.assertEqual(app.gotFirstRequest, False)

        def returnHello(*args, **kwargs):
            return 'Hello'
        app.router = shimehari.Router([Rule('/hell', endpoint='returnHello', methods=['POST'])])
        app.controllers['returnHello'] = returnHello
        c = app.testClient()
        c.get('/hell', content_type='text/planetext')
        self.assert_(app.gotFirstRequest)

    #u---mu
    def testLogger(self):
        ConfigManager.addConfig(testConfig)
        app = shimehari.Shimehari(__name__)
        self.assert_(type(app.logger))

    def testGetConfig(self):
        ConfigManager.addConfig(testConfig)
        app = shimehari.Shimehari(__name__)
        self.assertEqual(app.getConfig(), testConfig)

    def testSetControllerFromRouter(self):
        ConfigManager.addConfig(testConfig)
        app = shimehari.Shimehari(__name__)
        self.assertEqual(app.controllers, {})
        router = Router([Resource(TestController, root=True)])
        app.setControllerFromRouter(router)
        self.assertNotEqual(app.controllers, {})

    def testAddController(self):
        ConfigManager.addConfig(testConfig)
        app = shimehari.Shimehari(__name__)
        self.assertEqual(app.controllers, {})
        app.addController(TestController)
        self.assertNotEqual(app.controllers, {})

    def testAddRoute(self):
        ConfigManager.addConfig(testConfig)
        app = shimehari.Shimehari(__name__)
        self.assertEqual(app.controllers, {})
        self.assertEqual(app.router._rules, [])

        def index(*args, **kwargs):
            return 'Sake nomitai.'
        app.addRoute('/', index)
        c = app.testClient()
        rv = c.get('/', content_type='text/html')
        self.assertEqual(rv.status_code, 200)
        self.assert_('Sake nomitai.' in rv.data)

    def testSetup(self):
        # ConfigManager.addConfig(testConfig)
        ConfigManager.removeConfig('development')
        ConfigManager.addConfig(Config('development', {'AUTO_SETUP': False, 'SERVER_NAME': 'localhost', 'PREFERRED_URL_SCHEME': 'https'}))
        app = shimehari.Shimehari(__name__)
        app.appPath = os.path.join(app.rootPath, 'testApp')
        app.appFolder = 'shimehari.testsuite.testApp'
        app.setupTemplater()
        app.setupBindController()
        app.setupBindRouter()
        self.assertNotEqual(app.controllers, {})
        self.assertNotEqual(app.router._rules, {})
        pass

    def testTryTriggerBeforeFirstRequest(self):
        ConfigManager.removeConfig('development')
        ConfigManager.addConfig(testConfig)
        app = shimehari.Shimehari(__name__)

        app.testCnt = 0

        @app.beforeFirstRequest
        def doFirst():
            app.testCnt = app.testCnt + 1
            return app.testCnt

        def returnHello(*args, **kwargs):
            return 'Hello'
        app.router = shimehari.Router([Rule('/hell', endpoint='returnHello', methods=['POST'])])
        app.controllers['returnHello'] = returnHello
        c = app.testClient()
        self.assertEqual(app.testCnt, 0)
        c.get('/hell', content_type='text/planetext')
        self.assertEqual(app.testCnt, 1)
        c.get('/hell', content_type='text/planetext')
        self.assertEqual(app.testCnt, 1)

    def testPreprocessRequest(self):
        ConfigManager.removeConfig('development')
        ConfigManager.addConfig(testConfig)
        app = shimehari.Shimehari(__name__)

        app.testCnt = 0

        @app.beforeRequest
        def doRequest():
            app.testCnt = app.testCnt + 1
            return app.testCnt

        def returnHello(*args, **kwargs):
            return 'Hello'
        app.router = shimehari.Router([Rule('/hell', endpoint='returnHello', methods=['POST'])])
        app.controllers['returnHello'] = returnHello
        c = app.testClient()
        self.assertEqual(app.testCnt, 0)
        c.get('/hell', content_type='text/planetext')
        self.assertEqual(app.testCnt, 1)
        c.get('/hell', content_type='text/planetext')
        self.assertEqual(app.testCnt, 2)

    def testProcessResponse(self):
        ConfigManager.removeConfig('development')
        ConfigManager.addConfig(testConfig)
        app = shimehari.Shimehari(__name__)

        app.testCnt = 0

        @app.afterRequest
        def doRequest(res):
            app.testCnt = app.testCnt + 1
            return res

        def returnHello(*args, **kwargs):
            return 'Hello'
        app.router = shimehari.Router([Rule('/hell', endpoint='returnHello', methods=['POST'])])
        app.controllers['returnHello'] = returnHello
        c = app.testClient()
        self.assertEqual(app.testCnt, 0)
        c.get('/hell', content_type='text/planetext')
        self.assertEqual(app.testCnt, 1)
        c.get('/hell', content_type='text/planetext')
        self.assertEqual(app.testCnt, 2)

def suite():
    suite = unittest.TestSuite()
    suite.addTest(unittest.makeSuite(ShimehariAppTestCase))
    return suite


text:
var ipc=require('../../../node-ipc');

/***************************************\
 *
 * You should start both hello and world
 * then you will see them communicating.
 *
 * *************************************/

ipc.config.id = 'world';
ipc.config.retry= 1500;
ipc.config.tls={
    public: __dirname+'/../../../local-node-ipc-certs/server.pub',
    private: __dirname+'/../../../local-node-ipc-certs/private/server.key'
};

var messages={
    goodbye:false,
    hello:false
};

ipc.serveNet(
    function(){
        ipc.server.on(
            'app.message',
            function(data,socket){
                ipc.log('got a message from'.debug, (data.id).variable, (data.message).data);
                messages[data.id]=true;
                ipc.server.emit(
                    socket,
                    'app.message',
                    {
                        id      : ipc.config.id,
                        message : data.message+' world!'
                    }
                );

                if(messages.hello && messages.goodbye){
                    ipc.log('got all required events, telling clients to kill connection'.good);
                    ipc.server.broadcast(
                        'kill.connection',
                        {
                            id:ipc.config.id
                        }
                    );
                }
            }
        );
    }
);

ipc.server.start();


text:
require 'sinatra/base'
require 'json'
module WaltersApi
  class Server < Sinatra::Base
    configure do
      enable :static
      set :public_folder, 'public'
    end
    get %r{/places/([\w-]+)(?:\.json)?} do
      content_type :json
      Parser.place(params[:captures].first).to_json
    end
    get %r{/places(?:\.json)?} do
      content_type :json
      Parser.places.to_json
    end
    get %r{/mediums/([\w-]+)(?:\.json)?} do
      content_type :json
      Parser.medium(params[:captures].first, params[:page]).to_json
    end
    get %r{/mediums(?:\.json)?} do
      content_type :json
      Parser.mediums.to_json
    end
    get %r{/creators(?:/([a-z]))?(?:\.json)$?} do
      content_type :json
      Parser.creators(params[:captures] && params[:captures].first).to_json
    end
    get %r{/creators/([\w-]+)(?:\.json)$?} do
      content_type :json
      Parser.creator(params[:captures].first, params[:page]).to_json
    end
    get %r{/tags(?:/([a-z]))?(?:\.json)?$} do
      content_type :json
      Parser.tags(params[:captures] && params[:captures].first).to_json
    end
    get %r{/tags/([\w-]+)(?:.json)?$} do
      content_type :json
      Parser.tag(params[:captures].first).to_json
    end
    get %r{/locations/([\w-]+)(?:\.json)?$} do
      content_type :json
      id = params[:captures].first
      location = Parser.locations.find { |l| l[:id] == id }
      Parser.location(id,params[:page]).merge(location).to_json
    end
    get '/locations.?:format?' do
      content_type :json
      Parser.locations.to_json
    end
    get %r{/pieces/(\d+)(?:\.json)?$} do
      content_type :json
      id = params[:captures].first
      Parser.get(id).to_json
    end
  end
end


text:
(function () {
  'use strict';

  angular
    .module('assesments')
    .controller('ReportAssesmentController', ReportAssesmentController);

  ReportAssesmentController.$inject = ['AssesmentsService', 'ProfessorsService', 'StudentsService', 'Authentication', '$http', '$state', 'assignmentResolve', 'Notification'];

  function ReportAssesmentController(AssesmentsService, ProfessorsService, StudentsService, Authentication, $http, $state, assignment, Notification) {
    var vm = this;
    vm.authentication = Authentication;
    vm.professor = vm.authentication.user;
    vm.assignment = assignment;
    vm.course = vm.assignment.course;
    vm.assesmentTest = 'cia1';
    vm.assesments = {};
    vm.isLoading = false;

    /**
     * Fetch assesment records for the test
     */
    vm.fetchAssesments = function() {
      vm.assesments = {};
      vm.isLoading = true;

      var assesmentPromise = AssesmentsService.getAssesments({
        batch: vm.assignment.batch,
        courseId: vm.course._id,
        test: vm.assesmentTest
      }).$promise;

      Promise.all([assesmentPromise]).then(function(resps) {
        var assesments = resps[0];

        assesments.forEach(function (item) {
          AssesmentsService.get({
            assesmentId: item._id
          });
        });

        vm.assesments = assesments;

        vm.isLoading = false;
      }).catch(function(reason) {
        Notification.error({ title: 'Something went wrong :(', message: reason, delay: 3000 });
        vm.isLoading = false;
      });

    };

  }
}());


text:
<?php

namespace app\components;

use yii;
use yii\db\ActiveRecord;
use yii\filters\VerbFilter;
use yii\web\NotFoundHttpException;

abstract class BaseAdminCrudController extends BaseAdminController
{

    /**
     * Provides model class name for CRUD
     * @return string
     */
    abstract protected function getModelClass();

    /**
     * Provides search model class name for CRUD
     * @return string
     */
    abstract protected function getSearchModelClass();

    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * Finds the model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return ActiveRecord the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        $class = $this->getModelClass();

        if (($model = $class::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }

    /**
     * Called after successfull model saving
     * @param ActiveRecord $model
     * @return bool
     */
    protected  function saveModel(ActiveRecord $model) {
        return true;
    }

    /**
     * Lists all models.
     * @return mixed
     */
    public function actionIndex()
    {
        $class = $this->getSearchModelClass();

        $searchModel = new $class();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

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

    /**
     * Displays a single model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Deletes an existing model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Creates a new model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $class = $this->getModelClass();

        $model = new $class();

        if ($model->load(Yii::$app->request->post()) && $model->save() && $this->saveModel($model)) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Updates an existing model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post()) && $model->save() && $this->saveModel($model)) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }

}


text:
class ShadingGroup;

static std::vector<MObject> mtm_MayaSGList;
static std::vector<ShadingGroup> mtm_ShadingGroups;

void getObjectShadingGroups(MObject& geoObject);
void getObjectShadingGroups(MDagPath& shapeObjectDP);
bool getObjectShadingGroups(MObject& geoObject, MObject& sGroup, int instId);
bool getShadingGroup(MObject& shadingGroupObject, ShadingGroup& sg);
bool getObjectShadingGroups(MDagPath& shapeObjectDP, MObject& shadingGroup);
void clearObjectShadingGroups();
bool exportShadingGroups();
void clearShaderNodes();

class ShadingGroup
{
public:
	MObject mobject;
	MString name;
	ShaderNode surfaceShader;
	MString surfaceFileName;
	ShaderNode displacementShader;
	MString displacementFileName;
	ShaderNode volumeShader;
	MString volumeFileName;
	std::vector<ShaderPlug> surfaceExternalPlugs;
	std::vector<ShaderNode> surfaceNodeList;
	std::vector<ShaderPlug> displacementExternalPlugs;
	std::vector<ShaderNode> displacementNodeList;
	std::vector<ShaderPlug> volumeExternalPlugs;
	std::vector<ShaderNode> volumeNodeList;

	ShadingGroup();
	ShadingGroup(MObject& sGroup);
	~ShadingGroup();

	void parseTree();
	void exportVfl();
	bool compileShader();
	bool recursiveReadConnections(ShaderNode& sn, std::vector<ShaderNode>& nodeList, std::vector<ShaderPlug>& externalPlugs);
	//bool recursiveReadConnections(ShaderNode& sn);
	//void writeNodeExternalPlugs( std::ofstream& outFile);
	void writeNodeExternalPlugs( std::ofstream& outFile, std::vector<ShaderPlug>& externalPlugs);
};

#endif

//
//#include <vector>
//
//#include "mtm_renderOptions.h"
//
//class HyperShade;
//
//class ShadingTree
//{
//public:
//	RenderOptions *renderGlobals;
//	HyperShade *hyperShade;
//	std::vector<ShaderNode> treeNodes;
//	MObject shadingGroup;
//	MString shaderCmd;
//	MString outFile;
//	std::vector<ShaderPlug> shaderCmdPlugs;
//	ShadingTree(RenderOptions *ro);
//	ShadingTree(RenderOptions *ro, MObject& object, ShaderType type);
//	ShaderType shaderType;
//	bool isValid;
//	MString name;
//	MString typeAndName;
//
//	ShadingTree();
//	~ShadingTree();
//
//	MObject getShadingGroup(MObject& geoNode);
//	bool readShadingTree(MObject& geoNode);
//	bool recursiveReadConnections(MObject& object);
//	bool recursiveReadConnections(MObject& object, ShaderNode& sn);
//	bool exportShadingTree();
//	bool compileShader();
//	bool isNodeSupported( MObject& object, ShaderNode& sn);
//	bool isOutPlugSupported( ShaderNode& sn, MString plugName);
//	bool isOutPlugSupported( ShaderNode& sn, MString plugName, int *inPlugId, int *inSubId);
//	bool isInPlugSupported( ShaderNode& sn, MString plugName, int *plugId, int *subId);
//	bool isInPlugSupported( ShaderNode& sn, MString plugName);
//	void getPlugAttrs( ShaderNode& sn);
//	void defineOutputAttrs( ShaderNode& sn, std::ofstream& shaderFile);
//	MString houdiniType(PlugType type );
//	bool isShadingNode( MObject& object);
//	MString makeStringFromPlugList();
//	MString makeCmdStringFromPlugList();
//	MString getPlugAttrAsString( ShaderPlug pl);
//};
//
//class Material{
//public:
//	ShadingTree surfaceShader;
//	ShadingTree volumeShader;
//	ShadingTree displacementShader;
//};
//
//class HyperShade
//{
//public:
//	RenderOptions *renderGlobals;
//	std::vector<MObject> objectList;
//	std::vector<Material *> materialList;
//
//	HyperShade();
//	HyperShade(RenderOptions *opt);
//	~HyperShade();
//	std::vector<Material *> appendNode(MObject object);
//	void exportShader();
//};
//
//#endif


text:
package com.intellij.uiDesigner.lw;

import com.intellij.uiDesigner.UIFormXmlConstants;
import org.jdom.Element;

import java.awt.*;

public final class FlowLayoutSerializer extends LayoutSerializer {
  public static final FlowLayoutSerializer INSTANCE = new FlowLayoutSerializer();

  private FlowLayoutSerializer() {
  }

  @Override
  void readLayout(Element element, LwContainer container) {
    final int hGap = LwXmlReader.getOptionalInt(element, UIFormXmlConstants.ATTRIBUTE_HGAP, 5);
    final int vGap = LwXmlReader.getOptionalInt(element, UIFormXmlConstants.ATTRIBUTE_VGAP, 5);
    final int flowAlign = LwXmlReader.getOptionalInt(element, UIFormXmlConstants.ATTRIBUTE_FLOW_ALIGN, FlowLayout.CENTER);
    container.setLayout(new FlowLayout(flowAlign, hGap, vGap));
  }

  @Override
  void readChildConstraints(final Element constraintsElement, final LwComponent component) {
  }
}


text:
Demote groups
---------------------------------------------------------------------------
When a chief of police gets demoted you don't want them to be banned from becoming civil protection officer as well.
That is what demote groups are for.

When someone in a group is demoted, they will be banned from EVERY job in the group.
The examples shown below are the default demote groups

HOW TO CREATE A DEMOTE GROUP:
DarkRP.createDemoteGroup("Name of the group", {TEAM1, TEAM2})
---------------------------------------------------------------------------]]

-- Example: DarkRP.createDemoteGroup("Cops", {TEAM_POLICE, TEAM_CHIEF})
-- Example: DarkRP.createDemoteGroup("Gangsters", {TEAM_GANG, TEAM_MOB})

DarkRP.createDemoteGroup("Cops", {TEAM_POLICE, TEAM_CHIEF})
DarkRP.createDemoteGroup("Gangsters", {TEAM_GANG, TEAM_GANGLEADER})
DarkRP.createDemoteGroup("Triads", {TEAM_TRIAD, TEAM_TRIADLEADER})
DarkRP.createDemoteGroup("Mafia", {TEAM_MAFIA, TEAM_MOB})


text:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <title>Outline Mail - Making HTML email easy.</title>
    <meta name="description" content="" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />

    <link rel="shortcut icon" href="favicon.ico" />
    <link rel="apple-touch-icon-precomposed" href="favicon-152.png" />
    <meta name="msapplication-TileColor" content="#38a1d6" />
    <meta name="msapplication-TileImage" content="favicon-152.png" />

    <link
      href="//fonts.googleapis.com/css?family=Lato:400,700,900|Merriweather:400,400italic,700,700italic"
      rel="stylesheet"
      type="text/css"
    />

    <link href="css/outline.min.css" media="all" rel="stylesheet" type="text/css" />

                  Home

                  Get started

                  View on GitHub

                  Outline CSS framework

Making HTML email ridiculously easy.

            Outline Mail is an email framework with a bunch of fully trusted responsive components
            to provide you a solid foundation for your HTML email project.

          Download

          Get started

Version 0.3

Lovely looking email, on every device

Mix and match responsive email components

          Outline Mail is HTML email framework with a bunch of fully tested responsive components to
          provide you a solid foundation for your HTML email project.

              It allows you to mix and match content blocks to easily build an HTML email using
              todays best practices in minutes.

              You can let Gulp do its magic if you are in to that,
              or simply copy & paste the component code into the master layout file.

Outline Mail's components are tested in Litmus in over 30+ email clients.

              Outline Mail's library of email components will keep on growing! If you have any
              requests please get in touch.

Follow these easy steps

Choose.

              Choose a header, main content and footer blocks from the component list.

Build.

              Let Gulp do the hard work for you, just include the correct component blocks into the
              main layout file.

              Alternatively copy and paste the raw component block HTML into the main layout file.

Edit.

Put your text and image content into the email.

Test.

              Test it in as many email clients as possible... I have used Litmus to test on a number
              of devices. You should too.

Send.

Your email is ready to send!

          Get started

          Do you want to help make Outline Mail awesome?

        Check out the repo

        Report an issue

        Outline Mail is a project by Matt Harris


text:
using System;
using Com.Aspose.Slides.Api;
using Com.Aspose.Slides.Model;
using Com.Aspose.Storage.Api;

namespace Slides
{
    class DetectAllSlides
    {
        public static void Run()
        {
            // ExStart:1
            SlidesApi slidesApi = new SlidesApi(Common.APP_KEY, Common.APP_SID, Common.BASEPATH);
            StorageApi storageApi = new StorageApi(Common.APP_KEY, Common.APP_SID, Common.BASEPATH);

            String fileName = "sample-input.pptx";
            String folder = "";
            String storage = "";

            try
            {
                // Upload source file to aspose cloud storage
                storageApi.PutCreate(fileName, "", "", System.IO.File.ReadAllBytes(Common.GetDataDir() + fileName));

                // Invoke Aspose.Slides Cloud SDK API to detect all slides from a presentation
                SlideListResponse apiResponse = slidesApi.DeleteSlidesCleanSlidesList(fileName, folder, storage);

                if (apiResponse != null && apiResponse.Status.Equals("OK"))
                {
                    Com.Aspose.Storage.Model.ResponseMessage storageRes = storageApi.GetDownload(fileName, null, null);
                    System.Diagnostics.Debug.WriteLine("response:" + storageRes.ResponseStream);
                    System.IO.File.WriteAllBytes(Common.GetDataDir() + fileName, storageRes.ResponseStream);
                    Console.WriteLine("Delete All Slides from a PowerPoint Presentation, Done!");
                    Console.ReadKey();
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine("error:" + ex.Message + "\n" + ex.StackTrace);

            }
            // ExEnd:1
        }
    }
}