text:
package org.apache.harmony.security.provider.crypto;

import java.security.Provider;
import java.security.AccessController;

import org.apache.harmony.security.provider.crypto.RandomBitsSupplier;

/**
 * Implementation of Provider for SecureRandom, MessageDigest and Signature
 * using a Secure Hash Algorithm, SHA-1;
 * see SECURE HASH STANDARD, FIPS PUB 180-1 (http://www.itl.nist.gov/fipspubs/fip180-1.htm)

 *

 * The implementation supports "SHA1PRNG", "SHA-1" and "SHA1withDSA" algorithms described in
 * JavaTM Cryptography Architecture, API Specification & Reference
 */

public final class CryptoProvider extends Provider {

    private static final long serialVersionUID = 7991202868423459598L;

    /**
     * Creates a Provider and puts parameters
     */
    public CryptoProvider() {

        super("Crypto", 1.0, //$NON-NLS-1$
                "HARMONY (SHA1 digest; SecureRandom; SHA1withDSA signature)"); //$NON-NLS-1$

        //  names of classes implementing services
        final String MD_NAME = "org.apache.harmony.security.provider.crypto.SHA1_MessageDigestImpl"; //$NON-NLS-1$
        final String SR_NAME = "org.apache.harmony.security.provider.crypto.SHA1PRNG_SecureRandomImpl"; //$NON-NLS-1$

        final String SIGN_NAME = "org.apache.harmony.security.provider.crypto.SHA1withDSA_SignatureImpl"; //$NON-NLS-1$

        final String SIGN_ALIAS = "SHA1withDSA"; //$NON-NLS-1$

        final String KEYF_NAME =
                 "org.apache.harmony.security.provider.crypto.DSAKeyFactoryImpl"; //$NON-NLS-1$

        AccessController.doPrivileged(new java.security.PrivilegedAction<Void>() {

            public Void run() {

                put("MessageDigest.SHA-1", MD_NAME); //$NON-NLS-1$
                put("MessageDigest.SHA-1 ImplementedIn", "Software"); //$NON-NLS-1$ //$NON-NLS-2$
                put("Alg.Alias.MessageDigest.SHA1", "SHA-1"); //$NON-NLS-1$ //$NON-NLS-2$
                put("Alg.Alias.MessageDigest.SHA", "SHA-1"); //$NON-NLS-1$ //$NON-NLS-2$

                if (RandomBitsSupplier.isServiceAvailable()) {
                    put("SecureRandom.SHA1PRNG", SR_NAME); //$NON-NLS-1$
                    put("SecureRandom.SHA1PRNG ImplementedIn", "Software"); //$NON-NLS-1$ //$NON-NLS-2$
                }

                put("Signature.SHA1withDSA", SIGN_NAME); //$NON-NLS-1$
                put("Signature.SHA1withDSA ImplementedIn", "Software"); //$NON-NLS-1$ //$NON-NLS-2$
                put("Alg.Alias.Signature.SHAwithDSA", SIGN_ALIAS); //$NON-NLS-1$
                put("Alg.Alias.Signature.DSAwithSHA1", SIGN_ALIAS); //$NON-NLS-1$
                put("Alg.Alias.Signature.SHA1/DSA", SIGN_ALIAS); //$NON-NLS-1$
                put("Alg.Alias.Signature.SHA/DSA", SIGN_ALIAS); //$NON-NLS-1$
                put("Alg.Alias.Signature.SHA-1/DSA", SIGN_ALIAS); //$NON-NLS-1$
                put("Alg.Alias.Signature.DSA", SIGN_ALIAS); //$NON-NLS-1$
                put("Alg.Alias.Signature.DSS", SIGN_ALIAS); //$NON-NLS-1$

                put("Alg.Alias.Signature.OID.1.2.840.10040.4.3", SIGN_ALIAS); //$NON-NLS-1$
                put("Alg.Alias.Signature.1.2.840.10040.4.3", SIGN_ALIAS); //$NON-NLS-1$
                put("Alg.Alias.Signature.1.3.14.3.2.13", SIGN_ALIAS); //$NON-NLS-1$
                put("Alg.Alias.Signature.1.3.14.3.2.27", SIGN_ALIAS); //$NON-NLS-1$

                put("KeyFactory.DSA", KEYF_NAME); //$NON-NLS-1$
                put("KeyFactory.DSA ImplementedIn", "Software"); //$NON-NLS-1$ //$NON-NLS-2$
                put("Alg.Alias.KeyFactory.1.3.14.3.2.12", "DSA"); //$NON-NLS-1$ //$NON-NLS-2$
                put("Alg.Alias.KeyFactory.1.2.840.10040.4.1", "DSA"); //$NON-NLS-1$ //$NON-NLS-2$

                return null;
            }
        });
    }
}


text:
import deepFreeze from 'deep-freeze';
import {
  getNavigationRoutes,
  getNavigationIndex,
  getCurrentRouteParams,
  getCurrentRoute,
} from '../navigationSelectors';

describe('getNavigationRoutes', () => {
  test('return routes in navigation stack', () => {
    const state = {
      nav: {
        index: 1,
        routes: [{ routeName: 'first' }, { routeName: 'second' }],
      },
    };
    deepFreeze(state);
    const expectedResult = [{ routeName: 'first' }, { routeName: 'second' }];
    const actualResult = getNavigationRoutes(state);

    expect(actualResult).toEqual(expectedResult);
  });
});

describe('getNavigationIndex', () => {
  test('return index of the current route in navigation', () => {
    const state = {
      nav: {
        index: 1,
        routes: [{ routeName: 'first' }, { routeName: 'second' }],
      },
    };
    deepFreeze(state);
    const expectedResult = 1;
    const actualResult = getNavigationIndex(state);

    expect(actualResult).toEqual(expectedResult);
  });
});

describe('getCurrentRouteParams', () => {
  test('return params of the current route', () => {
    const state = {
      nav: {
        index: 1,
        routes: [
          { routeName: 'first', params: { email: 'a@a.com' } },
          { routeName: 'second', params: { email: 'b@a.com' } },
        ],
      },
    };
    deepFreeze(state);
    const expectedResult = { email: 'b@a.com' };
    const actualResult = getCurrentRouteParams(state);

    expect(actualResult).toEqual(expectedResult);
  });
});

describe('getCurrentRoute', () => {
  test('return name of the current route', () => {
    const state = {
      nav: {
        index: 1,
        routes: [
          { routeName: 'first', params: { email: 'a@a.com' } },
          { routeName: 'second', params: { email: 'b@a.com' } },
        ],
      },
    };
    deepFreeze(state);
    const expectedResult = 'second';
    const actualResult = getCurrentRoute(state);

    expect(actualResult).toEqual(expectedResult);
  });
});

redpajama_set_name: RedPajamaGithub


text:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <LinearLayout
        android:id="@+id/linear_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <Button
            android:id="@+id/take_photo"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/take_photo" />

        <Button
            android:id="@+id/speak1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Speak" />
    </LinearLayout>

    <ImageView
        android:id="@+id/imageview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginTop="75dp" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="45dp"
        android:text="TextView" />

</RelativeLayout>


text:
package com.consol.citrus.vertx.config.annotation;

import com.consol.citrus.TestActor;
import com.consol.citrus.config.annotation.AnnotationConfigParser;
import com.consol.citrus.spi.ReferenceResolver;
import com.consol.citrus.vertx.endpoint.VertxEndpoint;
import com.consol.citrus.vertx.endpoint.VertxEndpointBuilder;
import com.consol.citrus.vertx.factory.VertxInstanceFactory;
import com.consol.citrus.vertx.message.VertxMessageConverter;
import org.springframework.util.StringUtils;

/**
 * @author Christoph Deppisch
 * @since 2.5
 */
public class VertxEndpointConfigParser implements AnnotationConfigParser<VertxEndpointConfig, VertxEndpoint> {

    @Override
    public VertxEndpoint parse(VertxEndpointConfig annotation, ReferenceResolver referenceResolver) {
        VertxEndpointBuilder builder = new VertxEndpointBuilder();

        if (StringUtils.hasText(annotation.host())) {
            builder.host(annotation.host());
        }

        builder.port(annotation.port());

        if (StringUtils.hasText(annotation.address())) {
            builder.address(annotation.address());
        }

        builder.vertxFactory(referenceResolver.resolve(annotation.vertxFactory(), VertxInstanceFactory.class));

        builder.pubSubDomain(annotation.pubSubDomain());

        if (StringUtils.hasText(annotation.messageConverter())) {
            builder.messageConverter(referenceResolver.resolve(annotation.messageConverter(), VertxMessageConverter.class));
        }

        builder.pollingInterval(annotation.pollingInterval());

        builder.timeout(annotation.timeout());

        if (StringUtils.hasText(annotation.actor())) {
            builder.actor(referenceResolver.resolve(annotation.actor(), TestActor.class));
        }

        return builder.initialize().build();
    }
}


text:
module Calculon
  class Railtie < Rails::Railtie
    initializer 'calculon.insert_into_active_record' do
      ActiveSupport.on_load :active_record do
        ActiveRecord::Base.send(:include, Calculon)
      end
    end
  end
end


text:
package com.intellij.psi.stubs;

import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.openapi.progress.ProcessCanceledException;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.util.Computable;
import com.intellij.util.indexing.*;
import com.intellij.util.indexing.impl.InputDataDiffBuilder;
import com.intellij.util.indexing.impl.MapReduceIndexMappingException;
import com.intellij.util.indexing.impl.storage.TransientFileContentIndex;
import com.intellij.util.indexing.storage.VfsAwareIndexStorageLayout;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.io.IOException;
import java.util.Collections;
import java.util.Map;

public final class StubUpdatingIndexStorage extends TransientFileContentIndex<Integer, SerializedStubTree, StubUpdatingIndexStorage.Data> {
  private static final Logger LOG = Logger.getInstance(StubUpdatingIndexStorage.class);

  private StubIndexImpl myStubIndex;
  @Nullable
  private final CompositeBinaryBuilderMap myCompositeBinaryBuilderMap = FileBasedIndex.USE_IN_MEMORY_INDEX
                                                                        ? null
                                                                        : new CompositeBinaryBuilderMap();
  private final @NotNull SerializationManagerEx mySerializationManager;

  StubUpdatingIndexStorage(@NotNull FileBasedIndexExtension<Integer, SerializedStubTree> extension,
                           @NotNull VfsAwareIndexStorageLayout<Integer, SerializedStubTree> layout,
                           @NotNull SerializationManagerEx serializationManager) throws IOException {
    super(extension, layout, null);
    mySerializationManager = serializationManager;
  }

  @Override
  protected void doFlush() throws IOException, StorageException {
    final StubIndexImpl stubIndex = getStubIndex();
    try {
      stubIndex.flush();
      mySerializationManager.flushNameStorage();
    }
    finally {
      super.doFlush();
    }
  }

  @NotNull
  private StubIndexImpl getStubIndex() {
    StubIndexImpl index = myStubIndex;
    if (index == null) {
      myStubIndex = index = (StubIndexImpl)StubIndex.getInstance();
    }
    return index;
  }

  @Override
  public @NotNull Computable<Boolean> mapInputAndPrepareUpdate(int inputId, @Nullable FileContent content)
    throws MapReduceIndexMappingException, ProcessCanceledException {
    Computable<Boolean> indexUpdateComputable = super.mapInputAndPrepareUpdate(inputId, content);
    IndexingStampInfo indexingStampInfo = content == null ? null : StubUpdatingIndex.calculateIndexingStamp(content);

    return () -> {
      try {
        Boolean result = indexUpdateComputable.compute();
        if (Boolean.TRUE.equals(result) && !StaleIndexesChecker.isStaleIdDeletion()) {
          StubTreeLoaderImpl.saveIndexingStampInfo(indexingStampInfo, inputId);
        }
        return result;
      }
      catch (ProcessCanceledException e) {
        LOG.error("ProcessCanceledException is not expected here", e);
        throw e;
      }
    };
  }

  @Override
  public void removeTransientDataForKeys(int inputId, @NotNull InputDataDiffBuilder<Integer, SerializedStubTree> diffBuilder) {
    Map<StubIndexKey<?, ?>, Map<Object, StubIdList>> maps = getStubIndexMaps((StubCumulativeInputDiffBuilder)diffBuilder);

    if (FileBasedIndexEx.DO_TRACE_STUB_INDEX_UPDATE) {
      LOG.info("removing transient data for inputId = " + inputId +
               ", keys = " + ((StubCumulativeInputDiffBuilder)diffBuilder).getKeys() +
               ", data = " + maps);
    }

    super.removeTransientDataForKeys(inputId, diffBuilder);
    removeTransientStubIndexKeys(inputId, maps);
  }

  private static void removeTransientStubIndexKeys(int inputId, @NotNull Map<StubIndexKey<?, ?>, Map<Object, StubIdList>> indexedStubs) {
    StubIndexImpl stubIndex = (StubIndexImpl)StubIndex.getInstance();
    for (StubIndexKey key : indexedStubs.keySet()) {
      stubIndex.removeTransientDataForFile(key, inputId, indexedStubs.get(key));
    }
  }

  @NotNull
  private static Map<StubIndexKey<?, ?>, Map<Object, StubIdList>> getStubIndexMaps(@NotNull StubCumulativeInputDiffBuilder diffBuilder) {
    SerializedStubTree tree = diffBuilder.getSerializedStubTree();
    return tree == null ? Collections.emptyMap() : tree.getStubIndicesValueMap();
  }

  @Override
  protected void doClear() throws StorageException, IOException {
    final StubIndexImpl stubIndex = (StubIndexImpl)StubIndex.getInstance();
    if (stubIndex != null) {
      stubIndex.clearAllIndices();
    }
    super.doClear();
  }

  @Override
  protected void doDispose() throws StorageException {
    try {
      super.doDispose();
    }
    finally {
      try {
        getStubIndex().dispose();
      }
      finally {
        mySerializationManager.performShutdown();
      }
    }
  }

  static class Data extends IndexerIdHolder {
    private final FileType myFileType;

    Data(int indexerId, FileType type) {
      super(indexerId);
      myFileType = type;
    }
  }

  @Override
  public Data getFileIndexMetaData(@NotNull IndexedFile file) {
    IndexerIdHolder data = super.getFileIndexMetaData(file);
    FileType fileType = ProgressManager.getInstance().computeInNonCancelableSection(() -> file.getFileType());
    return new Data(data == null ? -1 : data.indexerId, fileType);
  }

  @Override
  public void setIndexedStateForFileOnFileIndexMetaData(int fileId, @Nullable StubUpdatingIndexStorage.Data fileData) {
    super.setIndexedStateForFileOnFileIndexMetaData(fileId, fileData);
    LOG.assertTrue(fileData != null, "getFileIndexMetaData doesn't return null");
    setBinaryBuilderConfiguration(fileId, fileData);
  }

  @Override
  public void setIndexedStateForFile(int fileId, @NotNull IndexedFile file) {
    super.setIndexedStateForFile(fileId, file);
    setBinaryBuilderConfiguration(fileId, file);
  }

  @Override
  public void setUnindexedStateForFile(int fileId) {
    super.setUnindexedStateForFile(fileId);
    resetBinaryBuilderConfiguration(fileId);
  }

  @Override
  protected FileIndexingState isIndexConfigurationUpToDate(int fileId, @NotNull IndexedFile file) {
    if (myCompositeBinaryBuilderMap == null) return FileIndexingState.UP_TO_DATE;
    try {
      return myCompositeBinaryBuilderMap.isUpToDateState(fileId, file.getFile());
    }
    catch (IOException e) {
      LOG.error(e);
      return FileIndexingState.OUT_DATED;
    }
  }

  @Override
  protected void setIndexConfigurationUpToDate(int fileId, @NotNull IndexedFile file) {
    setBinaryBuilderConfiguration(fileId, file);
  }

  private void setBinaryBuilderConfiguration(int fileId, @NotNull IndexedFile file) {
    if (myCompositeBinaryBuilderMap != null) {
      try {
        myCompositeBinaryBuilderMap.persistState(fileId, file.getFile());
      }
      catch (IOException e) {
        LOG.error(e);
      }
    }
  }

  private void setBinaryBuilderConfiguration(int fileId, @NotNull Data fileData) {
    if (myCompositeBinaryBuilderMap != null) {
      try {
        myCompositeBinaryBuilderMap.persistState(fileId, fileData.myFileType);
      }
      catch (IOException e) {
        LOG.error(e);
      }
    }
  }

  private void resetBinaryBuilderConfiguration(int fileId) {
    if (myCompositeBinaryBuilderMap != null) {
      try {
        myCompositeBinaryBuilderMap.resetPersistedState(fileId);
      }
      catch (IOException e) {
        LOG.error(e);
      }
    }
  }
}


text:
package jibe.tools.fsm.api.test.trafficlight;

import jibe.tools.fsm.annotations.Action;
import jibe.tools.fsm.annotations.StartState;
import jibe.tools.fsm.annotations.State;
import jibe.tools.fsm.annotations.StateMachine;
import jibe.tools.fsm.annotations.Transition;
import jibe.tools.fsm.annotations.TransitionOnTimeout;
import jibe.tools.fsm.api.ActionType;
import jibe.tools.fsm.api.Engine;
import jibe.tools.fsm.core.EngineFactory;

import static java.util.concurrent.TimeUnit.SECONDS;

/**
 *
 */
@StateMachine
public class TrafficLightFSM {

    private Object currentState;

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

        Engine engine = EngineFactory.newInstance().newEngine(new TrafficLightFSM());
        engine.start();

        Thread.sleep(30000);
        engine.event("error");

        Thread.sleep(10000);
        engine.event("fixed");

        Thread.sleep(30000);
        engine.stop();
    }

    @StartState
    private class RedLight {
        @Action(ActionType.OnEnter)
        public void onEnter() {
            System.out.println("RED");
            currentState = this;
        }

        @TransitionOnTimeout(period = 10, timeUnit = SECONDS)
        public RedAndYellowLight timeout() {
            return new RedAndYellowLight();
        }

        @Transition
        public BlinkingYellowLight event(String s) {
            if ("error".equals(s)) {
                return new BlinkingYellowLight();
            }
            return null;
        }
    }

    @State
    private class RedAndYellowLight {
        @Action(ActionType.OnEnter)
        public void onEnter() {
            System.out.println("RED_AND_YELLOW");
            currentState = this;
        }

        @TransitionOnTimeout(period = 2, timeUnit = SECONDS)
        public GreenLight timeout() {
            return new GreenLight();
        }

        @Transition
        public BlinkingYellowLight event(String s) {
            if ("error".equals(s)) {
                return new BlinkingYellowLight();
            }
            return null;
        }
    }

    @State
    private class YellowLight {
        @Action(ActionType.OnEnter)
        public void onEnter() {
            System.out.println("YELLOW");
            currentState = this;
        }

        @TransitionOnTimeout(period = 2, timeUnit = SECONDS)
        public RedLight timeout() {
            return new RedLight();
        }

        @Transition
        public BlinkingYellowLight event(String s) {
            if ("error".equals(s)) {
                return new BlinkingYellowLight();
            }
            return null;
        }
    }

    @State
    private class GreenLight {
        @Action(ActionType.OnEnter)
        public void onEnter() {
            System.out.println("GREEN");
            currentState = this;
        }

        @TransitionOnTimeout(period = 2, timeUnit = SECONDS)
        public YellowLight timeout() {
            return new YellowLight();
        }

        @Transition
        public BlinkingYellowLight event(String s) {
            if ("error".equals(s)) {
                return new BlinkingYellowLight();
            }
            return null;
        }
    }

    @State
    private class BlinkingYellowLight {
        @Action(ActionType.OnEnter)
        public void onEnter() {
            System.out.println("BLINKING_YELLOW");
            currentState = this;
        }

        @Transition
        public RedLight event(String s) {
            if ("fixed".equals(s)) {
                return new RedLight();
            }
            return null;
        }
    }
}


text:
'use strict'

angular.module("schoolines").controller("splashScreenController", ['$location', '$scope', '$window', 'IVLEService', function($location, $scope, $window, IVLEService) {
    $scope.images = ["/images/bgbanner-long.png", "/images/bgbanner-port.png", "/images/nus.jpg", "/images/homework.jpg"];

    $scope.login = function() {
        $window.location.href = IVLEService.getLoginUrl();
    }
}])


text:
	<title>Fyfe Dangerfield's panel show appearances</title>

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

Fyfe Dangerfield's panel show appearances

Fyfe Dangerfield (born 1980-07-07[ref]) has appeared in 1 episodes between 2007-2007.  Fyfe Dangerfield on Wikipedia.

2007

2007-02-14 / Never Mind The Buzzcocks


text:
/* Riot 1.0.0, @license MIT, (c) 2014 Muut Inc + contributors */
(function(riot) { "use strict";

riot.observable = function(el) {
  var callbacks = {}, slice = [].slice;

  el.on = function(events, fn) {
    if (typeof fn === "function") {
      events.replace(/[^\s]+/g, function(name, pos) {
        (callbacks[name] = callbacks[name] || []).push(fn);
        fn.typed = pos > 0;
      });
    }
    return el;
  };

  el.off = function(events) {
    events.replace(/[^\s]+/g, function(name) {
      callbacks[name] = [];
    });
    if (events == "*") callbacks = {};
    return el;
  };

  // only single event supported
  el.one = function(name, fn) {
    if (fn) fn.one = true;
    return el.on(name, fn);
  };

  el.trigger = function(name) {
    var args = slice.call(arguments, 1),
      fns = callbacks[name] || [];

    for (var i = 0, fn; (fn = fns[i]); ++i) {
      if (!fn.busy) {
        fn.busy = true;
        fn.apply(el, fn.typed ? [name].concat(args) : args);
        if (fn.one) { fns.splice(i, 1); i--; }
        fn.busy = false;
      }
    }

    return el;
  };

  return el;

};

var FN = {}, // Precompiled templates (JavaScript functions)
  template_escape = {"\\": "\\\\", "\n": "\\n", "\r": "\\r", "'": "\\'"},
  render_escape = {'&': '&', '"': '"', '<': '<', '>': '>'};

function default_escape_fn(str, key) {
  return str == undefined ? '' : (str+'').replace(/[&\"<>]/g, function(char) {
    return render_escape[char];
  });
}

riot.render = function(tmpl, data, escape_fn) {
  if (escape_fn === true) escape_fn = default_escape_fn;
  tmpl = tmpl || '';

  return (FN[tmpl] = FN[tmpl] || new Function("_", "e", "try { return '" +
    tmpl.replace(/[\\\n\r']/g, function(char) {
      return template_escape[char];

    }).replace(/{\s*([\w\.]+)\s*}/g, "' + (e?e(_.$1,'$1'):_.$1||(_.$1==undefined?'':_.$1)) + '")
      + "' } catch(e) { return '' }"
    )

  )(data, escape_fn);

};

/* Cross browser popstate */

// for browsers only
if (typeof top != "object") return;

var currentHash,
  pops = riot.observable({}),
  listen = window.addEventListener,
  doc = document;

function pop(hash) {
  hash = hash.type ? location.hash : hash;
  if (hash != currentHash) pops.trigger("pop", hash);
  currentHash = hash;
}

/* Always fire pop event upon page load (normalize behaviour across browsers) */

// standard browsers
if (listen) {
  listen("popstate", pop, false);
  doc.addEventListener("DOMContentLoaded", pop, false);

// IE
} else {
  doc.attachEvent("onreadystatechange", function() {
    if (doc.readyState === "complete") pop("");
  });
}

/* Change the browser URL or listen to changes on the URL */
riot.route = function(to) {
  // listen
  if (typeof to === "function") return pops.on("pop", to);

  // fire
  if (history.pushState) history.pushState(0, 0, to);
  pop(to);

};})(typeof top == "object" ? window.riot = {} : exports);


text:
package client

//go:generate mockery -name Client

import (
	"encoding/json"
	"fmt"
	"time"

	"github.com/kelda/kelda/api"
	"github.com/kelda/kelda/api/pb"
	"github.com/kelda/kelda/connection"
	"github.com/kelda/kelda/db"

	"golang.org/x/net/context"
	"google.golang.org/grpc"
)

const (
	// The timeout for making requests to the daemon once we've connected.
	requestTimeout = time.Minute
)

// Client provides methods to interact with the Quilt daemon.
type Client interface {
	// Close the grpc connection.
	Close() error

	// QueryMachines retrieves the machines tracked by the Quilt daemon.
	QueryMachines() ([]db.Machine, error)

	// QueryContainers retrieves the containers tracked by the Quilt daemon.
	QueryContainers() ([]db.Container, error)

	// QueryEtcd retrieves the etcd information tracked by the Quilt daemon.
	QueryEtcd() ([]db.Etcd, error)

	// QueryConnections retrieves the connection information tracked by the
	// Quilt daemon.
	QueryConnections() ([]db.Connection, error)

	// QueryLoadBalancers retrieves the load balancer information tracked by
	// the Quilt daemon.
	QueryLoadBalancers() ([]db.LoadBalancer, error)

	// QueryBlueprints retrieves blueprint information tracked by the Quilt daemon.
	QueryBlueprints() ([]db.Blueprint, error)

	// QueryCounters retrieves the debugging counters tracked with the Quilt daemon.
	QueryCounters() ([]pb.Counter, error)

	// QueryCounters retrieves the debugging counters tracked by a Quilt minion.
	// Only defined on the daemon.
	QueryMinionCounters(string) ([]pb.Counter, error)

	// QueryImages retrieves the image information tracked by the Quilt daemon.
	QueryImages() ([]db.Image, error)

	// Deploy makes a request to the Quilt daemon to deploy the given deployment.
	// Only defined on the daemon.
	Deploy(deployment string) error

	// Version retrieves the Quilt version of the remote daemon.
	Version() (string, error)
}

// Getter obtains a client connected to the given address.
type Getter func(string, connection.Credentials) (Client, error)

type clientImpl struct {
	pbClient pb.APIClient
	cc       *grpc.ClientConn
}

// New creates a new Quilt client connected to `lAddr`.
func New(lAddr string, creds connection.Credentials) (Client, error) {
	proto, addr, err := api.ParseListenAddress(lAddr)
	if err != nil {
		return nil, err
	}

	cc, err := connection.Client(proto, addr, creds.ClientOpts())
	if err != nil {
		if err == context.DeadlineExceeded {
			err = daemonTimeoutError{
				host:         lAddr,
				connectError: err,
			}
		}
		return nil, err
	}

	pbClient := pb.NewAPIClient(cc)
	return clientImpl{
		pbClient: pbClient,
		cc:       cc,
	}, nil
}

// Writes the result into `v` a pointer to a slice of database structs.  For example
// *[]db.Machine.
func query(pbClient pb.APIClient, table db.TableType, v interface{}) error {
	ctx, _ := context.WithTimeout(context.Background(), requestTimeout)
	reply, err := pbClient.Query(ctx, &pb.DBQuery{Table: string(table)})
	if err != nil {
		return err
	}

	replyBytes := []byte(reply.TableContents)
	return json.Unmarshal(replyBytes, v)
}

// Close the grpc connection.
func (c clientImpl) Close() error {
	return c.cc.Close()
}

// QueryMachines retrieves the machines tracked by the Quilt daemon.
func (c clientImpl) QueryMachines() ([]db.Machine, error) {
	var rows []db.Machine
	return rows, query(c.pbClient, db.MachineTable, &rows)
}

// QueryContainers retrieves the containers tracked by the Quilt daemon.
func (c clientImpl) QueryContainers() ([]db.Container, error) {
	var rows []db.Container
	return rows, query(c.pbClient, db.ContainerTable, &rows)
}

// QueryEtcd retrieves the etcd information tracked by the Quilt daemon.
func (c clientImpl) QueryEtcd() ([]db.Etcd, error) {
	var rows []db.Etcd
	return rows, query(c.pbClient, db.EtcdTable, &rows)
}

// QueryConnections retrieves the connection information tracked by the Quilt daemon.
func (c clientImpl) QueryConnections() ([]db.Connection, error) {
	var rows []db.Connection
	return rows, query(c.pbClient, db.ConnectionTable, &rows)
}

// QueryLoadBalancers retrieves the load balancer information tracked by the
// Quilt daemon.
func (c clientImpl) QueryLoadBalancers() ([]db.LoadBalancer, error) {
	var rows []db.LoadBalancer
	return rows, query(c.pbClient, db.LoadBalancerTable, &rows)
}

// QueryBlueprints retrieves the blueprint information tracked by the Quilt daemon.
func (c clientImpl) QueryBlueprints() ([]db.Blueprint, error) {
	var rows []db.Blueprint
	return rows, query(c.pbClient, db.BlueprintTable, &rows)
}

// QueryImages retrieves the image information tracked by the Quilt daemon.
func (c clientImpl) QueryImages() ([]db.Image, error) {
	var rows []db.Image
	return rows, query(c.pbClient, db.ImageTable, &rows)
}

// QueryCounters retrieves the debugging counters tracked with the Quilt daemon.
func (c clientImpl) QueryCounters() ([]pb.Counter, error) {
	ctx, _ := context.WithTimeout(context.Background(), requestTimeout)
	reply, err := c.pbClient.QueryCounters(ctx, &pb.CountersRequest{})
	if err != nil {
		return nil, err
	}

	return parseCountersReply(reply), nil
}

// QueryCounters retrieves the debugging counters tracked by a Quilt minion.
func (c clientImpl) QueryMinionCounters(host string) ([]pb.Counter, error) {
	ctx, _ := context.WithTimeout(context.Background(), requestTimeout)
	reply, err := c.pbClient.QueryMinionCounters(ctx,
		&pb.MinionCountersRequest{Host: host})
	if err != nil {
		return nil, err
	}

	return parseCountersReply(reply), nil
}

func parseCountersReply(reply *pb.CountersReply) (counters []pb.Counter) {
	for _, c := range reply.Counters {
		counters = append(counters, *c)
	}
	return counters
}

// Deploy makes a request to the Quilt daemon to deploy the given deployment.
func (c clientImpl) Deploy(deployment string) error {
	ctx, _ := context.WithTimeout(context.Background(), requestTimeout)
	_, err := c.pbClient.Deploy(ctx, &pb.DeployRequest{Deployment: deployment})
	return err
}

// Version retrieves the Quilt version of the remote daemon.
func (c clientImpl) Version() (string, error) {
	ctx, _ := context.WithTimeout(context.Background(), requestTimeout)
	version, err := c.pbClient.Version(ctx, &pb.VersionRequest{})
	if err != nil {
		return "", err
	}
	return version.Version, nil
}

// daemonTimeoutError represents when we are unable to connect to the Quilt
// daemon because of a timeout.
type daemonTimeoutError struct {
	host         string
	connectError error
}

func (err daemonTimeoutError) Error() string {
	return fmt.Sprintf("Unable to connect to the Quilt daemon at %s: %s. "+
		"Is the quilt daemon running? If not, you can start it with "+
		"`quilt daemon`.", err.host, err.connectError.Error())
}


text:
import { Component } from '@angular/core';

import { DataService } from './data.service';

@Component({
  selector: 'app-root',
  template: `
    <item-input (addItem)="add($event)"></item-input>
    <my-list [listItems]="data"></my-list>
  `
})
export class AppComponent {
  data: Array<string> = [];

  constructor(public dataService: DataService) {
    this.data = dataService.getData();
  }

  add(item: string) {
    this.dataService.addData(item);
  }
}


text:
package com.github.theborakompanioni.gn.article.events;

import com.lmax.disruptor.EventTranslator;

public class ArticleHeartEventTranslator implements EventTranslator<ArticleHeartEvent> {

    private String articleId;

    public ArticleHeartEventTranslator(String articleId) {
        this.articleId = articleId;
    }

    @Override
    public void translateTo(ArticleHeartEvent event, long l) {
        event.setArticleId(articleId);
    }
}


text:
exports.run = (client, message, params) => {
  if (!params[0]) {
    const commandNames = Array.from(client.commands.keys());
    const longest = commandNames.reduce((long, str) => Math.max(long, str.length), 0);
    message.channel.send(`= Command List =\n\n[Use ${client.config.prefix}help <commandname> for details]\n\n${client.commands.map(c => `${client.config.prefix}${c.help.name}${' '.repeat(longest - c.help.name.length)} :: ${c.help.description}`).join('\n')}`, {code:'asciidoc'});
  } else {
    let command = params[0];
    if (client.commands.has(command)) {
      command = client.commands.get(command);
      message.channel.send(`= ${command.help.name} = \n${command.help.description}\nusage::${command.help.usage}`, {code:'asciidoc'});
    }
  }
};

exports.conf = {
  enabled: true,
  guildOnly: false,
  aliases: ['h', 'halp']
};

exports.help = {
  name: 'help',
  description: 'Displays all the available commands for your permission level.',
  usage: 'help [command]'
};


text:
var CoreTable = (function () {

  function initializeTableFixedHead (table) {
    var tableElement = $(table).find('.elements-table__table')
    $(tableElement).floatThead({
      scrollContainer: function (table) {
        return table.closest('.elements-table--fixed')
      }
    })
  }

  function _initTableFixedHead () {
    $('.elements-table.elements-table--fixed').each(function () {
      initializeTableFixedHead(this)
    })
  }

  // Init:
  function init () {
    _initTableFixedHead()
  }

  return {
    init: init,
    initializeTableFixedHead: initializeTableFixedHead
  }

})()


text:
using System.Threading.Tasks;
using ParusnikServiceDesk.Core.ViewModels.Base;

namespace ParusnikServiceDesk.Core.Services.Navigation
{
    public interface INavigationService
    {
        Task InitializeAsync();
        Task NavigateToAsync<TViewModel>() where TViewModel : ViewModelBase;
        Task NavigateToAsync<TViewModel>(object parameter) where TViewModel : ViewModelBase;
        Task RemoveLastFromBackStackAsync();
        Task RemoveBackStackAsync();
    }
}


text:
define(
    ['durandal/app', 'durandal/plugins/router', 'services/logger', 'services/dataservice', './eventoModal'],
    function (app, router, logger, dataservice, EventoModal) {

        var self = this;

        self.currentDate = ko.observable(new Date());
        self.currentViewType = ko.observable('month');
        self.events = ko.observableArray();

        self.activate = function (context) {
            prepare(context);
            getAllEvents();

            return true;
        }

        self.showModalEvent = function () {
            app.showModal(new EventoModal());
        }

        self.dateChanged = function (e, args) {
            var referenceDate = args.selectedDates[0];
            self.currentDate(referenceDate);
            router.replaceLocation('/#/' + self.currentDate().getFullYear() + '/' + (self.currentDate().getMonth() + 1) + '/' + self.currentDate().getDate() + '/' + getViewType());
        }

        return self;

        function prepare(context) {
            if (context.splat) {
                params = context.splat[0].split("/");

                if (params[0] && params[1])
                    setDate(params[0], params[1] - 1, params[2]);

                if (params[3])
                    setViewType(params[3]);
            }
        }

        function setDate(year, month, day) {
            if (day == undefined)
                day = new Date().getDate();

            currentDate(new Date(year, month, day));
        }

        function setViewType(type) {
            if (type == 'semana')
                self.currentViewType('week');
            else if (type == 'dia')
                self.currentViewType('day');
            else
                self.currentViewType('month');
        }

        function getViewType() {
            if (self.currentViewType() == 'week')
                return 'semana';
            else if (self.currentViewType() == 'day')
                return 'dia';
            else
                return 'mes';
        }

        function getAllEvents() {
            dataservice.eventos.getAll(currentDate())
                .then(queryEventsSucceeded)
                .fail(queryEventsFailed);
        }

        function queryEventsSucceeded(data) {
            self.events(data.results);
            //if (data && data.results.length > 0) {
            //    for (var i = 0; i < data.results.length; i++) {
            //        //console.log(data.results[i]);
            //        self.events.push(data.results[i]);
            //        //self.events.push({
            //        //    id: "event1",
            //        //    subject: "Green event." + i,
            //        //    start: new Date(2013, 4, 18, 9),
            //        //    end: new Date(2013, 4, 18, 11),
            //        //    allday: true,
            //        //    description: "The green event.",
            //        //    color: "green"
            //        //});
            //    }
            //}

        }

        function queryEventsFailed(error) {
            logger.logError(error.message, "Erro ao obter eventos");
        }
    });


text:
module Fog
  module HP
    class LB
      class Real

      # Get details for an existing load balancer node
      #
      # ==== Parameters
      # * 'load_balancer_id'<~String> - UUId of the load balancer to get
      # * 'node_id'<~String> - UUId of node to get
      #
      # ==== Returns
      # * response<~Excon::Response>:
      #   * body<~Hash>:
      #     * 'id'<~String> - UUId for the node
      #     * 'address'<~String> - Address for the node
      #     * 'port'<~String> - Port for the node
      #     * 'condition'<~String> - Condition for the node e.g. 'ENABLED'
      #     * 'status'<~String> - Status for the node e.g. 'ONLINE'
        def get_load_balancer_node(load_balancer_id, node_id)
          request(
            :expects => 200,
            :method  => 'GET',
            :path    => "loadbalancers/#{load_balancer_id}/nodes/#{node_id}"
          )
        end
      end

      class Mock
        def get_load_balancer_node(load_balancer_id, node_id)
          response = Excon::Response.new
          if get_load_balancer(load_balancer_id)
           if node = find_node(load_balancer_id, node_id)
             response.status = 200
             response.body = node
             response
           else
             raise Fog::HP::LB::NotFound
           end
          else
            raise Fog::HP::LB::NotFound
          end

        end

        def find_node(load_balancer_id, node_id)
          nodes = list_load_balancer_nodes(load_balancer_id).body['nodes']
          nodes.detect {|n| n['id'] == node_id}
        end

      end
    end
  end
end


text:
import { LoopReducer } from "redux-loop"
import { Action } from "redux"

export type Selector<State, T> =
  ((state: State) => (...args: any[]) => T)

export type SelectorMap<State> = {
  [name: string]: Selector<State, any | undefined>
}

/**
 * Single interface that describes the entire and isolated behaviors of a reducer, its state,
 * and related selectors. By isolating like this, combining reducers becomes much easier and
 * conceptual understanding of
 */
export interface Reduxer<State, Actions extends Action> {

  /**
   * Initial State
   */
  initialState: State

  /**
   * The actual Reducer
   */
  reducer: LoopReducer<State, Actions>

  /**
   * All the selectors using local state
   */
  selectors: SelectorMap<State>

}


text:
package org.kuali.kfs.module.purap.service.impl;

import java.math.BigDecimal;
import java.util.Map;

import org.kuali.kfs.module.purap.businessobject.ElectronicInvoiceItem;
import org.kuali.kfs.module.purap.businessobject.ElectronicInvoiceItemMapping;
import org.kuali.kfs.module.purap.businessobject.ElectronicInvoiceRejectItem;
import org.kuali.kfs.module.purap.businessobject.PurchaseOrderItem;
import org.kuali.kfs.module.purap.util.ElectronicInvoiceUtils;
import org.kuali.rice.core.api.util.type.KualiDecimal;

public class ElectronicInvoiceItemHolder {

    private ElectronicInvoiceOrderHolder orderHolder;
    private ElectronicInvoiceRejectItem rejectItem;
    private ElectronicInvoiceItem invoiceItem;
    private PurchaseOrderItem poItem;
    private Map<String,ElectronicInvoiceItemMapping> itemTypeMappings;

    private boolean isRejectItemHolder;
    private boolean validateHeader;

    public ElectronicInvoiceItemHolder(ElectronicInvoiceRejectItem rejectItem,
                                       Map itemTypeMappings,
                                       PurchaseOrderItem poItem,
                                       ElectronicInvoiceOrderHolder orderHolder){

        if (rejectItem == null){
            throw new NullPointerException("ElectronicInvoiceRejectItem should not be null");
        }

        this.rejectItem = rejectItem;
        this.poItem = poItem;
        this.orderHolder = orderHolder;

        isRejectItemHolder = true;
    }

    public ElectronicInvoiceItemHolder(ElectronicInvoiceItem invoiceItem,
                                        Map itemTypeMappings,
                                        PurchaseOrderItem poItem,
                                        ElectronicInvoiceOrderHolder orderHolder){

        if (invoiceItem == null){
            throw new NullPointerException("ElectronicInvoiceItem should not be null");
        }

        this.invoiceItem = invoiceItem;
        this.poItem = poItem;
        this.orderHolder = orderHolder;

        isRejectItemHolder = false;
    }

    public Integer getInvoiceItemLineNumber(){
        if (isRejectItemHolder()){
            return rejectItem.getInvoiceReferenceItemLineNumber();
        }else{
           return invoiceItem.getReferenceLineNumberInteger();
        }
    }

    public String getInvoiceItemDescription(){
        if (isRejectItemHolder()){
            return rejectItem.getInvoiceReferenceItemDescription();
        }else{
           return invoiceItem.getReferenceDescription();
        }
    }

    public PurchaseOrderItem getPurchaseOrderItem(){
        return poItem;
    }

    public String getCatalogNumberStripped(){
        if (isRejectItemHolder()){
            return ElectronicInvoiceUtils.stripSplChars(rejectItem.getInvoiceItemCatalogNumber());
        }else{
            return ElectronicInvoiceUtils.stripSplChars(invoiceItem.getCatalogNumber());
        }
    }

    public BigDecimal getUnitPrice(){
        if (isRejectItemHolder()){
            return rejectItem.getInvoiceItemUnitPrice();
        }else{
            return invoiceItem.getInvoiceLineUnitCostBigDecimal();
        }
    }

    public String getUnitPriceCurrency(){
        if (isRejectItemHolder()){
            return rejectItem.getInvoiceItemUnitPriceCurrencyCode();
        }else{
            return invoiceItem.getUnitPriceCurrency();
        }
    }

    public BigDecimal getQuantity(){
        if (isRejectItemHolder()){
            return rejectItem.getInvoiceItemQuantity();
        }else{
            return invoiceItem.getInvoiceLineQuantityBigDecimal();
        }
    }

    public KualiDecimal getSubTotalAmount(){
        if (isRejectItemHolder()){
            return new KualiDecimal(rejectItem.getInvoiceItemSubTotalAmount().setScale(KualiDecimal.SCALE, KualiDecimal.ROUND_BEHAVIOR));
        }else{
            return new KualiDecimal(invoiceItem.getInvoiceLineSubTotalAmountBigDecimal());
        }
    }

    public boolean isRejectItemHolder(){
        return isRejectItemHolder;
    }

    public ElectronicInvoiceItemMapping getItemMapping(String invoiceItemTypeCode){
        if (itemTypeMappings == null){
            return null;
        }else{
            return itemTypeMappings.get(invoiceItemTypeCode);
        }
    }

    public String getItemTypeCode(String invoiceItemTypeCode) {

        ElectronicInvoiceItemMapping itemMapping = getItemMapping(invoiceItemTypeCode);

        if (itemMapping != null) {
            return itemMapping.getItemTypeCode();
        }
        else {
            return null;
        }
    }

    public String getInvoiceItemCatalogNumber(){
        if (isRejectItemHolder()){
            return rejectItem.getInvoiceItemCatalogNumber();
        }else{
            return invoiceItem.getReferenceItemIDSupplierPartID();
        }
    }

    public String getInvoiceItemUnitOfMeasureCode(){
        if (isRejectItemHolder()){
            return rejectItem.getInvoiceItemUnitOfMeasureCode();
        }else{
            return invoiceItem.getUnitOfMeasure();
        }
    }

    public boolean isUnitOfMeasureAcceptIndicatorEnabled() {
        if (isRejectItemHolder()){
            return rejectItem.isUnitOfMeasureAcceptIndicator();
        }else{
            return false;
        }
    }

    public boolean isCatalogNumberAcceptIndicatorEnabled() {
        if (isRejectItemHolder()){
            return rejectItem.isCatalogNumberAcceptIndicator();
        }else{
            return false;
        }
    }

    public BigDecimal getInvoiceItemUnitPrice(){
        if (isRejectItemHolder()){
            return rejectItem.getInvoiceItemUnitPrice();
        }else{
            return invoiceItem.getInvoiceLineUnitCostBigDecimal();
        }
    }

    public BigDecimal getInvoiceItemQuantity(){
        if (isRejectItemHolder()){
            return rejectItem.getInvoiceItemQuantity();
        }else{
            return invoiceItem.getInvoiceLineQuantityBigDecimal();
        }
    }

    public BigDecimal getInvoiceItemSubTotalAmount(){
        if (isRejectItemHolder()){
            return rejectItem.getInvoiceItemSubTotalAmount();
        }else{
            return invoiceItem.getInvoiceLineSubTotalAmountBigDecimal();
        }
    }

    public BigDecimal getTaxAmount(){
        if (isRejectItemHolder()){
            return rejectItem.getInvoiceItemTaxAmount();
        }else{
            return invoiceItem.getInvoiceLineTaxAmountBigDecimal();
        }
    }

    public ElectronicInvoiceOrderHolder getInvoiceOrderHolder(){
        return orderHolder;
    }
}


text:
var mongodbUri = require('mongodb-uri');
var mongodb = require('mongodb');

module.exports = AdminClient;

function AdminClient(url) {
  if (!(this instanceof AdminClient)) return new AdminClient(url);

  this.url = url;
  this.uri = mongodbUri.parse(url);

  this.client = null;
  this.pending = [];
  this.connecting = false;

  this.connect = this.connect.bind(this);
}

AdminClient.prototype.connect = function connect(fn) {
  var self = this;

  if (this.client) return fn && fn(null, this.client);
  if (fn) this.pending.push(fn);
  if (this.connecting) return;

  this.connecting = true;

  open(this.uri, function(err, client){
    if (err) throw err;

    self.client = client;

    if (self.pending.length) {
      self.pending.forEach(self.connect);
      self.pending.length = 0;
    }
  });
}

function createServer(host) {
  return new mongodb.Server(host.host, host.port);
}

function createServers(hosts) {
  if (hosts.length === 1) {
    return createServer(hosts[0]);
  } else if (hosts.length > 1) {
    return new mongodb.ReplSetServers(hosts.map(createServer));
  } else {
    throw new Error('Must provide a valid mongodb server uri string.');
  }
}

function open(uri, fn) {
  var mongoClient = new mongodb.MongoClient(createServers(uri.hosts));

  mongoClient.open(function(err, newClient){
    if (err) return fn(err);

    var adminDb = newClient.db('admin');

    adminDb.authenticate(uri.username, uri.password, function(err){
      if (err) return fn(err);
      fn(null, newClient);
    });
  });
}


text:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="54dp"
        android:layout_marginLeft="23dp"
        android:layout_marginRight="23dp"
        android:background="@drawable/common_white_list">

        <TextView
            android:id="@+id/name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:textColor="#333333"
            android:textSize="14sp" />

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_centerVertical="true"
            android:layout_marginRight="3dp"
            android:src="@drawable/arrow_right" />
    </RelativeLayout>

</FrameLayout>


text:
/* iCheck plugin Minimal skin, aero
----------------------------------- */
.icheckbox_minimal-aero,
.iradio_minimal-aero {
    display: inline-block;
    *display: inline;
    vertical-align: middle;
    margin: 0;
    padding: 0;
    width: 18px;
    height: 18px;
    background: url(aero.png) no-repeat;
    border: none;
    cursor: pointer;
}

.icheckbox_minimal-aero {
    background-position: 0 0;
}
    .icheckbox_minimal-aero.hover {
        background-position: -20px 0;
    }
    .icheckbox_minimal-aero.checked {
        background-position: -40px 0;
    }
    .icheckbox_minimal-aero.disabled {
        background-position: -60px 0;
        cursor: default;
    }
    .icheckbox_minimal-aero.checked.disabled {
        background-position: -80px 0;
    }

.iradio_minimal-aero {
    background-position: -100px 0;
}
    .iradio_minimal-aero.hover {
        background-position: -120px 0;
    }
    .iradio_minimal-aero.checked {
        background-position: -140px 0;
    }
    .iradio_minimal-aero.disabled {
        background-position: -160px 0;
        cursor: default;
    }
    .iradio_minimal-aero.checked.disabled {
        background-position: -180px 0;
    }

/* Retina support */
@media only screen and (-webkit-min-device-pixel-ratio: 1.5),
       only screen and (-moz-min-device-pixel-ratio: 1.5),
       only screen and (-o-min-device-pixel-ratio: 3/2),
       only screen and (min-device-pixel-ratio: 1.5) {
    .icheckbox_minimal-aero,
    .iradio_minimal-aero {
        background-image: url(aero@2x.png);
        -webkit-background-size: 200px 20px;
        background-size: 200px 20px;
    }
}


text:
require 'yaml'

class Money
  class Currency
    module Loader
      class << self
        def load_currencies
          currency_data_path = File.expand_path("../../../../config", __FILE__)

          currencies = {}
          currencies.merge! YAML.load_file("#{currency_data_path}/currency_historic.yml")
          currencies.merge! YAML.load_file("#{currency_data_path}/currency_non_iso.yml")
          currencies.merge! YAML.load_file("#{currency_data_path}/currency_iso.yml")
          deep_deduplicate!(currencies)
        end

        private

        def deep_deduplicate!(data)
          case data
          when Hash
            return data if data.frozen?
            data.transform_keys! { |k| deep_deduplicate!(k) }
            data.transform_values! { |v| deep_deduplicate!(v) }
            data.freeze
          when Array
            return data if data.frozen?
            data.map! { |d| deep_deduplicate!(d) }.freeze
          when String
            -data
          else
            data.freeze
          end
        end
      end
    end
  end
end


text:
package com.github.bolkunetsalexandre.autoservice.utils;

import java.util.Date;

import com.github.bolkunetsalexandre.autoservice.beans.AEntity;

public class Printer {

	public static void print(Date date) {
		System.out.println(DateWorker.dateToString(date));
	}

	public static void print(String info) {
		System.out.println(info);
	}

	public static void print(String[] arrayStr) {
		for(String str : arrayStr) {
			if(str!=null) {
				print(str);
			}
		}
	}

	public static void print(AEntity entity) {
		print(entity.toString());
	}

	public static void printArray(AEntity[] entityList) {
		for(AEntity entity : entityList) {
			if(entity!=null) {
				print(entity);
			}
		}
	}

	public static void print(int[] entity) {
		for(int i = 0; i<entity.length; i++)
			print(String.valueOf(entity[i]));
	}

}


text:
package io.crate.execution.dml.upsert;

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

import io.crate.common.collections.Lists2;
import io.crate.common.collections.Tuple;
import io.crate.data.Input;
import io.crate.execution.engine.collect.CollectExpression;
import io.crate.expression.InputFactory;
import io.crate.expression.reference.ReferenceResolver;
import io.crate.expression.symbol.Symbol;
import io.crate.metadata.ColumnIdent;
import io.crate.metadata.Reference;
import io.crate.metadata.TransactionContext;
import io.crate.metadata.doc.DocTableInfo;
import io.crate.sql.tree.CheckConstraint;

public final class CheckConstraints<T, E extends CollectExpression<T, ?>> {

    private final List<Input<?>> inputs = new ArrayList<>();
    private final List<E> expressions;
    private final List<ColumnIdent> notNullColumns;
    private final List<Tuple<? extends Input<?>, CheckConstraint<Symbol>>> checkConstraints;

    CheckConstraints(TransactionContext txnCtx,
                     InputFactory inputFactory,
                     ReferenceResolver<E> refResolver,
                     DocTableInfo table) {
        InputFactory.Context<E> ctx = inputFactory.ctxForRefs(txnCtx, refResolver);
        notNullColumns = new ArrayList<>(table.notNullColumns());
        for (int i = 0; i < notNullColumns.size(); i++) {
            ColumnIdent columnIdent = notNullColumns.get(i);
            Reference notNullRef = table.getReadReference(columnIdent);
            assert notNullRef != null
                : "ColumnIdent retrieved via `table.notNullColumns` must be available via `table.getReadReference`";
            inputs.add(ctx.add(notNullRef));
        }
        expressions = ctx.expressions();
        checkConstraints = Lists2.map(table.checkConstraints(), chk -> new Tuple<>(ctx.add(chk.expression()), chk));
    }

    /**
     * The method must be called on {@code T values}, e.g. source maps,
     * rows that already contain values of evaluated generated column
     * expressions.
     */
    public void validate(T values) {
        for (int i = 0; i < expressions.size(); i++) {
            expressions.get(i).setNextRow(values);
        }
        for (int i = 0; i < inputs.size(); i++) {
            Object val = inputs.get(i).value();
            if (val == null) {
                throw new IllegalArgumentException("\"" + notNullColumns.get(i) + "\" must not be null");
            }
        }
        for (int i = 0; i < checkConstraints.size(); i++) {
            Tuple<? extends Input<?>, CheckConstraint<Symbol>> checkEntry = checkConstraints.get(i);
            Input<?> checkInput = checkEntry.v1();
            Object value = checkInput.value();
            if (value == null) {
                // SQL semantics: If a column is omitted from an INSERT/UPDATE statement,
                // CHECK constraints should not fail. Same for writing explicit `null` values.
                continue;
            }
            assert value instanceof Boolean : "expected a boolean value";
            if (!((Boolean) value).booleanValue()) {
                CheckConstraint<Symbol> chk = checkEntry.v2();
                throw new IllegalArgumentException(String.format(
                    Locale.ENGLISH,
                    "Failed CONSTRAINT %s CHECK (%s) and values %s",
                    chk.name(), chk.expressionStr(), values));
            }
        }
    }
}


text:
CLR_RT_HeapBlock_String* CLR_RT_HeapBlock_String::CreateInstance( CLR_RT_HeapBlock& reference, CLR_UINT32 length )
{
    NATIVE_PROFILE_CLR_CORE();
    CLR_UINT32               totLength = sizeof(CLR_RT_HeapBlock_String) + length + 1;
    CLR_RT_HeapBlock_String* str;

    reference.SetObjectReference( NULL );

    str = (CLR_RT_HeapBlock_String*)g_CLR_RT_ExecutionEngine.ExtractHeapBytesForObjects( DATATYPE_STRING, 0, totLength );
    if(str)
    {
        char* szText = (char*)&str[ 1 ]; szText[ 0 ] = 0;

#if defined(NANOCLR_NO_ASSEMBLY_STRINGS)
        str->SetStringText( szText );
#else
        str->SetStringText( szText, NULL );
#endif

        reference.SetObjectReference( str );
    }

    return str;
}

HRESULT CLR_RT_HeapBlock_String::CreateInstance( CLR_RT_HeapBlock& reference, const char* szText )
{
    NATIVE_PROFILE_CLR_CORE();
    NANOCLR_HEADER();

    if(!szText) szText = "";

    NANOCLR_SET_AND_LEAVE(CLR_RT_HeapBlock_String::CreateInstance( reference, szText, (CLR_UINT32)hal_strlen_s( szText ) ));

    NANOCLR_NOCLEANUP();
}

HRESULT CLR_RT_HeapBlock_String::CreateInstance( CLR_RT_HeapBlock& reference, const char* szText, CLR_UINT32 length )
{
    NATIVE_PROFILE_CLR_CORE();
    NANOCLR_HEADER();

    CLR_RT_HeapBlock_String* str;
    char*                    szTextDst;

    str = CreateInstance( reference, length ); CHECK_ALLOCATION(str);

    szTextDst = (char*)str->StringText();

    memcpy( szTextDst, szText, length ); szTextDst[ length ] = 0;

    NANOCLR_NOCLEANUP();
}

HRESULT CLR_RT_HeapBlock_String::CreateInstance( CLR_RT_HeapBlock& reference, const char* szText, CLR_RT_Assembly* assm )
{
    NATIVE_PROFILE_CLR_CORE();
    NANOCLR_HEADER();

    CLR_RT_HeapBlock_String* str;

    reference.SetObjectReference( NULL );

    str = (CLR_RT_HeapBlock_String*)g_CLR_RT_ExecutionEngine.ExtractHeapBytesForObjects( DATATYPE_STRING, 0, sizeof(CLR_RT_HeapBlock_String) ); CHECK_ALLOCATION(str);

    reference.SetObjectReference( str );

#if defined(NANOCLR_NO_ASSEMBLY_STRINGS)
    (void)szText;
    (void)assm;

    NANOCLR_CHECK_HRESULT( CLR_RT_HeapBlock_String::CreateInstance( reference, szText ) );
#else
    str->SetStringText( szText, assm );
#endif

    NANOCLR_NOCLEANUP();
}

HRESULT CLR_RT_HeapBlock_String::CreateInstance( CLR_RT_HeapBlock& reference, CLR_UINT32 token, CLR_RT_Assembly* assm )
{
    NATIVE_PROFILE_CLR_CORE();
    return CreateInstance( reference, assm->GetString( CLR_DataFromTk( token ) ), assm );
}

HRESULT CLR_RT_HeapBlock_String::CreateInstance( CLR_RT_HeapBlock& reference, CLR_UINT16* szText, CLR_UINT32 length )
{
    NATIVE_PROFILE_CLR_CORE();
    NANOCLR_HEADER();

    CLR_RT_UnicodeHelper     uh;             uh.SetInputUTF16     ( szText );
    CLR_UINT32               lengthInBytes = uh.CountNumberOfBytes( length );
    CLR_RT_HeapBlock_String* str           = CreateInstance( reference, lengthInBytes ); CHECK_ALLOCATION(str);

    uh.m_outputUTF8      = (CLR_UINT8*)str->StringText();
    uh.m_outputUTF8_size = lengthInBytes + 1;

    uh.ConvertToUTF8( length, false );

    NANOCLR_NOCLEANUP();
}

CLR_RT_HeapBlock_String* CLR_RT_HeapBlock_String::GetStringEmpty()
{
    return g_CLR_RT_TypeSystem.m_assemblyMscorlib->GetStaticField( Library_corlib_native_System_String::FIELD_STATIC__Empty )->DereferenceString();
}


text:
package org.aikodi.java.core.enumeration;

import java.util.List;

import org.aikodi.chameleon.core.declaration.BasicDeclaration;
import org.aikodi.chameleon.core.declaration.Declaration;
import org.aikodi.chameleon.core.declaration.Name;
import org.aikodi.chameleon.core.lookup.LocalLookupContext;
import org.aikodi.chameleon.core.lookup.LookupException;
import org.aikodi.chameleon.core.validation.Valid;
import org.aikodi.chameleon.core.validation.Verification;
import org.aikodi.chameleon.oo.expression.Expression;
import org.aikodi.chameleon.oo.type.ClassBody;
import org.aikodi.chameleon.oo.type.ClassWithBody;
import org.aikodi.chameleon.oo.type.DeclarationWithType;
import org.aikodi.chameleon.oo.type.RegularType;
import org.aikodi.chameleon.oo.type.Type;
import org.aikodi.chameleon.util.Util;
import org.aikodi.chameleon.util.association.Multi;
import org.aikodi.chameleon.util.association.Single;
import org.aikodi.rejuse.contract.Contracts;

public class EnumConstant extends BasicDeclaration implements DeclarationWithType {

	public EnumConstant(String name) {
		setSignature(new Name(name));
	}

	@Override
	public EnumConstant cloneSelf() {
		return new EnumConstant(name());
	}

	public List<Declaration> getIntroducedMembers() {
		return Util.createNonNullList(this);
	}

	/**
	 * ACTUAL PARAMETERS
	 */
 private Multi<Expression> _parameters = new Multi<Expression>(this);

  public void addParameter(Expression parameter) {
  	add(_parameters, parameter);
  }

  public void addAllParameters(List<Expression> parameters) {
  	Contracts.notNull(parameters, "The list of parameters cannot be null.");
  	parameters.forEach(p -> addParameter(p));
  }

  public void removeParameter(Expression parameter) {
  	remove(_parameters,parameter);
  }

  public List<Expression> actualArguments() {
    return _parameters.getOtherEnds();
  }

	private Single<ClassWithBody> _anonymousType = new Single<ClassWithBody>(this, "type");

	public void setBody(ClassBody body) {
		if(body == null) {
			_anonymousType.connectTo(null);
		} else {
			set(_anonymousType,createAnonymousType(body));
		}
	}

	public ClassWithBody getAnonymousType() {
		return _anonymousType.getOtherEnd();
	}

	private void setAnonymousType(ClassWithBody type) {
		set(_anonymousType, type);
	}

  private ClassWithBody createAnonymousType(ClassBody body) {
  	RegularType anon = new EnumConstantType();
	  anon.setBody(body);
		return anon;
	}

  public ClassBody body() {
  	ClassWithBody anonymousType = getAnonymousType();
  	if(anonymousType != null) {
  		return anonymousType.body();
  	} else {
  		return null;
  	}
  }

	public Type declarationType() throws LookupException {
		return lexical().nearestAncestor(Type.class);
	}

	@Override
	public LocalLookupContext<?> targetContext() throws LookupException {
		Type type = getAnonymousType();
		if(type == null) {
		  return lexical().nearestAncestor(EnumType.class).targetContext();
		}
    return type.targetContext();
	}

}


text:
namespace headless {
class HeadlessBrowserImpl;

namespace protocol {
class HeadlessDevToolsSession;
}

class HeadlessDevToolsManagerDelegate
    : public content::DevToolsManagerDelegate {
 public:
  explicit HeadlessDevToolsManagerDelegate(
      base::WeakPtr<HeadlessBrowserImpl> browser);
  ~HeadlessDevToolsManagerDelegate() override;

  // DevToolsManagerDelegate implementation:
  void HandleCommand(content::DevToolsAgentHostClientChannel* channel,
                     base::span<const uint8_t> message,
                     NotHandledCallback callback) override;
  scoped_refptr<content::DevToolsAgentHost> CreateNewTarget(
      const GURL& url) override;
  bool HasBundledFrontendResources() override;
  void ClientAttached(
      content::DevToolsAgentHostClientChannel* channel) override;
  void ClientDetached(
      content::DevToolsAgentHostClientChannel* channel) override;

  std::vector<content::BrowserContext*> GetBrowserContexts() override;
  content::BrowserContext* GetDefaultBrowserContext() override;
  content::BrowserContext* CreateBrowserContext() override;
  void DisposeBrowserContext(content::BrowserContext* context,
                             DisposeCallback callback) override;

 private:
  base::WeakPtr<HeadlessBrowserImpl> browser_;
  std::map<content::DevToolsAgentHostClientChannel*,
           std::unique_ptr<protocol::HeadlessDevToolsSession>>
      sessions_;
};

}  // namespace headless

#endif  // HEADLESS_LIB_BROWSER_HEADLESS_DEVTOOLS_MANAGER_DELEGATE_H_


text:
<?php
namespace Admin\Model;

class QuestionMst
{
	public $TEST_ID;
	public $NUMBER;
	public $CONTENTS;

	public function exchangeArray($data)
	{
		$this->TEST_ID = (isset($data['TEST_ID']))?$data['TEST_ID']:0;
		$this->NUMBER = (isset($data['NUMBER']))?$data['NUMBER']:'';
		$this->CONTENTS = (isset($data['CONTENTS']))?$data['CONTENTS']:'';

	}
}


text:
//
//  NetManager.m
//  BreachApp
//
//  Created by ah on 16/4/11.
//  Copyright © 2016年 ah. All rights reserved.
//

// 项目打包上线都不会打印日志,因此可放心。
#ifdef DEBUG
#define BreachLog(s, ... ) NSLog( @"[%@ in line %d] ===============>%@", [[NSString stringWithUTF8String:__FILE__] lastPathComponent], __LINE__, [NSString stringWithFormat:(s), ##__VA_ARGS__] )
#else
#define BreachLog(s, ... )
#endif

#import "NetManager.h"
#import "AFNetworking.h"
#import "AFHTTPSessionManager.h"
#import "AFNetworkActivityIndicatorManager.h"
#import "MJExtension.h"
#import "AFNetworkReachabilityManager.h"
#import "SystemSet.h"
#import "AhResult.h"
#import "AhRequest.h"
#import "AFNetworkReachabilityManager.h"
#import "SystemSet.h"
#import "NetTool.h"
#import "MBProgressHUD.h"

/**接受SessionTask的数组*/
static NSMutableArray *TaskArr;

@implementation NetManager
/**网络连接状态-->实时监控网络状态的变化*/
+ (void)NetStatusNotiStart{

    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
    // 检测网络连接的单例,网络变化时的回调方法
    [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {

        switch  (status)  {

            case   AFNetworkReachabilityStatusReachableViaWWAN:
                [[NSNotificationCenter defaultCenter]postNotificationName:NOTI_NET_CHANGE_WWAN object:nil];
            break;

            case   AFNetworkReachabilityStatusReachableViaWiFi:
                 [[NSNotificationCenter defaultCenter]postNotificationName:NOTI_NET_CHANGE_WiFi object:nil];
            break;

            case   AFNetworkReachabilityStatusNotReachable:
                [[NSNotificationCenter defaultCenter]postNotificationName:NOTI_NET_CHANGE_NotReachable object:nil];
                break;
            default:

                break;

        }
    }];
}

/**网络连接状态-->当前的网络状态*/
+ (NetType)CurrentNetstatus{

    [[AFNetworkReachabilityManager sharedManager] startMonitoring];

    AFNetworkReachabilityStatus status = [AFNetworkReachabilityManager sharedManager].networkReachabilityStatus;

    if (status==AFNetworkReachabilityStatusNotReachable) {
        return NetTypeDisAble;
    }else if (status==AFNetworkReachabilityStatusReachableViaWWAN){
        return NetTypeWWAN;
    }else if (status==AFNetworkReachabilityStatusReachableViaWiFi){
        return NetTypeWifi;
    }
    return NetTypeUnknown;
}
/**检查是否能联网*/
+ (BOOL)isReachable{

    return [AFNetworkReachabilityManager sharedManager].isReachable;
}

#pragma mark- get
/**GEt*/
+ (AhSessionTask*)GET:(NSString *)URLString
 parameters:(AhResult*)Request
             progress:(void (^)(int64_t bytesRead,
                                int64_t totalBytesRead))Progress
    success:(void (^)(id responseObject,NSString*status))success
    failure:(void (^)(NSError *error))failure{

    AFHTTPSessionManager *mgr = [self defautManager];

    URLString = [self absoluteUrlWithPath :URLString];

    NSDictionary *parameters = Request.mj_keyValues;
    if ([SystemSet defaultSet].DeBug) {  //  打开打印
        MJExtensionLog(@" 🈹🈹🈹  🈹🈹🈹  🈹🈹🈹  🈹🈹🈹  🈹🈹🈹 \n 请求模型:%@\n 参数为:\n %@ \n",[NSString stringWithUTF8String:class_getName(Request.class)],parameters);
    }
    MBProgressHUD *hub  = [NetTool showWaitWithText:nil ToVc:[SystemSet defaultSet].CurrentVc];

    AhSessionTask *task =  [mgr GET:URLString parameters:parameters progress:^(NSProgress * _Nonnull downloadProgress) {

        hub.progress =downloadProgress.completedUnitCount/downloadProgress.totalUnitCount;

        if (Progress) {

            Progress(downloadProgress.completedUnitCount,downloadProgress.totalUnitCount);
        }

    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {

       [self sucHandle:responseObject parameters:Request Url:URLString success:success hub:hub];

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
         [self failHandle:error parameters:Request Url:URLString failure:failure hub:hub];
    }];
    if (task) {
        [[self allTasks]addObject:task];
    }
    return task;
}

#pragma mark- post
+(AhSessionTask*)POST:(NSString *)URLString
 parameters:(AhResult*)Request
             progress:(void (^)(int64_t bytesRead,
                                 int64_t totalBytesRead))Progress
    success:(void (^)(id responseObject,NSString*status))success
    failure:(void (^)(NSError *error))failure {

    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    NSDictionary *parameters = Request.mj_keyValues;
    AFHTTPSessionManager *mgr = [self defautManager];
    URLString = [self absoluteUrlWithPath:URLString];
    if ([SystemSet defaultSet].DeBug) {  //  打开打印
        MJExtensionLog(@" 🈹🈹🈹  🈹🈹🈹  🈹🈹🈹  🈹🈹🈹  🈹🈹🈹 \n 请求模型:%@\n 请求地址:%@ 请求参数为:\n %@ \n",[NSString stringWithUTF8String:class_getName(Request.class)],URLString,parameters);
    }
     MBProgressHUD *hub  = [NetTool showWaitWithText:nil ToVc:[SystemSet defaultSet].CurrentVc];
    AhSessionTask *task =  [mgr POST:URLString parameters:parameters progress:^(NSProgress * _Nonnull uploadProgress ) {
         hub.progress =uploadProgress.completedUnitCount/uploadProgress.totalUnitCount;
        if (Progress) {
            Progress(uploadProgress.completedUnitCount,uploadProgress.totalUnitCount);
        }

    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {

        [self sucHandle:responseObject parameters:Request Url:URLString success:success hub:hub];

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {

        [self failHandle:error parameters:Request Url:URLString failure:failure hub:hub];
    }];
    if (task) {
        [[self allTasks]addObject:task];
    }
    return task;
}
#pragma mark- 上传图片
/**上传图片*/
+ (AhSessionTask*)POST:(NSString *)URLString
            parameters:(AhResult*)Request
                 image:(UIImage *)image
              progress:(void (^)(int64_t bytesRead,
                                 int64_t totalBytesRead))Progress
               success:(void (^)(id responseObject,NSString*status))success
               failure:(void (^)(NSError *error))failure{

    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    NSDictionary *parameters = Request.mj_keyValues;
    AFHTTPSessionManager *mgr = [self defautManager];
    URLString = [self absoluteUrlWithPath:URLString];
    if ([SystemSet defaultSet].DeBug) {  //  打开打印
        MJExtensionLog(@" 🈹🈹🈹  🈹🈹🈹  🈹🈹🈹  🈹🈹🈹  🈹🈹🈹 \n 请求模型:%@\n 请求地址:%@ 请求参数为:\n %@ \n",[NSString stringWithUTF8String:class_getName(Request.class)],URLString,parameters);
    }
    AhSessionTask *task =nil;
    MBProgressHUD *hub  = [NetTool showWaitWithText:@"图片上传中..." ToVc:[SystemSet defaultSet].CurrentVc];
    task= [mgr POST:URLString parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {

        NSData *file = UIImagePNGRepresentation(image);
        //           NSData *data =  UIImageJPEGRepresentation(image, 0.001);
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        formatter.dateFormat = @"yyyyMMddHHmmss";
        NSString *str = [formatter stringFromDate:[NSDate date]];
        NSString *name = [NSString stringWithFormat:@"%@.png", str];

        [formData appendPartWithFileData:file name:@"img" fileName:name mimeType:@"image/png"];

    } progress:^(NSProgress * _Nonnull uploadProgress) {

         hub.progress =uploadProgress.completedUnitCount/uploadProgress.totalUnitCount;
        if (Progress) {
            Progress(uploadProgress.completedUnitCount,uploadProgress.totalUnitCount);
        }

    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {

       [self sucHandle:responseObject parameters:Request Url:URLString success:success hub:hub];

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {

        [self failHandle:error parameters:Request Url:URLString failure:failure hub:hub];
    }];

    if (task) {
        [[self allTasks]addObject:task];
    }
    return task;

}

+ (NSString*)createCacheDirectory:(NSString*)path
{
    NSString *fullPath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:[NSString stringWithFormat:@"%@",path]];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if (![fileManager fileExistsAtPath:fullPath]) {
        [fileManager createDirectoryAtPath:fullPath withIntermediateDirectories:YES attributes:nil error:NULL];
    }
    return fullPath;
}
/**
 *  创建Document下的文件
 *
 *  @param path 路径描述
 *
 */
+ (NSString*)CreatDocumentDirectory:(NSString*)path fileName:(NSString*)fileName{

//    NSString *testPath3 = [testDirectory stringByAppendingPathComponent:@"test33.txt"];

    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *pathDocuments = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *createPath = [NSString stringWithFormat:@"%@/%@", pathDocuments,path];
    if (![[NSFileManager defaultManager] fileExistsAtPath:createPath]) {
        [fileManager createDirectoryAtPath:createPath withIntermediateDirectories:YES attributes:nil error:nil];
    }
    NSString *fullName = [createPath stringByAppendingPathComponent:fileName];
    return fullName;

}

#pragma mark- 下载文件

+ (AhSessionTask *)downloadWithUrl:(NSString *)URLString
                            saveToPath:(NSString *)SaveToPath
                          fileName:(NSString *)aFileName
                          progress:(void (^)(int64_t bytesRead,
                                             int64_t totalBytesRead))Progress
                           success:(void (^)(id responseObject))success
                           failure:(void (^)(NSError *error))failure{

    //检查本地文件是否已存在

    NSString *fullPath = [self CreatDocumentDirectory:SaveToPath fileName:aFileName];

    AFHTTPSessionManager *mgr = [self defautManager];

    NSURLRequest *downloadRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:URLString]];

        if ([SystemSet defaultSet].DeBug) {  //  打开打印
            MJExtensionLog(@" 🈹🈹🈹  🈹🈹🈹  🈹🈹🈹  🈹🈹🈹  🈹🈹🈹 \n 下载地址:%@\n 保存路径为:\n %@ \n",URLString,SaveToPath);
        }
    AhSessionTask *task = nil;

    task = [mgr downloadTaskWithRequest:downloadRequest progress:^(NSProgress * _Nonnull downloadProgress) {

            if (Progress) {
                Progress(downloadProgress.completedUnitCount, downloadProgress.totalUnitCount);
            }
        } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {

            return [NSURL URLWithString:fullPath];

        } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {

            [[self allTasks] removeObject:task];

            if (error == nil) {
                if (success) {

//                    success(filePath.absoluteString);
                }

                if ([SystemSet defaultSet].DeBug) {
                    NSLog(@"下载成功 路径 %@",fullPath);
                }
            } else {

                failure(error);

                if ([SystemSet defaultSet].DeBug) {
                    NSLog(@"下载失败 路径 %@, reason : %@",
                          fullPath,
                          [error description]);
                }
            }
        }];

        [task resume];  //  断点续传 校验

        //    [task suspend]; //  暂停下载

        if (task) {
            [[self allTasks]addObject:task];
        }
        return task;
}

#pragma mark- 默认管理者

+ (AFHTTPSessionManager *)defautManager{

    [AFNetworkActivityIndicatorManager sharedManager].enabled = YES;

    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];

    // 设置请求时间
    manager.requestSerializer.timeoutInterval =30;
    //  拿最原始的data数据
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];

    manager.requestSerializer.stringEncoding = NSUTF8StringEncoding;

    if ([SystemSet defaultSet].Header!=nil) {  //  使用者设置了公共请求头

        for (NSString *key in [SystemSet defaultSet].Header.allKeys) {
            if ([SystemSet defaultSet].Header[key]!=nil) {
                [manager.requestSerializer setValue:[SystemSet defaultSet].Header[key] forHTTPHeaderField:key];
            }
        }

    }

    //  设置可以接受的类型
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithArray:@[
                                                                              @"application/json",
                                                                              @"text/html",
                                                                              @"text/xml",
                                                                              @"text/json",
                                                                              @"text/plain",
                                                                              @"text/javascript",
                                                                              @"text/xml",
                                                                              @"image/*",
                                                                              @"image/png",
                                                                              ]];

    manager.operationQueue.maxConcurrentOperationCount = [SystemSet defaultSet].maxConcurrentOperationCount<9?[SystemSet defaultSet].maxConcurrentOperationCount:4;

    return manager;
}

#pragma mark- 合成URl
/**合成Url*/
+ (NSString*)MakeFullUrl:(NSString*)url{

    return [NSString stringWithFormat:@"%@%@%@",[SystemSet defaultSet].HOST,url,[SystemSet defaultSet].SUFFIX==nil?@"":[SystemSet defaultSet].SUFFIX];
}

#pragma mark- 由请求模型得到接受模型
/**由请求模型得到接受类模型的字符串*/
+ (NSString *)resultFromRequest:(AhResult*)request{

    NSString *requestClassName =  [NSString stringWithUTF8String:class_getName(request.class)];
    NSString *resultClassName = [NSString stringWithFormat:@"%@%@",requestClassName,[SystemSet defaultSet].Result_Request];
    return resultClassName;
}

#pragma mark- 请求url含有中文的处理

/**url含有中文时的处理*/
+ (NSString *)AhURLEncode:(NSString *)url {
    NSString *newString =
    CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
                                                              (CFStringRef)url,
                                                              NULL,
                                                              CFSTR(":/?#[]@!$ &'()*+,;=\"<>%{}|\\^~`"), CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding)));
    if (newString) {
        return newString;
    }

    return url;
}
#pragma mark- 获取所有请求SessionTask的数组单例
+ (NSMutableArray *)allTasks {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        if (TaskArr == nil) {
            TaskArr = [[NSMutableArray alloc] init];
        }
    });

    return TaskArr;
}
#pragma mark- 完整路径描述
+ (NSString *)absoluteUrlWithPath:(NSString *)path {
    if (path == nil || path.length == 0) {
        MJExtensionLog(@"传入的url为nil或者空");
        return @"";
    }
    NSString *absoluteUrl = path;

    if (![path hasPrefix:@"http://"] && ![path hasPrefix:@"https://"]) {  //  猜测path是一个片段
        absoluteUrl = [self MakeFullUrl:path];
    }
    return absoluteUrl;
}
#pragma mark- 取消全部网络请求

+ (void)cancelAllRequest {
    @synchronized(self) {
        [[self allTasks] enumerateObjectsUsingBlock:^(AhSessionTask * _Nonnull task, NSUInteger idx, BOOL * _Nonnull stop) {
            if ([task isKindOfClass:[AhSessionTask class]]) {
                [task cancel];
            }
        }];

        [[self allTasks] removeAllObjects];
    };
}

#pragma mark- 取消特定Url的网络请求

+ (void)cancelRequestWithURL:(NSString *)url {
    if (url == nil) {
        return;
    }

    @synchronized(self) {
        [[self allTasks] enumerateObjectsUsingBlock:^(AhSessionTask * _Nonnull task, NSUInteger idx, BOOL * _Nonnull stop) {
            if ([task isKindOfClass:[AhSessionTask class]]
                && [task.currentRequest.URL.absoluteString hasSuffix:url]) {
                [task cancel];
                [[self allTasks] removeObject:task];
                return;
            }
        }];
    };
}

#pragma mark- 将返回状态全部在success中暴露的 使用于 tableVIew加载数据时,返回status不是成功时也需要结束刷新状态的场景

+ (NSArray*)StatusResult{
    NSMutableArray *NewStatusResult = @[].mutableCopy;
    for (NSString *UrlString in [SystemSet defaultSet].StatusResult) {

        NSString *NewUrl = [self absoluteUrlWithPath :UrlString];
        [NewStatusResult addObject:NewUrl];
    }

    return NewStatusResult;
}

#pragma mark - 网络成功后的处理
/**网络请求成功后的处理*/
+ (void)sucHandle:(id)responseObject parameters:(AhResult*)Request Url:(NSString *)URLString  success:(void (^)(id responseObject,NSString*status))success hub:(MBProgressHUD*)hub
{

    [hub hideAnimated:YES];

    if (success) {

        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObject options:0 error:nil];
        NSString *resultClassName = [self resultFromRequest:Request];
        Class aclass = NSClassFromString(resultClassName);
        AhResult *result = [aclass mj_objectWithKeyValues:dict];
        if (result==nil) {

            result = [AhResult mj_objectWithKeyValues:dict];
            resultClassName = @"AhResult";
        }

        if ([SystemSet defaultSet].DeBug) {  //  打开打印
            MJExtensionLog(@" 🈹🈹🈹  🈹🈹🈹  🈹🈹🈹  🈹🈹🈹  🈹🈹🈹 \n 接受模型:%@\n状态码:%@\n状态msg:%@\n 接受数据为:\n %@ \n",resultClassName,result.status,result.msg,dict);
        }
        if ([SystemSet defaultSet].SucStatus.length>0) {  // 含有自定义的成功状态码

            if ([result.status isEqualToString:[SystemSet defaultSet].SucStatus]) {

                success(result,[SystemSet defaultSet].SucStatus);

            }else{

                // 抛错
                MJExtensionLog(@"否❌否❌否❌否❌否❌否❌否❌ 抛出异常:%@\n status:%@\n 接受数据为:\n msg:%@ \n ",resultClassName,result.status,result.msg);
                if (result.msg) {

                    [NetTool showmsg:result.msg Tovc:[SystemSet defaultSet].CurrentVc];
                }

                if ([SystemSet defaultSet].LoginOutStatus.length>0 && [result.status isEqualToString:[SystemSet defaultSet].LoginOutStatus]) {

                    [[NSNotificationCenter defaultCenter]postNotificationName:NOTI_LOGIN_OUT object:nil];
                }

                if ([SystemSet defaultSet].LoginSiginleStatus.length>0 && [result.status isEqualToString:[SystemSet defaultSet].LoginSiginleStatus]) {

                    [[NSNotificationCenter defaultCenter]postNotificationName:NOTI_LOGIN_SINGLE object:nil];
                }

                if ([[self StatusResult]containsObject:URLString]) {  // 某些特定的接口异常要暴露出去,

                    success(result,result.status);
                }
            }

        }else{  // 未设置SucStatus 则 所有的状态都会通过句柄传递出去, 需要在业务界面自己判断  成功则处理业务逻辑,不成功 抛错
            success(result,result.status);
        }
    }

    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}
#pragma mark - 网络请求失败后的处理
/**网络请求失败后的处理*/
+ (void)failHandle:(id)error parameters:(AhResult*)Request Url:(NSString *)URLString  failure:(void (^)(NSError *error))failure hub:(MBProgressHUD*)hub{

    [hub hideAnimated:YES];

    if ([SystemSet defaultSet].DeBug) {  //  打开打印
        MJExtensionLog(@"否❌否❌否❌否❌否❌否❌否❌否❌否❌ \n 数据请求失败 \n: 请求模型:%@\n 请求路径:%@\n error: %@ \n\n\n",[NSString stringWithUTF8String:class_getName(Request.class)],URLString,error);
    }
    if (failure) {

        failure(error);
    }
    [error localizedDescription];
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}

@end


text:
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
/**
 * \class document::TestDocMan
 * \ingroup base
 *
 * \brief Utility for unit tests that need document manager and documents.
 *
 * This test class sets up a document manager, and defines a few document types
 * for use in testing.
 *
 * The following document types are defined by this manager
 * (add more when needed):
 *
 * testtype1
 *     headerval int (header variable)
 *     content string (body variable)
 */

#pragma once

#include "testdocrepo.h"
#include <vespa/document/fieldvalue/document.h>
#include <vespa/document/datatype/documenttype.h>

namespace document {

class Document;

class TestDocMan {
    static std::vector<char> _buffer;
    TestDocRepo _test_repo;
    std::shared_ptr<const DocumentTypeRepo> _repo;
    const DocumenttypesConfig *_typeCfg;

public:
    TestDocMan();
    ~TestDocMan();

    void setTypeRepo(const std::shared_ptr<const DocumentTypeRepo> &repo);

    const DocumentTypeRepo& getTypeRepo() const { return *_repo; }
    std::shared_ptr<const DocumentTypeRepo> getTypeRepoSP() const { return _repo; }
    const DocumenttypesConfig *getTypeConfig() const { return _typeCfg; }

    /** Create test document. */
    std::unique_ptr<Document> createDocument(
            const std::string& content = "This is the contents of "
                    "the test document.\nIt ain't much.\n",
            const std::string& uri = "id:test:testdoctype1::test",
            const std::string& type = "testdoctype1") const;

    /** Create random document from given seed. */
    std::unique_ptr<Document> createRandomDocument(
            int seed = 0, int maxContentSize = 0x80) const;
    /** Create random document from given seed belonging to given location */
    std::unique_ptr<Document> createRandomDocumentAtLocation(
            int location, int seed = 0, int maxContentSize = 0x80) const;
    std::unique_ptr<Document> createRandomDocumentAtLocation(
            int location, int seed, int minContentSize, int maxContentSize) const;
    /** Create random document of given type from given seed. */
    std::unique_ptr<Document> createRandomDocument(
            const std::string& type, int seed = 0,
            int maxContentSize = 0x80) const;
    static std::string generateRandomContent(uint32_t size);
};

} // document


text:
'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _calc = require('./calc');

var _calc2 = _interopRequireDefault(_calc);

var _cursor = require('./cursor');

var _cursor2 = _interopRequireDefault(_cursor);

var _crossFade = require('./crossFade');

var _crossFade2 = _interopRequireDefault(_crossFade);

var _filter = require('./filter');

var _filter2 = _interopRequireDefault(_filter);

var _flex = require('./flex');

var _flex2 = _interopRequireDefault(_flex);

var _flexboxIE = require('./flexboxIE');

var _flexboxIE2 = _interopRequireDefault(_flexboxIE);

var _flexboxOld = require('./flexboxOld');

var _flexboxOld2 = _interopRequireDefault(_flexboxOld);

var _gradient = require('./gradient');

var _gradient2 = _interopRequireDefault(_gradient);

var _imageSet = require('./imageSet');

var _imageSet2 = _interopRequireDefault(_imageSet);

var _position = require('./position');

var _position2 = _interopRequireDefault(_position);

var _sizing = require('./sizing');

var _sizing2 = _interopRequireDefault(_sizing);

var _transition = require('./transition');

var _transition2 = _interopRequireDefault(_transition);

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

exports.default = [_position2.default, _calc2.default, _cursor2.default, _imageSet2.default, _crossFade2.default, _filter2.default, _sizing2.default, _gradient2.default, _transition2.default, _flexboxIE2.default, _flexboxOld2.default, _flex2.default];
module.exports = exports['default'];


text:
namespace NCheck.Test.Examples
{
    public class Wrapper<T> : IWrapper<T>
    {
        public T Content { get; set; }
    }
}


text:
describe('Controller: app.mainViewCtrl', function () {

    // load the controller's module
    beforeEach(module('app'));

    var ctrl,
        scope;

    // Initialize the controller and a mock scope
    beforeEach(inject(function ($controller, $rootScope) {
        scope = $rootScope.$new();
        ctrl = $controller('mainViewCtrl', {
            $scope: scope
        });
    }));

    it('should be defined', function () {
        expect(ctrl).toBeDefined();
    });
});


text:
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <script src="init.js"></script>
    <script src="semantics.js"></script>
    <script src="semanticsCube.js"></script>
    <script src="paintCanvas.js"></script>
    <script src="virtualMachine.js"></script>
    <script src="blockly/blockly_compressed.js"></script>
    <script src="blockly/blocks_compressed.js"></script>
    <script src="blockly/chabuscript_compressed.js"></script>
    <script src="blockly/msg/js/en.js"></script>
    <style>
      html, body {
        background-color: #fff;
        margin: 0;
        padding: 0;
        overflow: hidden;
        height: 100%;
      }
      .blocklySvg {
        height: 100%;
        width: 100%;
      }
    </style>
    <script>
      function init() {
        var workspace = Blockly.inject(document.body, {toolbox: document.getElementById('toolbox')});
        Blockly.Xml.domToWorkspace(workspace, document.getElementById('toolbox'));
        // Let the top-level application know that Blockly is ready.
        window.parent.blockly_loaded(Blockly, workspace);
      }

      function run_code(){
        startRun();
        Blockly.Chabuscript.INFINITE_LOOP_TRAP = null;
        code = window.Blockly;
        code = window.Blockly.Chabuscript.workspaceToCode(workspace);
        console.log(code);
      }
    </script>
  </head>
  <body onload="init()">
    <xml id="toolbox" style="display: none">
      <category name="Functions">
        <block type="main"></block>
        <block type="func_block"></block>
        <block type="param_block"></block>
        <block type="return_stmt"></block>
        <block type="invokefuncreturn"></block>
        <block type="invokevoidfunc"></block>
        <block type="func_param"></block>
      </category>
      <category name="Variables">
        <block type="var"></block>
        <block type="variables_exist_var"></block>
      </category>
      <category name="Math">
        <block type="assign"></block>
        <block type="term"></block>
        <block type="exp"></block>
        <block type="paren"></block>
        <block type="random"></block>
      </category>
      <category name="Logic">
        <block type="logic_if"></block>
        <block type="logic_if_else"></block>
        <block type="logic_if_elsif_else"></block>
        <block type="boolean_compare_expression"></block>
        <block type="boolean_expression"></block>
      </category>
      <category name="Lists">
        <block type="list_values"></block>
        <block type="list_item"></block>
        <block type="add_item"></block>
        <block type="remove_item"></block>
      </category>
      <category name="Text">
        <block type="print"></block>
        <block type="print_ctestring"></block>
      </category>
      <category name="Drawing">
        <block type="background"></block>
        <block type="draw"></block>
        <block type="line"></block>
        <block type="point"></block>
        <block type="circle"></block>
        <block type="rectangle"></block>
        <block type="polygon"></block>
        <block type="color"></block>
      </category>
    </xml>
    <button id="button_run" onclick="run_code()">
      Run Code
    </button>
  </body>
</html>


text:
(function () {

    var inputTime = angular.module('inputTime', [
    ]);

    inputTime.directive('inputTime', function () {
        return {
            restrict: 'E',
            replace: true,
            scope: {
                ngModel: '=?',
                placeholder: '@',
                editable: '=?'
            },
            templateUrl: 'input-time/input-time.html',
            controller: 'InputTimeCtrl'
        };
    });

    inputTime.controller('InputTimeCtrl', ['$scope', function ($scope) {
        }]);

}());


text:
testname
=====

Documentation: https://godoc.org/github.com/facebookgo/testname