text:
namespace chromeos {
namespace platform_keys {

// Supported key types.
enum class KeyType { kRsassaPkcs1V15, kEcdsa };

// Supported key attribute types.
enum class KeyAttributeType { kCertificateProvisioningId, kKeyPermissions };

// Supported hash algorithms.
enum HashAlgorithm {
  HASH_ALGORITHM_NONE,  // The value if no hash function is selected.
  HASH_ALGORITHM_SHA1,
  HASH_ALGORITHM_SHA256,
  HASH_ALGORITHM_SHA384,
  HASH_ALGORITHM_SHA512
};

// Supported token IDs.
// A token is a store for keys or certs and can provide cryptographic
// operations.
// ChromeOS provides itself a user token and conditionally a system wide token.
enum class TokenId { kUser, kSystem };

// The service possible statuses.
// For every platform keys service operation callback, a status is passed
// signaling the success or failure of the operation.
enum class Status {
  kSuccess,
  kErrorAlgorithmNotSupported,
  kErrorAlgorithmNotPermittedByCertificate,
  kErrorCertificateNotFound,
  kErrorCertificateInvalid,
  kErrorInputTooLong,
  kErrorGrantKeyPermissionForExtension,
  kErrorInternal,
  kErrorKeyAttributeRetrievalFailed,
  kErrorKeyAttributeSettingFailed,
  kErrorKeyNotAllowedForSigning,
  kErrorKeyNotFound,
  kErrorShutDown,
  // kNetError* are for errors occurred during net::* operations.
  kNetErrorAddUserCertFailed,
  kNetErrorCertificateDateInvalid,
  kNetErrorCertificateInvalid,
};

// These strings can be used to be passed to extensions as well as for logging
// purposes.
// Note: Do not change already existing status-to-string translations, since
// extensions may hardcode specific messages.
std::string StatusToString(Status status);

// Convert platform_keys::Status into a KeystoreError. Status::kSuccess should
// not be passed in the function.
crosapi::mojom::KeystoreError StatusToKeystoreError(Status status);

// Creates platform_keys::Status into a KeystoreError. Keystore specific errors
// are not supported and should be processed separately.
Status StatusFromKeystoreError(crosapi::mojom::KeystoreError error);

// Converts KeystoreError code into an error message.
// Note: Do not change already existing error-to-string translations, since
// extensions may hardcode specific messages.
std::string KeystoreErrorToString(crosapi::mojom::KeystoreError error);

// Returns the DER encoding of the X.509 Subject Public Key Info of the public
// key in |certificate|.
std::string GetSubjectPublicKeyInfo(
    const scoped_refptr<net::X509Certificate>& certificate);

// Intersects the two certificate lists |certs1| and |certs2| and passes the
// intersection to |callback|. The intersction preserves the order of |certs1|.
void IntersectCertificates(
    const net::CertificateList& certs1,
    const net::CertificateList& certs2,
    base::OnceCallback<void(std::unique_ptr<net::CertificateList>)> callback);

// The output for GetPublicKeyAndAlgorithm.
struct GetPublicKeyAndAlgorithmOutput {
  GetPublicKeyAndAlgorithmOutput();
  GetPublicKeyAndAlgorithmOutput(GetPublicKeyAndAlgorithmOutput&&);
  ~GetPublicKeyAndAlgorithmOutput();

  Status status = Status::kSuccess;
  std::vector<uint8_t> public_key;  // Only set if status == kSuccess
  base::DictionaryValue algorithm;  // Only set if status == kSuccess
};

// This is a convenient wrapper around GetPublicKey which also builds a
// WebCrypto algorithm dictionary and performs error checking.
GetPublicKeyAndAlgorithmOutput GetPublicKeyAndAlgorithm(
    const std::vector<uint8_t>& possibly_invalid_cert_der,
    const std::string& algorithm_name);

struct PublicKeyInfo {
  PublicKeyInfo();
  ~PublicKeyInfo();

  // The X.509 Subject Public Key Info of the key in DER encoding.
  std::string public_key_spki_der;

  // The type of the key.
  net::X509Certificate::PublicKeyType key_type =
      net::X509Certificate::kPublicKeyTypeUnknown;

  // The size of the key in bits.
  size_t key_size_bits = 0;
};

// Checks if the certificate key type and the algorithm are
//    - valid
//    - supported
//    - compatible
// Returns Status::kSuccess if they are, or the correct error reason if they
// are not.
Status CheckKeyTypeAndAlgorithm(net::X509Certificate::PublicKeyType key_type,
                                const std::string& algorithm_name);

// Returns the certificate key type that supports the given algorithm,
// or |kPublicKeyTypeUnknown| if the algorithm is unknown or unsupported.
net::X509Certificate::PublicKeyType GetKeyTypeForAlgorithm(
    const std::string& algorithm_name);

// Builds a partial WebCrypto Algorithm object from the parameters available in
// |key_info|. This supports both RSA and EC keys.
// Returns absl::nullopt if the key is of an unsupported type (so not RSA or
// EC).
absl::optional<base::DictionaryValue> BuildWebCrypAlgorithmDictionary(
    const PublicKeyInfo& key_info);

// Builds a partial WebCrypto Algorithm object from the parameters available in
// |key_info|, which must be the info of an RSA key. This doesn't include
// sign/hash parameters and thus isn't complete. platform_keys::GetPublicKey()
// enforced the public exponent 65537.
void BuildWebCryptoRSAAlgorithmDictionary(const PublicKeyInfo& key_info,
                                          base::DictionaryValue* algorithm);

// Builds a partial WebCrypto Algorithm object from the parameters available in
// |key_info|, which must be the info of an EC key. For more information about
// EcKeyAlgorithm dictionary, please refer to:
// https://www.w3.org/TR/WebCryptoAPI/#EcKeyAlgorithm-dictionary
void BuildWebCryptoEcdsaAlgorithmDictionary(const PublicKeyInfo& key_info,
                                            base::DictionaryValue* algorithm);

// Obtains information about the public key in |certificate|.
// If |certificate| contains an RSA key, sets |key_size_bits| to the modulus
// length, and |key_type| to type RSA and returns true.
// If |certificate| contains any other key type, or if the public exponent of
// the RSA key in |certificate| is not F4, returns false and does not update any
// of the output parameters.
// All pointer arguments must not be null.
bool GetPublicKey(const scoped_refptr<net::X509Certificate>& certificate,
                  net::X509Certificate::PublicKeyType* key_type,
                  size_t* key_size_bits);

// Obtains information about the public key in |spki|.
// If |spki| is an RSA key, sets |key_size_bits| to the modulus
// length, and |key_type| to type RSA and returns true.
// If |spki| is any other key type, returns false and does not update any
// of the output parameters.
// All pointer arguments must not be null.
bool GetPublicKeyBySpki(const std::string& spki,
                        net::X509Certificate::PublicKeyType* key_type,
                        size_t* key_size_bits);

struct ClientCertificateRequest {
  ClientCertificateRequest();
  ClientCertificateRequest(const ClientCertificateRequest& other);
  ~ClientCertificateRequest();

  // The list of the types of certificates requested, sorted in order of the
  // server's preference.
  std::vector<net::X509Certificate::PublicKeyType> certificate_key_types;

  // List of distinguished names of certificate authorities allowed by the
  // server. Each entry must be a DER-encoded X.509 DistinguishedName.
  std::vector<std::vector<uint8_t>> certificate_authorities;
};

}  // namespace platform_keys
}  // namespace chromeos

#endif  // CHROME_BROWSER_PLATFORM_KEYS_PLATFORM_KEYS_H_

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace StaticAnalysis\LazyLoadingValueHolder;

use ProxyManager\Factory\LazyLoadingValueHolderFactory;
use ProxyManager\Proxy\LazyLoadingInterface;

require_once __DIR__ . '/../../vendor/autoload.php';

class MyProxiedClass
{
    public function sayHello() : string
    {
        return 'Hello!';
    }
}

(static function () : void {
    echo (new LazyLoadingValueHolderFactory())
        ->createProxy(
            MyProxiedClass::class,
            static function (
                ?object & $instance,
                LazyLoadingInterface $proxy,
                string $method,
                array $parameters,
                ?\Closure & $initializer
            ) : bool {
                $instance    = new MyProxiedClass();
                $initializer = null; // disable initialization

                return true;
            }
        )
        ->sayHello();

    $valueHolder = (new LazyLoadingValueHolderFactory())
        ->createProxy(MyProxiedClass::class, static function (
            ?object & $wrappedObject,
            LazyLoadingInterface $proxy,
            string $method,
            array $parameters,
            ?\Closure & $initializer
        ) : bool {
            $initializer   = null; // disable initialization
            $wrappedObject = new MyProxiedClass();

            return true;
        });

    $valueHolder->initializeProxy();

    $wrappedValue = $valueHolder->getWrappedValueHolderValue();

    assert(null !== $wrappedValue);

    echo $wrappedValue->sayHello();

    $valueHolder->setProxyInitializer(static function (
        ?object & $instance,
        LazyLoadingInterface $proxy,
        string $method,
        array $parameters,
        ?\Closure & $initializer
    ) : bool {
        $instance    = new MyProxiedClass();
        $initializer = null; // disable initialization

        return true;
    });
})();


text:
module.exports = function (docPath, suffix) {

  this.copy(docPath, suffix).del(docPath);

  return this;

};


text:
require 'spec_helper'

describe Wechat::JsapiTicket do
  let(:ticket_content){
    {
      errcode: 0,
      errmsg: "ok",
      ticket: "bxLdikRXVbTPdHSM05e5u5sUoXNKd8-41ZO3MhKoyN5OfkWITDGgnr2fwJ0m9E8NYzWKVZvdVtaUgWvsdshFKA",
      expires_in: 7200
    }
  }
  let(:jsapi_ticket_file){Rails.root.join("tmp/jsapi_ticket_file")}
  let(:client){ double(:client) }
  let(:access_token){ double(:access_token) }
  let(:token_content){ {access_token: "12345", expires_in: 7200} }

  subject do
    Wechat::JsapiTicket.new(client, access_token, jsapi_ticket_file)
  end

  before :each do
    allow(client).to receive(:get).with("ticket/getticket", params: {
      type: "jsapi",
      access_token: token_content[:access_token]
    }).and_return(ticket_content)

    allow(access_token).to receive(:token).and_return(token_content[:access_token])
  end

  after :each do
    File.delete(jsapi_ticket_file) if File.exist?(jsapi_ticket_file)
  end

  describe "#ticket" do
    specify "read from file if jsapi_ticket_file is not initialized" do
      File.open(jsapi_ticket_file, 'w'){|f| f.write(ticket_content.to_json)}
      expect(subject.ticket).to eq(ticket_content[:ticket])
    end
  end

  describe "#refresh" do
    specify "will set jsapi_ticket_data" do
      expect(subject.refresh).to eq(ticket_content)
      expect(subject.jsapi_ticket_data).to eq(ticket_content)
    end
  end
  describe "#signature" do
    specify "will get signature" do
      url = 'http://www.baidu.com?q=ming'
      expect(subject.signature(url)[:url]).to eq(url)
    end
  end
end


text:
package tracing

import (
	"bytes"
	"context"

	"github.com/opentracing/opentracing-go"
	"github.com/uber/jaeger-client-go"

	"github.com/scionproto/scion/go/lib/log"
)

// CtxWith creates a new span and attaches it to the context, it also sets the
// debug id of the logger and the span id and attaches the logger to the context.
func CtxWith(parentCtx context.Context, operationName string,
	opts ...opentracing.StartSpanOption) (opentracing.Span, context.Context) {

	span, ctx := opentracing.StartSpanFromContext(parentCtx, operationName, opts...)
	if spanCtx, ok := span.Context().(jaeger.SpanContext); ok {
		id := spanCtx.TraceID()
		return span, log.CtxWith(ctx, log.New("debug_id", id.String()[:8], "trace_id", id))
	}
	return span, log.CtxWith(ctx, log.New("debug_id", log.NewDebugID()))
}

// IDFromCtx reads the tracing ID from the context.
func IDFromCtx(ctx context.Context) []byte {
	span := opentracing.SpanFromContext(ctx)
	if span == nil {
		return nil
	}
	var tracingBin bytes.Buffer
	err := opentracing.GlobalTracer().Inject(span.Context(), opentracing.Binary, &tracingBin)
	if err != nil {
		// According to the opentracing documentation, this error should never happen:
		// "All opentracing.Tracer implementations MUST support all BuiltinFormats."
		panic(err)
	}
	return tracingBin.Bytes()
}

// StartSpanFromCtx wraps opentracing.StartSpanFromContext for convenience.
func StartSpanFromCtx(ctx context.Context, operationName string,
	opts ...opentracing.StartSpanOption) (opentracing.Span, context.Context) {

	return opentracing.StartSpanFromContext(ctx, operationName, opts...)
}


text:
module Dynflow
  class DelayedPlan < Serializable

    include Algebrick::TypeCheck

    attr_reader :execution_plan_uuid, :start_before
    attr_accessor :frozen, :start_at

    def initialize(world, execution_plan_uuid, start_at, start_before, args_serializer, frozen)
      @world               = Type! world, World
      @execution_plan_uuid = Type! execution_plan_uuid, String
      @start_at            = Type! start_at, Time, NilClass
      @start_before        = Type! start_before, Time, NilClass
      @args_serializer     = Type! args_serializer, Serializers::Abstract
      @frozen              = Type! frozen, Algebrick::Types::Boolean
    end

    def execution_plan
      @execution_plan ||= @world.persistence.load_execution_plan(@execution_plan_uuid)
    end

    def plan
      execution_plan.root_plan_step.load_action
      execution_plan.generate_action_id
      execution_plan.generate_step_id
      execution_plan.plan(*@args_serializer.perform_deserialization!)
    end

    def timeout
      error("Execution plan could not be started before set time (#{@start_before})", 'timeout')
    end

    def error(message, history_entry = nil)
      execution_plan.root_plan_step.state = :error
      execution_plan.root_plan_step.error = ::Dynflow::ExecutionPlan::Steps::Error.new(message)
      execution_plan.root_plan_step.save
      execution_plan.execution_history.add history_entry, @world.id unless history_entry.nil?
      execution_plan.update_state :stopped
    end

    def cancel
      execution_plan.root_plan_step.state = :cancelled
      execution_plan.root_plan_step.save
      execution_plan.execution_history.add "Delayed task cancelled", @world.id
      execution_plan.update_state :stopped
      @world.persistence.delete_delayed_plans(:execution_plan_uuid => @execution_plan_uuid)
      return true
    end

    def execute(future = Concurrent.future)
      @world.execute(@execution_plan_uuid, future)
      ::Dynflow::World::Triggered[@execution_plan_uuid, future]
    end

    def to_hash
      recursive_to_hash :execution_plan_uuid => @execution_plan_uuid,
                        :start_at            => @start_at,
                        :start_before        => @start_before,
                        :serialized_args     => @args_serializer.serialized_args,
                        :args_serializer     => @args_serializer.class.name,
                        :frozen              => @frozen
    end

    # Retrieves arguments from the serializer
    #
    # @return [Array] array of the original arguments
    def args
      @args_serializer.perform_deserialization! if @args_serializer.args.nil?
      @args_serializer.args
    end

    # @api private
    def self.new_from_hash(world, hash, *args)
      serializer = Utils.constantize(hash[:args_serializer]).new(nil, hash[:serialized_args])
      self.new(world,
               hash[:execution_plan_uuid],
               string_to_time(hash[:start_at]),
               string_to_time(hash[:start_before]),
               serializer,
               hash[:frozen] || false)
    rescue NameError => e
      error(e.message)
    end
  end
end


text:
/*!
{
  "name": "CSS Regions",
  "caniuse": "css-regions",
  "authors": ["Mihai Balan"],
  "property": "regions",
  "tags": ["css"],
  "builderAliases": ["css_regions"],
  "notes": [{
    "name": "W3C Specification",
    "href": "https://www.w3.org/TR/css3-regions/"
  }]
}
!*/
define(['Modernizr', 'createElement', 'docElement', 'isSVG', 'prefixed'], function(Modernizr, createElement, docElement, isSVG, prefixed) {
  // We start with a CSS parser test then we check page geometry to see if it's affected by regions
  // Later we might be able to retire the second part, as WebKit builds with the false positives die out

  Modernizr.addTest('regions', function() {

    if (isSVG) {
      // css regions don't work inside of SVG elements. Rather than update the
      // below test to work in an SVG context, just exit early to save bytes
      return false;
    }

    /* Get the 'flowFrom' property name available in the browser. Either default or vendor prefixed.
       If the property name can't be found we'll get Boolean 'false' and fail quickly */
    var flowFromProperty = prefixed('flowFrom');
    var flowIntoProperty = prefixed('flowInto');
    var result = false;

    if (!flowFromProperty || !flowIntoProperty) {
      return result;
    }

    /* If CSS parsing is there, try to determine if regions actually work. */
    var iframeContainer = createElement('iframe');
    var container = createElement('div');
    var content = createElement('div');
    var region = createElement('div');

    /* we create a random, unlikely to be generated flow number to make sure we don't
       clash with anything more vanilla, like 'flow', or 'article', or 'f1' */
    var flowName = 'modernizr_flow_for_regions_check';

    /* First create a div with two adjacent divs inside it. The first will be the
       content, the second will be the region. To be able to distinguish between the two,
       we'll give the region a particular padding */
    content.innerText = 'M';
    container.style.cssText = 'top: 150px; left: 150px; padding: 0px;';
    region.style.cssText = 'width: 50px; height: 50px; padding: 42px;';

    region.style[flowFromProperty] = flowName;
    container.appendChild(content);
    container.appendChild(region);
    docElement.appendChild(container);

    /* Now compute the bounding client rect, before and after attempting to flow the
       content div in the region div. If regions are enabled, the after bounding rect
       should reflect the padding of the region div.*/
    var flowedRect, delta;
    var plainRect = content.getBoundingClientRect();

    content.style[flowIntoProperty] = flowName;
    flowedRect = content.getBoundingClientRect();

    delta = parseInt(flowedRect.left - plainRect.left, 10);
    docElement.removeChild(container);

    if (delta == 42) {
      result = true;
    } else {
      /* IE only allows for the content to come from iframes. This has the
       * side effect of automatic collapsing of iframes once they get the flow-into
       * property set. checking for a change on the height allows us to detect this
       * in a sync way, without having to wait for a frame to load */

      docElement.appendChild(iframeContainer);
      plainRect = iframeContainer.getBoundingClientRect();
      iframeContainer.style[flowIntoProperty] = flowName;
      flowedRect = iframeContainer.getBoundingClientRect();

      if (plainRect.height > 0 && plainRect.height !== flowedRect.height && flowedRect.height === 0) {
        result = true;
      }
    }

    content = region = container = iframeContainer = undefined;

    return result;
  });
});


text:
=head1 LICENSE

Copyright (c) 1999-2013 The European Bioinformatics Institute and
Genome Research Limited.  All rights reserved.

This software is distributed under a modified Apache license.
For license details, please see

http://www.ensembl.org/info/about/legal/code_licence.html

=head1 CONTACT

Please email comments or questions to the public Ensembl
developers list at <dev@ensembl.org>.

Questions may also be sent to the Ensembl help desk at
<helpdesk@ensembl.org>.

=cut

package ThirdComputation;

use strict;
use warnings;

use base ('Bio::EnsEMBL::Hive::Process');

use FileHandle;

sub run {
  my $self = shift;
  my $dir = $self->param('pipeline_dir');
  my $species = $self->param('species');

  $self->warning("Third computation $species");

  my $fh = FileHandle->new("$dir/$species/ThirdComputation.txt", 'w');
  print $fh "ThirdComputation\n";
  $fh->close();

}

1;


text:
var fs = require('fs-extra');
var path = require('path');
var spawn = require('cross-spawn');
var pathExists = require('path-exists');
var chalk = require('chalk');

module.exports = function(appPath, appName, verbose, originalDirectory) {
  var ownPackageName = require(path.join(__dirname, '..', 'package.json')).name;
  var ownPath = path.join(appPath, 'node_modules', ownPackageName);
  var appPackage = require(path.join(appPath, 'package.json'));

  // Copy over some of the devDependencies
  appPackage.dependencies = appPackage.dependencies || {};
  appPackage.devDependencies = appPackage.devDependencies || {};
  appPackage.peerDependencies = appPackage.peerDependencies || {"react": "^15.4.0", "react-dom": "^15.4.0"};
  return ;

  // Setup the script rules
  appPackage.scripts = {
    'start': 'magic-scripts start',
    'dist': 'magic-scripts dist',
    'build': 'magic-scripts build',
    'test': 'magic-scripts test --env=jsdom',
    'eject': 'magic-scripts eject'
  };

  fs.writeFileSync(
    path.join(appPath, 'package.json'),
    JSON.stringify(appPackage, null, 2)
  );

  var readmeExists = pathExists.sync(path.join(appPath, 'README.md'));
  if (readmeExists) {
    fs.renameSync(path.join(appPath, 'README.md'), path.join(appPath, 'README.old.md'));
  }

  // Copy the files for the user
  fs.copySync(path.join(ownPath, 'template'), appPath);

  // Rename gitignore after the fact to prevent npm from renaming it to .npmignore
  // See: https://github.com/npm/npm/issues/1862
  fs.move(path.join(appPath, 'gitignore'), path.join(appPath, '.gitignore'), [], function (err) {
    if (err) {
      // Append if there's already a `.gitignore` file there
      if (err.code === 'EEXIST') {
        var data = fs.readFileSync(path.join(appPath, 'gitignore'));
        fs.appendFileSync(path.join(appPath, '.gitignore'), data);
        fs.unlinkSync(path.join(appPath, 'gitignore'));
      } else {
        throw err;
      }
    }
  });

  // Run another npm install for react and react-dom
  console.log('Installing react and react-dom from npm...');
  console.log();
  // TODO: having to do two npm installs is bad, can we avoid it?
  var args = [
    'install',
    'react',
    'react-dom',
    verbose && '--verbose'
  ].filter(function(e) { return e; });
  var proc = spawn('npm', args, {stdio: 'inherit'});
  proc.on('close', function (code) {
    if (code !== 0) {
      console.error('`npm ' + args.join(' ') + '` failed');
      return;
    }

    // Display the most elegant way to cd.
    // This needs to handle an undefined originalDirectory for
    // backward compatibility with old global-cli's.
    var cdpath;
    if (originalDirectory &&
        path.join(originalDirectory, appName) === appPath) {
      cdpath = appName;
    } else {
      cdpath = appPath;
    }

    console.log();
    console.log('Success! Created ' + appName + ' at ' + appPath);
    console.log('Inside that directory, you can run several commands:');
    console.log();
    console.log(chalk.cyan('  npm start'));
    console.log('    Starts the development server.');
    console.log();
    console.log(chalk.cyan('  npm run dist'));
    console.log('    Dist your component at src/components.');
    console.log();
    console.log(chalk.cyan('  npm run build'));
    console.log('    Bundles the app into static files for production.');
    console.log();
    console.log(chalk.cyan('  npm test'));
    console.log('    Starts the test runner.');
    console.log();
    console.log(chalk.cyan('  npm run eject'));
    console.log('    Removes this tool and copies build dependencies, configuration files');
    console.log('    and scripts into the app directory. If you do this, you can't go back!');
    console.log();
    console.log('We suggest that you begin by typing:');
    console.log();
    console.log(chalk.cyan('  cd'), cdpath);
    console.log('  ' + chalk.cyan('npm start'));
    if (readmeExists) {
      console.log();
      console.log(chalk.yellow('You had a `README.md` file, we renamed it to `README.old.md`'));
    }
    console.log();
    console.log('Happy hacking!');
  });
};


text:
@implementation UIViewController (Tools)
- (void)setNavigationBarWithColor:(UIColor *)color {
    if ([color isEqual:[UIColor clearColor]]) {
        self.navigationController.navigationBar.barTintColor = [UIColor whiteColor];
        self.navigationController.navigationBar.translucent = YES;
        // 将状态栏和导航条设置成透明
        UIImage *image = [[UIImage alloc] init];
        [self.navigationController.navigationBar setBackgroundImage:image forBarMetrics:UIBarMetricsDefault];
        self.navigationController.navigationBar.shadowImage = image;
    }
    else {
        self.navigationController.navigationBar.barTintColor = color;
        self.navigationController.navigationBar.tintColor = color;
        self.navigationController.navigationBar.translucent = NO;
        [self.navigationController.navigationBar setBackgroundImage:nil forBarMetrics:UIBarMetricsDefault];
        self.navigationController.navigationBar.shadowImage = [[UIImage alloc] init];
    }
}

- (void)tryAnalyzeVideo:(DDPVideoModel *)model {
    [DDPMethod matchVideoModel:model completion:nil];
}

@end


text:
<?php

namespace Hanson\Vbot\Foundation;

interface ServiceProviderInterface
{
    public function register(Vbot $vbot);
}


text:
__LLBC_INTERNAL_NS_BEGIN
static LLBC_NS LLBC_TlsHandle __LLBC_libTlsHandle = LLBC_INVALID_TLS_HANDLE;
__LLBC_INTERNAL_NS_END

__LLBC_NS_BEGIN

__LLBC_LibTls::__LLBC_LibTls()
{
    commonTls.errNo = LLBC_ERROR_SUCCESS;
    commonTls.subErrNo = LLBC_ERROR_SUCCESS;
    memset(&commonTls.errDesc, 0, sizeof(commonTls.errDesc));
    memset(&commonTls.customErrDesc, 0, sizeof(commonTls.customErrDesc));

    coreTls.llbcThread = false;
    coreTls.entryThread = false;
    coreTls.needInitWinSock = true;
    coreTls.threadHandle = LLBC_INVALID_HANDLE;
    coreTls.threadId = LLBC_INVALID_NATIVE_THREAD_ID;
    coreTls.nativeThreadHandle = LLBC_INVALID_NATIVE_THREAD_HANDLE;
    coreTls.task = nullptr;
    coreTls.timerScheduler = nullptr;
    coreTls.safetyObjectPool = nullptr;
    coreTls.unsafetyObjectPool = nullptr;

    #if LLBC_CFG_OS_IMPL_SYMBOL
     #if LLBC_TARGET_PLATFORM_WIN32
    coreTls.symbol.win32Symbol = LLBC_Calloc(
        ::SYMBOL_INFO, sizeof(::SYMBOL_INFO) + (LLBC_CFG_OS_SYMBOL_MAX_SYMBOL_NAME + 1) * sizeof(char));
    coreTls.symbol.win32Symbol->SizeOfStruct = sizeof(::SYMBOL_INFO);
    coreTls.symbol.win32Symbol->MaxNameLen = LLBC_CFG_OS_SYMBOL_MAX_SYMBOL_NAME;

    memset(&coreTls.symbol.win32ImgHelpLine64, 0, sizeof(coreTls.symbol.win32ImgHelpLine64));
    coreTls.symbol.win32ImgHelpLine64.SizeOfStruct = sizeof(coreTls.symbol.win32ImgHelpLine64);
     #endif // LLBC_TARGET_PLATFORM_WIN32
    #endif // LLBC_CFG_OS_IMPL_SYMBOL

    objbaseTls.poolStack = nullptr;

    memset(commTls.services, 0, sizeof(commTls.services));
}

__LLBC_LibTls::~__LLBC_LibTls()
{
    #if LLBC_CFG_OS_IMPL_SYMBOL
     #if LLBC_TARGET_PLATFORM_WIN32
    LLBC_XFree(coreTls.symbol.win32Symbol);
     #endif // LLBC_TARGET_PLATFORM_WIN32
    #endif // LLBC_CFG_OS_IMPL_SYMBOL
}

void __LLBC_CreateLibTls()
{
    LLBC_TlsHandle &tlsHandle = LLBC_INTERNAL_NS __LLBC_libTlsHandle;
    if (tlsHandle != LLBC_INVALID_TLS_HANDLE)
        return;

    bool tlsCreated;
#if LLBC_TARGET_PLATFORM_NON_WIN32
    tlsCreated = (pthread_key_create(&tlsHandle, nullptr) == 0) ? true : false;
#else
    tlsCreated = ((tlsHandle = ::TlsAlloc()) != TLS_OUT_OF_INDEXES) ? true : false;
#endif
    if (!tlsCreated)
    {
        ASSERT(!tlsCreated && "Create llbc library TLS handle failed!");
        exit(-1);
    }
}

void __LLBC_DestroyLibTls()
{
    LLBC_TlsHandle &tlsHandle = LLBC_INTERNAL_NS __LLBC_libTlsHandle;

#if LLBC_TARGET_PLATFORM_NON_WIN32
    (void)pthread_key_delete(tlsHandle);
#else
    (void)::TlsFree(tlsHandle);
#endif

    tlsHandle = LLBC_INVALID_TLS_HANDLE;
}

__LLBC_LibTls *__LLBC_GetLibTls()
{
    LLBC_TlsHandle &tlsHandle = LLBC_INTERNAL_NS __LLBC_libTlsHandle;
    if (UNLIKELY(tlsHandle == LLBC_INVALID_TLS_HANDLE))
        return nullptr;

    __LLBC_LibTls *libTls;
#if LLBC_TARGET_PLATFORM_NON_WIN32
    libTls = reinterpret_cast<__LLBC_LibTls *>(pthread_getspecific(tlsHandle));
#else
    libTls = reinterpret_cast<__LLBC_LibTls *>(::TlsGetValue(tlsHandle));
#endif

    if (UNLIKELY(!libTls))
    {
        libTls = new __LLBC_LibTls;

#if LLBC_TARGET_PLATFORM_NON_WIN32
        (void)pthread_setspecific(tlsHandle, libTls);
#else
        (void)::TlsSetValue(tlsHandle, libTls);
#endif
    }

    return libTls;
}

void __LLBC_ResetLibTls()
{
    LLBC_TlsHandle &tlsHandle = LLBC_INTERNAL_NS __LLBC_libTlsHandle;

    __LLBC_LibTls *libTls;
#if LLBC_TARGET_PLATFORM_NON_WIN32
    if ((libTls = reinterpret_cast<__LLBC_LibTls *>(
        pthread_getspecific(tlsHandle))))
    {
        delete libTls;
        pthread_setspecific(tlsHandle, nullptr);
    }
#else
    if ((libTls = reinterpret_cast<__LLBC_LibTls *>(
        ::TlsGetValue(tlsHandle))))
    {
        delete libTls;
        ::TlsSetValue(tlsHandle, nullptr);
    }
#endif
}

__LLBC_NS_END


text:
// Copyright Dirk Lemstra https://github.com/dlemstra/Magick.NET.
// Licensed under the Apache License, Version 2.0.

using System;

namespace ImageMagick
{
    /// <summary>
    /// Class that can be used to create various settings.
    /// </summary>
    /// <typeparam name="TQuantumType">The quantum type.</typeparam>
    public interface ISettingsFactory<TQuantumType>
        where TQuantumType : struct, IConvertible
    {
        /// <summary>
        /// Initializes a new instance that implements <see cref="ICompareSettings{TQuantumType}"/>.
        /// </summary>
        /// <returns>A new <see cref="ICompareSettings{TQuantumType}"/> instance.</returns>
        ICompareSettings<TQuantumType> CreateCompareSettings();

        /// <summary>
        /// Initializes a new instance that implements <see cref="IComplexSettings"/>.
        /// </summary>
        /// <returns>A new <see cref="IComplexSettings"/> instance.</returns>
        IComplexSettings CreateComplexSettings();

        /// <summary>
        /// Initializes a new instance that implements <see cref="IConnectedComponentsSettings"/>.
        /// </summary>
        /// <returns>A new <see cref="IConnectedComponentsSettings"/> instance.</returns>
        IConnectedComponentsSettings CreateConnectedComponentsSettings();

        /// <summary>
        /// Initializes a new instance that implements <see cref="IDeskewSettings"/>.
        /// </summary>
        /// <returns>A new <see cref="IDeskewSettings"/> instance.</returns>
        IDeskewSettings CreateDeskewSettings();

        /// <summary>
        /// Initializes a new instance that implements <see cref="IDistortSettings"/>.
        /// </summary>
        /// <returns>A new <see cref="IDistortSettings"/> instance.</returns>
        IDistortSettings CreateDistortSettings();

        /// <summary>
        /// Initializes a new instance that implements <see cref="IKmeansSettings"/>.
        /// </summary>
        /// <returns>A new <see cref="IKmeansSettings"/> instance.</returns>
        IKmeansSettings CreateKmeansSettings();

        /// <summary>
        /// Initializes a new instance that implements <see cref="IMagickReadSettings{TQuantumType}"/>.
        /// </summary>
        /// <returns>A new <see cref="IMagickReadSettings{TQuantumType}"/> instance.</returns>
        IMagickReadSettings<TQuantumType> CreateMagickReadSettings();

        /// <summary>
        /// Initializes a new instance that implements <see cref="IMontageSettings{TQuantumType}"/>.
        /// </summary>
        /// <returns>A new <see cref="IMagickReadSettings{TQuantumType}"/> instance.</returns>
        IMontageSettings<TQuantumType> CreateMontageSettings();

        /// <summary>
        /// Initializes a new instance that implements <see cref="IMorphologySettings"/>.
        /// </summary>
        /// <returns>A new <see cref="IMorphologySettings"/> instance.</returns>
        IMorphologySettings CreateMorphologySettings();

        /// <summary>
        /// Initializes a new instance that implements <see cref="IPixelReadSettings{TQuantumType}"/>.
        /// </summary>
        /// <returns>A new <see cref="IPixelReadSettings{TQuantumType}"/> instance.</returns>
        IPixelReadSettings<TQuantumType> CreatePixelReadSettings();

        /// <summary>
        /// Initializes a new instance that implements <see cref="IQuantizeSettings"/>.
        /// </summary>
        /// <returns>A new <see cref="IQuantizeSettings"/> instance.</returns>
        IQuantizeSettings CreateQuantizeSettings();
    }
}


text:
"""
This module is used to filter and reload PATH.
This file is genrated by Splunk add-on builder
"""

import os
import sys
import re

ta_name = 'SplunkTAforPuppetEnterprise'
ta_lib_name = 'splunktaforpuppetenterprise'
pattern = re.compile(r"[\\/]etc[\\/]apps[\\/][^\\/]+[\\/]bin[\\/]?$")
new_paths = [path for path in sys.path if not pattern.search(path) or ta_name in path]
new_paths.insert(0, os.path.sep.join([os.path.dirname(__file__), ta_lib_name]))
sys.path = new_paths


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

express().get('/user/', function(req, res) {
    var evil = req.query.evil;
    res.send(console.log("
%s
", evil)); // OK (returns undefined)
    res.send(util.format("
%s
", evil)); // NOT OK
    res.send(require("printf")("
%s
", evil)); // NOT OK
});


text:
package server;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;

import org.apache.commons.net.PrintCommandListener;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;

/**
 * Simple FTP upload clients
 *
 */
public class FTPUploader {

    FTPClient ftp = null;

    /**
     * Class constructor
     * @param host
     * @param user
     * @param pwd
     * @throws Exception
     */
    public FTPUploader(String host, String user, String pwd) throws Exception{

    	//Init FTP client
        ftp = new FTPClient();

        //Add protocol listener
        ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out)));
        int reply;

        //Connect to host
        ftp.connect(host);
        reply = ftp.getReplyCode();

        //If negative reply, disconnect and throw error
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
            throw new Exception("Exception in connecting to FTP Server");
        }

        //Login
        ftp.login(user, pwd);

        //Set file type
        ftp.setFileType(FTP.BINARY_FILE_TYPE);

        //Passive mode
        ftp.enterLocalPassiveMode();
    }

    /**
     * Uploads a file
     * @param file
     * @param fileName
     * @param hostDir
     * @throws Exception
     */
    public void uploadFile(File file, String fileName, String hostDir)
            throws Exception {

    	try {

    		//Init input stream and store the file
    		InputStream input = new FileInputStream(file);
            this.ftp.storeFile(hostDir + fileName, input);

		} catch (Exception e) {

			e.printStackTrace();
		}
    }

    /**
     * Disconnects from FTP server
     */
    public void disconnect(){

    	//If connected, disconnect
        if (this.ftp.isConnected()) {

        	try {
                this.ftp.logout();
                this.ftp.disconnect();
            } catch (IOException f) {

                // do nothing as file is already saved to server
            	f.printStackTrace();
            }
        }
    }

    /*******************************************************/
    /********************* STATIC **************************/
    /*******************************************************/

    /**
	 * Uploads a file through the ftp server
	 * @param file
	 * @param fileName
	 * @param ftpUrl
	 * @param userName
	 * @param password
	 * @param fileRoute
	 * @throws Exception
	 */
	public static void uploadFileToFtp(File file, String fileName, String ftpUrl, String userName, String password, String fileRoute) throws Exception{

		//Start upload
		System.out.println("Start");

		//Init ftp client and uplaod
        FTPUploader ftpUploader = new FTPUploader(ftpUrl, userName, password);
        ftpUploader.uploadFile(file, fileName, fileRoute);

        //Disconnect and finish
        ftpUploader.disconnect();
        System.out.println("Done");
	}
}


text:
module NdfdRestApi
  class SummarizedDataForLine < SummarizedData

    class << self
      private :new

      def fetch(line_params, params)
        massaged_params = {
          :endPoint1Lat => line_params[0][:lat],
          :endPoint1Lon => line_params[0][:lon],
          :endPoint2Lat => line_params[1][:lat],
          :endPoint2Lon => line_params[1][:lon],
          :format => params[:format] || "12 hourly",
          :numDays => params[:days] || 1,
          :unit => params[:unit] || "e"
        }
        super(massaged_params)
      end

    end

  end
end


text:
package org.apache.flink.storm.wordcount;

import org.apache.storm.topology.IRichBolt;
import org.apache.storm.tuple.Fields;
import org.apache.flink.api.java.io.CsvInputFormat;
import org.apache.flink.api.java.io.TupleCsvInputFormat;
import org.apache.flink.api.java.tuple.Tuple;
import org.apache.flink.api.java.tuple.Tuple1;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.api.java.typeutils.TupleTypeInfo;
import org.apache.flink.api.java.typeutils.TypeExtractor;
import org.apache.flink.core.fs.Path;
import org.apache.flink.examples.java.wordcount.util.WordCountData;
import org.apache.flink.storm.wordcount.operators.BoltTokenizerByName;
import org.apache.flink.storm.wordcount.operators.WordCountDataTuple;
import org.apache.flink.storm.wrappers.BoltWrapper;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

/**
 * Implements the "WordCount" program that computes a simple word occurrence histogram over text files in a streaming
 * fashion. The tokenizer step is performed by a {@link IRichBolt Bolt}. In contrast to {@link BoltTokenizerWordCount}
 * the tokenizer's input is a {@link Tuple} type and the single field is accessed by name.
 *

 * The input is a plain text file with lines separated by newline characters.
 *

 * Usage: WordCount <text path> <result path>

 * If no parameters are provided, the program is run with default data from {@link WordCountData}.
 *

 * This example shows how to:
 *

 *
how to access attributes by name within a Bolt for {@link Tuple} type input streams
 *

 */
public class BoltTokenizerWordCountWithNames {

	// *************************************************************************
	// PROGRAM
	// *************************************************************************

	public static void main(final String[] args) throws Exception {

		if (!parseParameters(args)) {
			return;
		}

		// set up the execution environment
		final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

		// get input data
		final DataStream<Tuple1<String>> text = getTextDataStream(env);

		final DataStream<Tuple2<String, Integer>> counts = text
				// split up the lines in pairs (2-tuples) containing: (word,1)
				// this is done by a Storm bolt that is wrapped accordingly
				.transform(
						"BoltTokenizerWithNames",
						TypeExtractor.getForObject(new Tuple2<String, Integer>("", 0)),
						new BoltWrapper<Tuple1<String>, Tuple2<String, Integer>>(
								new BoltTokenizerByName(), new Fields("sentence")))
				// group by the tuple field "0" and sum up tuple field "1"
				.keyBy(0).sum(1);

		// emit result
		if (fileOutput) {
			counts.writeAsText(outputPath);
		} else {
			counts.print();
		}

		// execute program
		env.execute("Streaming WordCount with schema bolt tokenizer");
	}

	// *************************************************************************
	// UTIL METHODS
	// *************************************************************************

	private static boolean fileOutput = false;
	private static String textPath;
	private static String outputPath;

	private static boolean parseParameters(final String[] args) {

		if (args.length > 0) {
			// parse input arguments
			fileOutput = true;
			if (args.length == 2) {
				textPath = args[0];
				outputPath = args[1];
			} else {
				System.err.println("Usage: BoltTokenizerWordCountWithNames <text path> <result path>");
				return false;
			}
		} else {
			System.out.println("Executing BoltTokenizerWordCountWithNames example with built-in default data");
			System.out.println("  Provide parameters to read input data from a file");
			System.out.println("  Usage: BoltTokenizerWordCountWithNames <text path> <result path>");
		}
		return true;
	}

	private static DataStream<Tuple1<String>> getTextDataStream(final StreamExecutionEnvironment env) {
		if (fileOutput) {
			// read the text file from given input path
			TupleTypeInfo<Tuple1<String>> sourceType = (TupleTypeInfo<Tuple1<String>>)TypeExtractor
					.getForObject(new Tuple1<String>(""));
			return env.createInput(new TupleCsvInputFormat<Tuple1<String>>(new Path(
					textPath), CsvInputFormat.DEFAULT_LINE_DELIMITER,
					CsvInputFormat.DEFAULT_LINE_DELIMITER, sourceType),
					sourceType);
		}

		return env.fromElements(WordCountDataTuple.TUPLES);
	}

}


text:
cask 'marked' do
  version '2.5.17950'
  sha256 '38f0bc6d5ea13ef202a18ea770cb5ee0f2097755c80e6632da3f368036202278'

  url "https://updates.marked2app.com/Marked#{version}.zip"
  appcast 'https://updates.marked2app.com/marked.xml',
          checkpoint: '2be7502e88a0499ce8695297dad3a4a6e2b36afec4e3c7e14b18cc9a07babe81'
  name 'Marked'
  homepage 'http://marked2app.com/'

  auto_updates true
  depends_on macos: '>= :yosemite'

  app "Marked #{version.major}.app"

  uninstall quit: "com.brettterpstra.marked#{version.major}"

  zap trash: [
               "~/Library/Application Support/Marked #{version.major}",
               "~/Library/Application Support/com.apple.sharedfilelist/com.apple.LSSharedFileList.ApplicationRecentDocuments/com.brettterpstra.marked#{version.major}.sfl*",
               "~/Library/Caches/Marked #{version.major}",
               "~/Library/Caches/com.brettterpstra.marked#{version.major}",
               "~/Library/Logs/Marked #{version.major}",
               "~/Library/Preferences/com.brettterpstra.marked#{version.major}.plist",
               "~/Library/Saved Application State/com.brettterpstra.marked#{version.major}.savedState",
             ]
end


text:
package cli;

/** Generic parameter element. */
public abstract class Param extends SyntaxNode {

    /** Constructor.
        @param I_NativeRef Native instance reference. */
    protected Param(int I_NativeRef) {
        super(I_NativeRef);
    }

    /** Copy value method.
        @param CLI_Param Source parameter to copy the value from. */
    public final void copyValue(Param CLI_Param) {
        __copyValue(this.getNativeRef(), CLI_Param.getNativeRef());
    }
    private static final native boolean __copyValue(int I_NativeDestParamRef, int I_NativeSrcParamRef);

    /** Determines whether an element matches this parameter.
        @param CLI_Element Element to check the correspondance with this parameter.
        @return true if the element matches this parameter, false if the element does not match this parameter. */
    public boolean matches(Element CLI_Element) {
        Traces.trace(NativeTraces.CLASS, NativeTraces.begin("Param.matches(CLI_Element)"));
        Traces.trace(NativeTraces.CLASS, NativeTraces.param("this", new Integer(this.getNativeRef()).toString()));
        Traces.trace(NativeTraces.CLASS, NativeTraces.param("CLI_Element", new Integer(CLI_Element.getNativeRef()).toString()));

        boolean b_Res = false;
        if (CLI_Element instanceof Param) {
            Param cli_Param = (Param) CLI_Element;
            if (cli_Param != null) {
                if (cli_Param.getCloned() == this) {
                    this.copyValue(cli_Param);
                    b_Res = true;
                }
            }
        }

        Traces.trace(NativeTraces.CLASS, NativeTraces.end("Param.matches()", new Boolean(b_Res).toString()));
        return b_Res;
    }
    /** Source clone parameter accessor.
        @return Source clone parameter instance. */
    protected final cli.Param getCloned() {
        return (cli.Param) NativeObject.getObject(__getCloned(this.getNativeRef()));
    }
    private static final native int __getCloned(int I_NativeParamRef);

}


text:
extern crate proc_macro;
use proc_macro::TokenStream;

#[proc_macro]
pub fn dump_debug(tokens: TokenStream) -> TokenStream {
    eprintln!("{:?}", tokens);
    eprintln!("{:#?}", tokens);
    TokenStream::new()
}


text:
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <artifactId>gitkit</artifactId>
    <groupId>com.google.gitkit</groupId>
    <version>1.0</version>
  </parent>
  <groupId>com.google.gitkit</groupId>
  <artifactId>samples</artifactId>
  <version>1.0</version>
  <packaging>pom</packaging>
  <name>Google Identity Toolkit Samples</name>
  <dependencies>
  </dependencies>
  <modules>
    <module>tutorial</module>
  </modules>
</project>


text:
'''
Created on 2017/11/16.

@author: chk01
'''
import pandas as pd
import numpy as np
import os
import tensorflow as tf
from tensorflow.python.framework import ops
import matplotlib.pyplot as plt
import scipy.io as scio
import math

def convert_to_one_hot(Y, C):
    Y = np.eye(C)[Y.reshape(-1)].T
    return Y

def init_sets(X, Y, file, distribute):
    m = X.shape[1]
    permutation = list(np.random.permutation(m))
    shuffled_X = X[:, permutation]
    shuffled_Y = Y[:, permutation]
    assert len(distribute) == 2
    assert sum(distribute) == 1
    scio.savemat(file + '_train',
                 {'X': shuffled_X[:, :int(m * distribute[0])], 'Y': shuffled_Y[:, :int(m * distribute[0])]})
    scio.savemat(file + '_test',
                 {'X': shuffled_X[:, int(m * distribute[0]):], 'Y': shuffled_Y[:, int(m * distribute[0]):]})
    return True

def load_data(x, y, file):
    init_sets(x, y, file, distribute=[0.8, 0.2])
    return True

def initialize_parameters_deep(layer_dims):
    parameters = {}
    L = len(layer_dims)  # number of layers in the network

    for l in range(1, L):
        parameters['W' + str(l)] = tf.get_variable(dtype=tf.float32, name='W' + str(l),
                                                   shape=(layer_dims[l], layer_dims[l - 1]),
                                                   initializer=tf.contrib.layers.xavier_initializer())
        parameters['b' + str(l)] = tf.get_variable(dtype=tf.float32, name='b' + str(l),
                                                   shape=(layer_dims[l], 1),
                                                   initializer=tf.contrib.layers.xavier_initializer())
        assert (parameters['W' + str(l)].shape == (layer_dims[l], layer_dims[l - 1]))
        assert (parameters['b' + str(l)].shape == (layer_dims[l], 1))

    return parameters

def create_placeholders(n_x, n_y):
    X = tf.placeholder(name='X', shape=(n_x, None), dtype=tf.float32)
    Y = tf.placeholder(name='Y', shape=(n_y, None), dtype=tf.float32)

    return X, Y

def forward_propagation(X, parameters):
    A = X
    L = len(parameters) // 2
    for l in range(1, L):
        A_prev = A
        W = parameters['W' + str(l)]
        b = parameters['b' + str(l)]
        A = tf.nn.relu(tf.add(tf.matmul(W, A_prev), b))
        # A = tf.nn.dropout(A, 0.9)
        # 94
    ZL = tf.add(tf.matmul(parameters['W' + str(L)], A), parameters['b' + str(L)])

    return ZL

def compute_cost(ZL, Y):
    cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=tf.transpose(ZL), labels=tf.transpose(Y)))
    return cost

def cost_fig(costs, learning_rate):
    costs = np.squeeze(costs)
    plt.plot(costs)
    plt.ylabel('cost')
    plt.xlabel('epochs (per hundreds)')
    plt.title("Learning rate =" + str(learning_rate))
    plt.show()
    return True

def random_mini_batches(X, Y, mini_batch_size=64):
    m = X.shape[1]
    mini_batches = []

    permutation = list(np.random.permutation(m))
    shuffled_X = X[:, permutation]
    shuffled_Y = Y[:, permutation]

    num_complete_minibatches = math.floor(m / mini_batch_size)
    for k in range(0, num_complete_minibatches):
        mini_batch_X = shuffled_X[:, k * mini_batch_size: k * mini_batch_size + mini_batch_size]
        mini_batch_Y = shuffled_Y[:, k * mini_batch_size: k * mini_batch_size + mini_batch_size]
        mini_batch = (mini_batch_X, mini_batch_Y)
        mini_batches.append(mini_batch)
    if m % mini_batch_size != 0:
        mini_batch_X = shuffled_X[:, num_complete_minibatches * mini_batch_size: m]
        mini_batch_Y = shuffled_Y[:, num_complete_minibatches * mini_batch_size: m]
        mini_batch = (mini_batch_X, mini_batch_Y)
        mini_batches.append(mini_batch)
    return mini_batches

def data_check(data):
    res = list(np.argmax(data.T, 1))
    num = len(res)
    classes = data.shape[0]
    for i in range(classes):
        print(str(i) + '的比例', round(100.0 * res.count(i) / num, 2), '%')
    print('<------------------分割线---------------------->')

def model(X_train, Y_train, X_test, Y_test, layer_dims, epochs=2000, minibatch_size=64, learning_rate=0.5,
          print_cost=True):
    ops.reset_default_graph()
    n_x, m = X_train.shape
    n_y = Y_train.shape[0]
    costs = []

    X, Y = create_placeholders(n_x, n_y)

    parameters = initialize_parameters_deep(layer_dims)
    # layer_dims = [5, 4, 3]
    ZL = forward_propagation(X, parameters)

    cost = compute_cost(ZL, Y)
    # cost = compute_cost(Z1, Y) + tf.contrib.layers.l1_regularizer(.2)(parameters['W1'])
    # optimizer = tf.train.MomentumOptimizer(learning_rate=learning_rate,momentum=0.99).minimize(cost)
    optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost)
    # optimizer = tf.train.RMSPropOptimizer(learning_rate=learning_rate).minimize(cost)

    init = tf.global_variables_initializer()

    with tf.Session() as sess:
        sess.run(init)
        for epoch in range(epochs):

            minibatch_cost = 0.
            num_minibatches = int(m / minibatch_size)
            minibatches = random_mini_batches(X_train, Y_train, minibatch_size)

            for minibatch in minibatches:
                (minibatch_X, minibatch_Y) = minibatch
                zl, par, _, temp_cost = sess.run([ZL, parameters, optimizer, cost],
                                                 feed_dict={X: minibatch_X, Y: minibatch_Y})
                minibatch_cost += temp_cost / num_minibatches

            if print_cost and epoch % 5 == 0:
                print("Cost after epoch %i: %f" % (epoch, temp_cost))
            if print_cost and epoch % 1 == 0:
                costs.append(minibatch_cost)

        cost_fig(costs, learning_rate)

        predict_op = tf.argmax(tf.transpose(ZL), 1)
        correct_prediction = tf.equal(predict_op, tf.argmax(tf.transpose(Y), 1))

        # Calculate accuracy on the test set
        accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
        train_accuracy = accuracy.eval({X: X_train, Y: Y_train})
        test_accuracy = accuracy.eval({X: X_test, Y: Y_test})

        print("Train Accuracy:", train_accuracy)
        print("Test Accuracy:", test_accuracy)

    return par

def predict(X, parameters):
    L = len(parameters) // 2
    params = {}
    for l in range(1, L):
        params['W' + str(l)] = tf.convert_to_tensor(parameters['W' + str(l)])
        params['b' + str(l)] = tf.convert_to_tensor(parameters['b' + str(l)])

    x = tf.placeholder("float", [784, None])

    z3 = forward_propagation(x, params)
    p = tf.argmax(tf.transpose(z3), 1)

    sess = tf.Session()
    prediction = sess.run(p, feed_dict={x: X})
    result = pd.read_csv('C:/Users/chk01/Desktop/sample_submission.csv')
    result['Label'] = prediction
    result.to_csv('result.csv')
    return prediction

if __name__ == '__main__':
    file = 'kaggle_mnist'
    # parameters = scio.loadmat(file + '_parameter')
    # result = pd.read_csv("C:/Users/chk01/Desktop/test.csv")
    # result_X = result.values.T[0:]
    # print(result_X.shape)
    # predict(result_X, parameters)
    # assert 1 == 0

    train = pd.read_csv("C:/Users/chk01/Desktop/train.csv")
    train_X = train.values.T[1:]
    train_Y = train['label'].values.reshape(1, -1)
    train_Y = convert_to_one_hot(train_Y, 10)

    load_data(train_X, train_Y, 'kaggle_mnist')

    data_train = scio.loadmat(file + '_train')
    X_train = data_train['X']
    Y_train = data_train['Y']
    # print(X_train.shape)
    # (784, 16000)
    # print(Y_train.shape)
    data_test = scio.loadmat(file + '_test')
    X_test = data_test['X']
    Y_test = data_test['Y']

    layer_dims = [784, 10]
    data_check(Y_test)
    data_check(Y_train)
    parameters = model(X_train, Y_train, X_test, Y_test, layer_dims, epochs=200, learning_rate=0.001)

    scio.savemat(file + '_parameter', parameters)


text:
'use strict';

var path = require('path');

var ModelError = require(path.join(__dirname, '..', 'Error'));

/**
 * find cursor chain class
 */
class MongodbFindCursorChain {

    /**
     * @param {Object} collection
     * @param {Object} filter
     * @param {Object} fields
     * @param {DebugTimer} debugTimer
     */
    constructor (collection, filter, fields, debugTimer) {
        this._collection = collection;

        this._cursor = collection.find(filter);

        this._execCallback = null;

        this._debugTimer = null;

        if (debugTimer) {
            this._debugTimer = debugTimer;

            this._debugTimer.data = {
                collection: this._collection.namespace,
                filter: filter,
                fields: fields,
                params: {}
            };
        }

        if (fields) {
            this._cursor.project(fields);
        }

    }

    /**
     * @param {Function} callback
     */
    onExec (callback) {
        this._execCallback = callback;
    }

    /**
     * @param {Object} fields
     * @return {this}
     */
    fields (fields) {
        if (fields) {
            this._cursor.project(fields);
        }

        if (this._debugTimer) {
            this._debugTimer.fields = fields;
        }

        return this;
    }

    /**
     * @param {Object} sort
     * @return {this}
     */
    sort (sort) {
        if (sort) {
            if (this._debugTimer) {
                this._debugTimer.sort = sort;
            }

            this._cursor.sort(sort);
        }

        return this;
    }

    /**
     * @param {Number} limit
     * @return {this}
     */
    limit (limit) {
        if (this._debugTimer) {
            this._debugTimer.limit = limit;
        }

        this._cursor.limit(limit);

        return this;
    }

    /**
     * @param {Number} skip
     * @return {this}
     */
    skip (skip) {
        if (skip) {

            if (this._debugTimer) {
                this._debugTimer.skip = skip;
            }

            this._cursor.skip(skip);
        }

        return this;
    }

    /**
     * @param {Object} data
     * @return {this}
     */
    mapToChain (data) {

        for (var name in data) {
            if (!this[name]) {
                var error = new ModelError(ModelError.CODES.FIND_CURSOR_CHAIN_NO_METHOD);
                error.bind({name: name});
                throw error;
            }

            this[name](data[name]);

            if (this._debugTimer) {
                this._debugTimer.data.params[name] = data[name];
            }
        }

        return this;
    }

    /**
     * exec cursor
     *
     * @return {Promise}
     */
    exec () {
        if (!this._execCallback) {
            throw new ModelError(ModelError.CODES.FIND_CURSOR_CHAIN_NO_CALLBACK);
        }

        return this._execCallback(this._cursor);
    }

}

module.exports = MongodbFindCursorChain;


text:
const color = require('cli-color')
const moment = require('moment')

/**
 * Log util
 *
 * Exports methods to log various events in standardised fashion
 */

module.exports = function (mandi) {
  var lastLoggedTime = ''

  return { task, info, warn, time, log }

  /**
   * Basic log function
   *
   * @return {void}
   */
  function log(message) {
    mandi.emit('log', message)
    if (mandi.config.quiet) { return }
    console.log.apply(console, arguments)
  }

  /**
   * Log task message - statuses are:
   *
   * -1 - Title
   *  0 - Starting
   *  1 - Completed
   *  2 - Failed
   *
   * @return {void}
   */
  function task(message, status = 0) {
    let prefix = ''

    time()

    if (status === -1) {
      prefix = color.cyan('+')
    } else if (status === 0) {
      prefix = color.blackBright('•')
    } else if (status === 1) {
      prefix = color.green('✔')
    } else if (status === 2) {
      prefix = color.red('✘')
    }

    if (prefix) { prefix += ' ' }

    mandi.util.log.log(`${ prefix }${ color.whiteBright(message) }`)
  }

  /**
   * Log single piece of information - e.g. a Number or String
   *
   * @param  {String} label
   * @param  {*} value
   */
  function info(label, value) {
    let prefix = color.yellow('-') + ' '

    time()

    mandi.util.log.log(
      `${ prefix }${ color.whiteBright(label + ':') } ` +
      `${  color.white.bold.italic(value || '-') } `
    )
  }

  /**
   * Log warning message
   *
   * @param  {String} message
   * @return {void}
   */
  function warn(message) {
    time()

    mandi.util.log.log(color.yellow(`[!] ${ message }`))
  }

  /**
   * Log current time (If different from last logged)
   *
   * @return {void}
   */
  function time() {
    let time = `[ ${ moment().format('ddd DD-MM-YYYY HH:mm') } ]`
    if (lastLoggedTime === time) { return }
    lastLoggedTime = time
    mandi.util.log.log(color.blackBright(time))
  }

}


text:
import org.xvolks.jnative.JNative;
import org.xvolks.jnative.Type;
import org.xvolks.jnative.pointers.Pointer;
import org.xvolks.jnative.pointers.memory.MemoryBlockFactory;
import org.xvolks.jnative.exceptions.NativeException;
import org.xvolks.jnative.pointers.memory.NativeMemoryBlock;

/**
 * Class to retrieve info about media files.
 * MediaInfo library (http://MediaArea.net/MediaInfo) is used
 * by the help of JNative (http://jnative.sourceforge.net)
 * to obtain technical the info about the files.
 *
 * @author bro3@users.sourceforge.net
 * @author Info@MediaArea.net
 */
class MediaInfo
{

    /* static_fields */

    final public static int Stream_General       = 0;
    final public static int Stream_Video         = 1;
    final public static int Stream_Audio         = 2;
    final public static int Stream_Text          = 3;
    final public static int Stream_Other         = 4;
    final public static int Stream_Image         = 5;
    final public static int Stream_Menu          = 6;
    final public static int Stream_Max           = 7;

    final public static int Info_Name            = 0;
    final public static int Info_Text            = 1;
    final public static int Info_Measure         = 2;
    final public static int Info_Options         = 3;
    final public static int Info_Name_Text       = 4;
    final public static int Info_Measure_Text    = 5;
    final public static int Info_Info            = 6;
    final public static int Info_HowTo           = 7;
    final public static int Info_Max             = 8;

    /* The MediaInfo handle */
    private String handle = null;
    private JNative new_jnative;

    /* The library to be used */
    private static String libraryName = "";

    /**
     * Constructor that initializes the new MediaInfo object.
     * @throws NativeException  JNative Exception.
     */
    public MediaInfo() throws NativeException, Exception
    {
        setLibraryName();
        New();
    }

    /**
     * Constructor that initializes the new MediaInfo object.
     * @param libraryName       name of libarary to be used
     * @throws NativeException  JNative Exception
     */
    public MediaInfo(String libraryName) throws NativeException, Exception
    {
        setLibraryName(libraryName);
        New();
    }

    /**
     * Method New initializes the MediaInfo handle
     * @throws NativeException  JNative Exception
     */
    private void New() throws NativeException, Exception
    {
        /* Getting the handle */
        new_jnative = new JNative(libraryName, "MediaInfoA_New");
        new_jnative.setRetVal(Type.INT);
        new_jnative.invoke();
        handle = new_jnative.getRetVal();
        Option("CharSet", "UTF-8");
    }

    /**
     * Opens a media file.
     * Overloads method {@link #Open(int, int, int, int)}
     * @param  begin                          buffer with the beginning of datas
     * @param  beginSize                      size of begin
     * @return                                1 for success and 0 for failure
     * @throws HandleNotInitializedException  if the handle is null
     * @throws NativeException                JNative Exception
     * @see                                   #Open(int, int, int, int)
     */
    public int Open(int begin, int beginSize) throws HandleNotInitializedException, NativeException, Exception
    {
        return Open(begin, beginSize, 0, 0);
    }

    /**
     * Opens a media file.
     * @param  begin                          buffer with the beginning of datas
     * @param  beginSize                      size of begin
     * @param  end                            buffer with the end of datas
     * @param  endSize                        size of end
     * @return                                1 for success and 0 for failure
     * @throws HandleNotInitializedException  if the handle is null
     * @throws NativeException                JNative Exception
     */
    public int Open(int begin, int beginSize, int end, int endSize) throws HandleNotInitializedException, NativeException, Exception
    {
        if (handle == null)
            throw new HandleNotInitializedException("Handle is not initialized.");

        /*JNative call */
        JNative jnative = new JNative(libraryName, "MediaInfoA_Open_Buffer");
        jnative.setRetVal(Type.INT);
        jnative.setParameter(0, Type.INT, handle);
        jnative.setParameter(1, Type.INT, String.valueOf(begin));
        jnative.setParameter(2, Type.INT, String.valueOf(beginSize));
        jnative.setParameter(3, Type.INT, String.valueOf(end));
        jnative.setParameter(4, Type.INT, String.valueOf(endSize));
        jnative.invoke();

        /* Retrieving data */
        int ret = Integer.parseInt(jnative.getRetVal());

        return ret;
    }

    /**
     * Opens a media file.
     * @param  filename                       the filename
     * @return                                1 for success and 0 for failure
     * @throws HandleNotInitializedException  if the handle is null
     * @throws NativeException                JNative Exception
     */
    public int Open(String filename) throws HandleNotInitializedException, NativeException, Exception
    {
        if (handle == null)
            throw new HandleNotInitializedException("Handle is not initialized.");

        /* Setting the memory with the byte array returned in UTF-8 format */
        Pointer fileNamePointer = createPointer(filename);

        /*JNative call */
        JNative jnative = new JNative(libraryName, "MediaInfoA_Open");
        jnative.setRetVal(Type.INT);
        jnative.setParameter(0, Type.INT, handle);
        jnative.setParameter(1, fileNamePointer);
        jnative.invoke();

        /* Retrieving data */
        int ret = Integer.parseInt(jnative.getRetVal());

        return ret;
    }

    /**
     * Gets the file info, (if available) according to the previous options set by {@link #Option(String, String)}
     * @return                                the file info
     * @throws HandleNotInitializedException  if the handle is null
     * @throws NativeException                JNative Exception
     */
    public String Inform() throws HandleNotInitializedException, NativeException, Exception
    {
        if (handle == null)
            throw new HandleNotInitializedException("Handle is not initialized.");

        /*JNative call */
        JNative jnative = new JNative(libraryName, "MediaInfoA_Inform");
        jnative.setRetVal(Type.INT);
        jnative.setParameter(0, Type.INT, handle);
        jnative.setParameter(1, Type.INT, "0"); //Necessary for backward compatibility
        jnative.invoke();

        /* Retrieving data */
        String ret = retrieveString(jnative);

        return ret;
    }

    /**
     * Gets the specific info according to the parameters.
     * Overloads method {@link #Get(int, int, String, int, int)}.
     * @param streamKind                      type of stream. Can be any of the Stream_XX values {@link Field details}
     * @param streamNumber                    stream number to process
     * @param parameter                       parameter string (list of strings is available with Option("Info_Parameters");
     * @return                                information
     * @throws HandleNotInitializedException  if the handle is null
     * @throws NativeException                JNative Exception
     * @see                                   #Get(int, int, String, int, int)
     */
    public String Get(int streamKind, int streamNumber, String parameter) throws HandleNotInitializedException, NativeException, Exception
    {
        return Get(streamKind, streamNumber, parameter, MediaInfo.Info_Name, MediaInfo.Info_Text);
    }

    /**
     * Gets the specific info according to the parameters.
     * Overloads method {@link #Get(int, int, String, int, int)}
     * @param streamKind                      type of stream. Can be any of the Stream_XX values {@link Field details}
     * @param streamNumber                    stream to process
     * @param parameter                       parameter string (list of strings is available with Option("Info_Parameters");
     * @param infoKind                        type of info. Can be any of the Info_XX values {@link Field details}
     * @return                                desired information
     * @throws HandleNotInitializedException  if the handle is null
     * @throws NativeException                JNative Exception
     * @see                                   #Get(int, int, String, int, int)
     */
    public String Get(int streamKind, int streamNumber, String parameter, int infoKind) throws HandleNotInitializedException, NativeException, Exception
    {
        return Get(streamKind, streamNumber, parameter, infoKind, MediaInfo.Info_Name);
    }

    /**
     * Gets the specific file info according to the parameters.
     * @param streamKind                      type of stream. Can be any of the Stream_XX values {@link Field details}
     * @param streamNumber                    stream to process
     * @param parameter                       parameter string (list of strings is available with Option("Info_Parameters");
     * @param infoKind                        type of info. Can be any of the Info_XX values {@link Field details}
     * @param searchKind                      type of search. Can be any of the Info_XX values {@link Field details}
     * @return                                desired information
     * @throws HandleNotInitializedException  if the handle is null
     * @throws NativeException                JNative Exception
     */
    public String Get(int streamKind, int streamNumber, String parameter, int infoKind, int searchKind) throws HandleNotInitializedException, NativeException, Exception
    {
        if (handle == null)
            throw new HandleNotInitializedException("Handle is not initialized.");

        /* Setting the memory with the byte array returned in UTF-8 format */
        Pointer parameterPointer = createPointer(parameter);

        /*JNative call */
        JNative jnative = new JNative(libraryName, "MediaInfoA_Get");
        jnative.setRetVal(Type.INT);
        jnative.setParameter(0, Type.INT, handle);
        jnative.setParameter(1, Type.INT, String.valueOf(streamKind));
        jnative.setParameter(2, Type.INT, String.valueOf(streamNumber));
        jnative.setParameter(3, parameterPointer);
        jnative.setParameter(4, Type.INT, String.valueOf(infoKind));
        jnative.setParameter(5, Type.INT, String.valueOf(searchKind));
        jnative.invoke();

        /* Retrieving data */
        String ret = retrieveString(jnative);

        return ret;
    }

    /**
     * Gets the specific file info according to the parameters.
     * Overloads method {@link #Get(int, int, int, int)}.
     * @param streamKind                      type of stream. Can be any of the Stream_XX values {@link Field details}
     * @param streamNumber                    stream to process
     * @param parameter                       parameter position (count of parameters is available with Count_Get(streamKind, streamNumber) )
     * @return                                desired information
     * @throws HandleNotInitializedException  if the handle is null
     * @throws NativeException                JNative Exception
     * @see                                   #Get(int, int, int, int)
    */
    public String Get(int streamKind, int streamNumber, int parameter) throws HandleNotInitializedException, NativeException, Exception
    {
        return Get(streamKind, streamNumber, parameter, MediaInfo.Info_Text);
    }

    /**
     * Gets the specific file info according to the parameters.
     * @param streamKind                      type of stream. Can be any of the Stream_XX values {@link Field details}
     * @param streamNumber                    stream to process
     * @param parameter                       parameter position (count of parameters is available with Count_Get(streamKind, streamNumber) )
     * @param infoKind                        type of info. Can be any of the Info_XX values {@link Field details}
     * @return                                desired information
     * @throws HandleNotInitializedException  if the handle is null
     * @throws NativeException                JNative Exception
    */
    public String Get(int streamKind, int streamNumber, int parameter, int infoKind) throws HandleNotInitializedException, NativeException, Exception
    {
        if (handle == null)
            throw new HandleNotInitializedException("Handle is not initialized.");

        /*JNative call */
        JNative jnative = new JNative(libraryName, "MediaInfoA_GetI");
        jnative.setRetVal(Type.INT);
        jnative.setParameter(0, Type.INT, handle);
        jnative.setParameter(1, Type.INT, String.valueOf(streamKind));
        jnative.setParameter(2, Type.INT, String.valueOf(streamNumber));
        jnative.setParameter(3, Type.INT, String.valueOf(parameter));
        jnative.setParameter(4, Type.INT, String.valueOf(infoKind));
        jnative.invoke();

        /* Retrieving data */
        String ret = retrieveString(jnative);

        return ret;
    }

    /**
     * Sets the option
     * Overloads method {@link #Option(String, String)}
     * @param option                          name of option
     * @return                                desired information or status of the option
     * @throws HandleNotInitializedException  if the handle is null
     * @throws NativeException                JNative Exception
     * @see #Option(String, String)
     */
    public String Option(String option) throws HandleNotInitializedException, NativeException, Exception
    {
        return Option(option, "");
    }

    /**
     * Sets the option with value
     * @param option                          name of option
     * @param value                           option value
     * @return                                desired information or status of the option
     * @throws HandleNotInitializedException  if the handle is null
     * @throws NativeException                JNative Exception
    */
    public String Option(String option, String value) throws HandleNotInitializedException, NativeException, Exception
    {
        if (handle == null)
            throw new HandleNotInitializedException("Handle is not initialized.");

        /* Setting the memory with the byte array returned in UTF-8 format */
        Pointer optionPointer = createPointer(option);
        Pointer valuePointer = createPointer(value);

        /*JNative call */
        JNative jnative = new JNative(libraryName, "MediaInfoA_Option");
        jnative.setRetVal(Type.INT);
        jnative.setParameter(0, Type.INT, handle);
        jnative.setParameter(1, optionPointer);
        jnative.setParameter(2, valuePointer);
        jnative.invoke();

        /* Retrieving data */
        String ret = retrieveString(jnative);

        return ret;
    }

    /**
     * Sets the option (you do not need to create a MediaInfo handle)
     * Overloads method {@link #Option_Static(String, String)}
     * @param option                          name of option
     * @return                                desired information or status of the option
     * @throws HandleNotInitializedException  if the handle is null
     * @throws NativeException                JNative Exception
     * @see                                   #Option_Static(String, String)
     */
    static public String Option_Static(String option) throws HandleNotInitializedException, NativeException, Exception
    {
        return Option_Static(option, "");
    }

    /**
     * Sets the option (you do not need to create a MediaInfo handle)
     * @param option                          name of option
     * @param value                           option value
     * @return                                desired information or status of the option
     * @throws HandleNotInitializedException  if the handle is null
     * @throws NativeException                JNative Exception
    */
    static public String Option_Static(String option, String value) throws HandleNotInitializedException, NativeException, Exception
    {
        if (libraryName.equals(""))
            setLibraryName();

        /* Setting the memory with the byte array returned in UTF-8 format */
        Pointer optionPointer = createPointer(option);
        Pointer valuePointer = createPointer(value);

        /*JNative call */
        JNative jnative = new JNative(libraryName, "MediaInfoA_Option");
        jnative.setRetVal(Type.INT);
        jnative.setParameter(0, Type.INT, "0");
        jnative.setParameter(1, optionPointer);
        jnative.setParameter(2, valuePointer);
        jnative.invoke();

        /* Retrieving data */
        String ret = retrieveString(jnative);

        return ret;
    }

    /**
     * Gets the state of the libaray
     * @return                                state of the library (between 0 and 10000)
     * @throws HandleNotInitializedException  if the handle is null
     * @throws NativeException                JNative Exception
    */
    public int State_Get() throws HandleNotInitializedException, NativeException, Exception
    {
        if (handle == null)
            throw new HandleNotInitializedException("Handle is not initialized.");

        /*JNative call */
        JNative jnative = new JNative(libraryName, "MediaInfoA_State_Get");
        jnative.setRetVal(Type.INT);
        jnative.setParameter(0, Type.INT, handle);
        jnative.invoke();

        /* Retrieving data */
        int ret = Integer.parseInt(jnative.getRetVal());

        return ret;
    }

    /**
     * Gets the count of streams
     * Overloads method {@link #Count_Get(int, int)}.
     * @param streamKind                      type of stream. Can be any of the Stream_XX values {@link Field details}
     * @return                                count of streams
     * @throws HandleNotInitializedException  if the handle is null
     * @throws NativeException                JNative Exception
     * @see                                   #Count_Get(int, int)
     */
    public int Count_Get(int streamKind) throws HandleNotInitializedException, NativeException, Exception
    {
        return Count_Get(streamKind, -1);
    }

    /**
     * Gets the count of streams
     * @param streamKind                      type of stream. Can be any of the Stream_XX values {@link Field details}
     * @param streamNumber                    stream to process
     * @return                                count of parameters for a specific stream
     * @throws HandleNotInitializedException  if the handle is null
     * @throws NativeException                JNative Exception
     */
    public int Count_Get(int streamKind, int streamNumber) throws HandleNotInitializedException, NativeException, Exception
    {
        if (handle == null)
            throw new HandleNotInitializedException("Handle is not initialized.");

        /*JNative call */
        JNative jnative = new JNative(libraryName, "MediaInfoA_Count_Get");
        jnative.setRetVal(Type.INT);
        jnative.setParameter(0, Type.INT, handle);
        jnative.setParameter(1, Type.INT, String.valueOf(streamKind));
        jnative.setParameter(2, Type.INT, String.valueOf(streamNumber));
        jnative.invoke();

        /* Retrieving data */
        int retval = Integer.parseInt(jnative.getRetVal());

        return retval;
    }

    /**
     * Deletes the handle
     * @throws HandleNotInitializedException  if the handle is null
     * @throws NativeException                JNative Exception
     */
    protected void finalize() throws HandleNotInitializedException, NativeException, Exception
    {
        if (handle == null)
            throw new HandleNotInitializedException("Handle is not initialized.");

        /*JNative call */
        JNative jnative = new JNative(libraryName, "MediaInfoA_Delete");
        jnative.setParameter(0, Type.INT, handle);
        jnative.invoke();
    }

    /**
     * Closes the handle
     * @throws HandleNotInitializedException  if the handle is null
     * @throws NativeException                JNative Exception
     */
    public void Close() throws HandleNotInitializedException, NativeException, Exception
    {
        if (handle == null)
            throw new HandleNotInitializedException("Handle is not initialized.");

        /*JNative call */
        JNative jnative = new JNative(libraryName, "MediaInfoA_Close");
        jnative.setParameter(0, Type.INT, handle);
        jnative.invoke();
    }

     /**
     * Create a memory pointer for giving it to an external library
     * @param value            The string to give
      * @return                 A pointer to the memory
    */
    static Pointer createPointer(String value) throws Exception
    {
        value+="\0";
        byte[] array=value.getBytes("UTF-8");
        Pointer valuePointer = new Pointer(MemoryBlockFactory.createMemoryBlock(array.length));
        valuePointer.setMemory(array);
        return valuePointer;
    }

     /**
     * Create a string from a memory pointer
     * @param jnative          The jnative handler
      * @return                 A string
    */
    static String retrieveString(JNative jnative) throws Exception
    {
        int address = Integer.parseInt(jnative.getRetVal());
        byte[]  strEnd          ={0};
        int     howFarToSearch  =10000;
        int     length          =0;

        while (true)
        {
            int pos=JNative.searchNativePattern(address+length, strEnd, howFarToSearch);
            if (pos == -1)
                howFarToSearch+=10000; //The strEnd wasn't found
            else
            {
                length+=pos;
                break;
            }
        }

        if (length > 0)
        {
            Pointer retPointer = new Pointer(new NativeMemoryBlock(address, length));
            String fileInfo = new String(retPointer.getMemory(), "UTF-8");
            retPointer.dispose();
            return fileInfo;
        }
        else
            return new String();
    }

    /**
     * Sets the default name of the library to be used.
     * If windows -> "MediaInfo.dll" else -> "libmediainfo.so.0"
     */
    public static void setLibraryName()
    {
        if (libraryName.equals(""))
        {
            String os=System.getProperty("os.name");
            if (os!=null && os.toLowerCase().startsWith("windows"))
                setLibraryName("MediaInfo.dll");
            else if (os!=null && os.toLowerCase().startsWith("mac"))
                setLibraryName("libmediainfo.dynlib.0");
            else
                setLibraryName("libmediainfo.so.0");
        }
    }

    /**
     * Sets the name of the library to be used.
     * @param libName            name of the library
     */
    public static void setLibraryName(String libName)
    {
        libraryName = libName;
    }
}

/**
 * Exception thrown if the handle isn't initialized.
 */
class HandleNotInitializedException extends Exception
{
    private static final long serialVersionUID = 1L;

    HandleNotInitializedException(String msg)
    {
        super(msg);
    }
}


text:
package gui;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;

import connection.Collector;

/**
 * The ActionListener for the DeleteButton.
 * @author Haeldeus
 *
 */
public class DeleteButtonListener implements ActionListener{

	/**
	 * The Collector, that will send the Messages.
	 */
	private Collector c;

	/**
	 * The Gaplist as a selectable List.
	 */
	private JList<String> gaplistModel;

	/**
	 * The Label that displays responses.
	 */
	private JLabel fail;

	/**
	 * The Frame of the Application.
	 */
	private JFrame frame;

	/**
	 * The Constructor for the ActionListener.
	 * @param c	The Collector that will send the Messages.
	 * @param gaplistModel	The Gaplist as a selectable List.
	 * @param fail	The Label, that displays Responses.
	 * @param frame	The Frame, that contains the Fail-Label.
	 */
	public DeleteButtonListener(Collector c, JList<String> gaplistModel, JLabel fail, JFrame frame) {
		this.c = c;
		this.gaplistModel = gaplistModel;
		this.fail = fail;
		this.frame = frame;
	}

	/**
	 * Performs the Action.
	 * @param arg0 Just a stub.
	 */
	public void actionPerformed(ActionEvent arg0) {
		int i = gaplistModel.getSelectedIndex();
		c.deleteFromGaplist(i, fail, frame);
	}

}


text:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <title>Defaults: SkipTo Menu Example Page</title>
    <link href="skipTo.css" rel="stylesheet"/>

        <hgroup>

SkipTo Menu Example: Defaults

        </hgroup>

SkipTo Test Pages

Default

Default: Illinois styling

Default: ARIA styling

Basic: No Actions and no heading level shortcuts

Custom elements, classes and selectors

No landmarks or headings

Selected and all landmarks or headings are the same

Popup Menu Button

Fixed Menu Button

Regions with no accessible name

Test Deprecated Title Feature

Search Region

        <button>Search Button</button>
        Search Hidden<input type="text"/>
        Search Hidden<input type="text"/>
        Search Hidden<input type="text"/>
        Search<input type="text"/>

Quick link 1

Quick link 2

Quick link 3

Quick link 4

Quick link 5

Example Content

Pastrami

                Boudin pastrami cow ham leberkas doner ground round pork. Turducken swine bresaola, flank kielbasa ground round beef ribs chuck meatball shoulder tail leberkas biltong pastrami andouille. Drumstick jowl brisket ribeye ham jerky shank cow bacon. Ham swine chuck, ball tip frankfurter meatball short loin bacon andouille ribeye beef ribs shoulder tail spare ribs bresaola. Swine meatball leberkas bacon. Beef ribs short loin pork belly meatloaf pastrami bacon pig andouille ham jowl pork chop shoulder jerky ribeye. Meatball doner t-bone strip steak tail biltong ham hock, shank jowl.
                Paypal.com

More Pastrami

                        Boudin pastrami cow ham leberkas doner ground round pork. Turducken swine bresaola, flank kielbasa ground round beef ribs chuck meatball shoulder tail leberkas biltong pastrami andouille. Drumstick jowl brisket ribeye ham jerky shank cow bacon. Ham swine chuck, ball tip frankfurter meatball short loin bacon andouille ribeye beef ribs shoulder tail spare ribs bresaola. Swine meatball leberkas bacon. Beef ribs short loin pork belly meatloaf pastrami bacon pig andouille ham jowl pork chop shoulder jerky ribeye. Meatball doner t-bone strip steak tail biltong ham hock, shank jowl.
                        Paypal.com

Turkey

                Turkey tri-tip sirloin tail hamburger, pancetta prosciutto pork chop pork tongue. Salami drumstick bacon jerky, pork sausage ham prosciutto capicola pancetta beef ribs fatback. Bresaola andouille sirloin, fatback beef ribs shoulder leberkas tongue. Shankle shank turducken, flank jerky leberkas strip steak chuck pancetta tail venison pork belly meatball.
                eBay.com

More Turkey

                    Turkey tri-tip sirloin tail hamburger, pancetta prosciutto pork chop pork tongue. Salami drumstick bacon jerky, pork sausage ham prosciutto capicola pancetta beef ribs fatback. Bresaola andouille sirloin, fatback beef ribs shoulder leberkas tongue. Shankle shank turducken, flank jerky leberkas strip steak chuck pancetta tail venison pork belly meatball.
                    eBay.com

Ribeye

                Ribeye turkey beef ribs, ground round pork chop cow venison capicola shank pastrami. Salami pork ball tip tongue chicken tenderloin sausage short loin. Prosciutto jerky chuck sausage. Tri-tip shankle short ribs cow pastrami, sirloin drumstick pig ball tip shank meatball ground round hamburger.
                developer.paypal.com

Beef Chuck

                Doner beef chuck, tongue cow strip steak pork chop meatloaf pastrami short loin sausage ham hock. Pork belly corned beef meatball salami rump pork chop boudin kielbasa leberkas sausage sirloin pig pork venison. Pork tri-tip prosciutto, ground round meatloaf frankfurter filet mignon sirloin turducken. Flank sausage swine pork loin jerky sirloin. Andouille chuck sausage frankfurter meatball.
                Paypal.com

Related topics 1

Related topics 2

Related topics 3

Related topics 4

Related topics 5

Main using main element and hidden headings

More Pastrami

                Boudin pastrami cow ham leberkas doner ground round pork. Turducken swine bresaola, flank kielbasa ground round beef ribs chuck meatball shoulder tail leberkas biltong pastrami andouille. Drumstick jowl brisket ribeye ham jerky shank cow bacon. Ham swine chuck, ball tip frankfurter meatball short loin bacon andouille ribeye beef ribs shoulder tail spare ribs bresaola. Swine meatball leberkas bacon. Beef ribs short loin pork belly meatloaf pastrami bacon pig andouille ham jowl pork chop shoulder jerky ribeye. Meatball doner t-bone strip steak tail biltong ham hock, shank jowl.
                Paypal.com

More Turkey

                Turkey tri-tip sirloin tail hamburger, pancetta prosciutto pork chop pork tongue. Salami drumstick bacon jerky, pork sausage ham prosciutto capicola pancetta beef ribs fatback. Bresaola andouille sirloin, fatback beef ribs shoulder leberkas tongue. Shankle shank turducken, flank jerky leberkas strip steak chuck pancetta tail venison pork belly meatball.
                eBay.com

More Ribeye

                Ribeye turkey beef ribs, ground round pork chop cow venison capicola shank pastrami. Salami pork ball tip tongue chicken tenderloin sausage short loin. Prosciutto jerky chuck sausage. Tri-tip shankle short ribs cow pastrami, sirloin drumstick pig ball tip shank meatball ground round hamburger.
                developer.paypal.com

More Beef Chuck

                Doner beef chuck, tongue cow strip steak pork chop meatloaf pastrami short loin sausage ham hock. Pork belly corned beef meatball salami rump pork chop boudin kielbasa leberkas sausage sirloin pig pork venison. Pork tri-tip prosciutto, ground round meatloaf frankfurter filet mignon sirloin turducken. Flank sausage swine pork loin jerky sirloin. Andouille chuck sausage frankfurter meatball.
                Paypal.com

More fish

                Boudin pastrami cow ham leberkas doner ground round pork. Turducken swine bresaola, flank kielbasa ground round beef ribs chuck meatball shoulder tail leberkas biltong pastrami andouille. Drumstick jowl brisket ribeye ham jerky shank cow bacon. Ham swine chuck, ball tip frankfurter meatball short loin bacon andouille ribeye beef ribs shoulder tail spare ribs bresaola. Swine meatball leberkas bacon. Beef ribs short loin pork belly meatloaf pastrami bacon pig andouille ham jowl pork chop shoulder jerky ribeye. Meatball doner t-bone strip steak tail biltong ham hock, shank jowl.
                Paypal.com

Related Topic 1

            Vel pharetra vel turpis nunc. Velit sed ullamcorper morbi tincidunt ornare. Mauris vitae ultricies leo integer malesuada nunc vel risus commodo. Malesuada bibendum arcu vitae elementum. At augue eget arcu dictum varius duis at. Convallis a cras semper auctor neque vitae tempus. Nunc scelerisque viverra mauris in. Enim nulla aliquet porttitor lacus luctus. In eu mi bibendum neque egestas congue. Pellentesque massa placerat duis ultricies lacus sed turpis tincidunt id. Rhoncus aenean vel elit scelerisque mauris pellentesque pulvinar pellentesque habitant. Aliquam vestibulum morbi blandit cursus. Sagittis vitae et leo duis ut. At ultrices mi tempus imperdiet nulla malesuada pellentesque elit eget. Ut tellus elementum sagittis vitae et leo duis ut. Orci nulla pellentesque dignissim enim sit amet venenatis urna. Netus et malesuada fames ac. Sollicitudin ac orci phasellus egestas. Ut eu sem integer vitae justo eget magna fermentum.

Related Topic 2

            Vel pharetra vel turpis nunc. Velit sed ullamcorper morbi tincidunt ornare. Mauris vitae ultricies leo integer malesuada nunc vel risus commodo. Malesuada bibendum arcu vitae elementum. At augue eget arcu dictum varius duis at. Convallis a cras semper auctor neque vitae tempus. Nunc scelerisque viverra mauris in. Enim nulla aliquet porttitor lacus luctus. In eu mi bibendum neque egestas congue. Pellentesque massa placerat duis ultricies lacus sed turpis tincidunt id. Rhoncus aenean vel elit scelerisque mauris pellentesque pulvinar pellentesque habitant. Aliquam vestibulum morbi blandit cursus. Sagittis vitae et leo duis ut. At ultrices mi tempus imperdiet nulla malesuada pellentesque elit eget. Ut tellus elementum sagittis vitae et leo duis ut. Orci nulla pellentesque dignissim enim sit amet venenatis urna. Netus et malesuada fames ac. Sollicitudin ac orci phasellus egestas. Ut eu sem integer vitae justo eget magna fermentum.

Important Content by ID

Nunc consequat interdum varius sit amet mattis. Lorem mollis aliquam ut porttitor leo a diam sollicitudin tempor. Ac felis donec et odio pellentesque diam volutpat commodo. Enim nulla aliquet porttitor lacus luctus accumsan tortor posuere. Nunc lobortis mattis aliquam faucibus. Sit amet porttitor eget dolor morbi non arcu risus quis. Amet commodo nulla facilisi nullam vehicula ipsum a arcu cursus. Molestie ac feugiat sed lectus vestibulum. Viverra vitae congue eu consequat ac felis donec. Tellus cras adipiscing enim eu. Aenean euismod elementum nisi quis eleifend quam. Velit laoreet id donec ultrices tincidunt arcu non sodales neque. Quis risus sed vulputate odio. Sit amet mauris commodo quis imperdiet massa tincidunt nunc pulvinar.

        Copyright © 2013


text:
package com.tinkerpop.rexster.gremlin.converter;

import com.tinkerpop.blueprints.Element;
import com.tinkerpop.blueprints.util.io.graphson.GraphSONMode;
import com.tinkerpop.blueprints.util.io.graphson.GraphSONUtility;
import com.tinkerpop.pipes.util.structures.Pair;
import com.tinkerpop.pipes.util.structures.Row;
import com.tinkerpop.pipes.util.structures.Table;
import com.tinkerpop.rexster.Tokens;
import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONObject;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * Converts a result from Gremlin to a JSONArray using GraphSON format.
 *
 * @author Blake Eggleston (bdeggleston.github.com)
 */
public class JSONResultConverter implements ResultConverter<JSONArray> {

    private final GraphSONMode mode;
    private final long offsetStart;
    private final long offsetEnd;
    private final Set<String> returnKeys;

    public JSONResultConverter(final GraphSONMode mode, final long offsetStart, final long offsetEnd,
                               final Set<String> returnKeys) {
        this.mode = mode;
        this.offsetEnd = offsetEnd;
        this.offsetStart = offsetStart;
        this.returnKeys = returnKeys;
    }

    public JSONArray convert(final Object result) throws Exception {
        return convert(result, false).getA();
    }

    public Pair<JSONArray, Long> convert(final Object result, final boolean returnTotal) throws Exception {
        JSONArray results = new JSONArray();
        long counter = 0;
        if (result == null) {
            // for example a script like g.clear()
            results = null;

        } else if (result instanceof Table) {
            final Table table = (Table) result;
            final Iterator<Row> rows = table.iterator();

            while (rows.hasNext()) {
                final Row row = rows.next();
                if (counter >= this.offsetStart && counter < this.offsetEnd)
                    results.put(prepareOutput(row));

                if (!returnTotal && counter >= this.offsetEnd)
                    break;

                counter++;
            }
        } else if (result instanceof Iterable) {
            for (Object o : (Iterable) result) {
                if (counter >= this.offsetStart && counter < this.offsetEnd)
                    results.put(prepareOutput(o));

                if (!returnTotal && counter >= this.offsetEnd)
                    break;

                counter++;
            }
        } else if (result instanceof Iterator) {
            final Iterator itty = (Iterator) result;
            while (itty.hasNext()) {
                Object current = itty.next();
                if (counter >= this.offsetStart && counter < this.offsetEnd)
                    results.put(prepareOutput(current));

                if (!returnTotal && counter >= this.offsetEnd)
                    break;

                counter++;
            }
        } else {
            results.put(prepareOutput(result));
        }

        return new Pair<JSONArray, Long>(results, counter);
    }

    private Object prepareOutput(final Object object) throws Exception {
        if (object == null) {
            return null;
        }
        if (object instanceof Element) {
            return GraphSONUtility.jsonFromElement((Element) object, returnKeys, this.mode);
        } else if (object instanceof Row) {
            final Row row = (Row) object;
            final List<String> columnNames = row.getColumnNames();
            final Map<String, Object> map = new HashMap<String, Object>();
            for (String columnName : columnNames) {
                map.put(columnName, prepareOutput(row.getColumn(columnName)));
            }

            return new JSONObject(map);
        } else if (object instanceof Map) {
            final JSONObject jsonObject = new JSONObject();
            final Map map = (Map) object;
            for (Object key : map.keySet()) {
                // force an error here by passing in a null key to the JSONObject.  That way a good error message
                // gets back to the user.
                if (key instanceof Element) {
                    final Element element = (Element) key;
                    final HashMap<String, Object> m = new HashMap<String, Object>();
                    m.put(Tokens._KEY, this.prepareOutput(element));
                    m.put(Tokens._VALUE, this.prepareOutput(map.get(key)));

                    jsonObject.put(element.getId().toString(), new JSONObject(m));
                } else {
                    jsonObject.put(key == null ? null : key.toString(), this.prepareOutput(map.get(key)));
                }
            }

            return jsonObject;
        } else if (object instanceof Table || object instanceof Iterable || object instanceof Iterator) {
            return this.convert(object);
        } else if (object instanceof Number || object instanceof Boolean) {
            return object;
        } else if (object == JSONObject.NULL) {
            return JSONObject.NULL;
        } else {
            return object.toString();
        }
    }
}