text:
package org.apache.kylin.job;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;

import com.google.common.collect.Maps;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.kylin.common.KylinConfig;
import org.apache.kylin.common.persistence.ResourceStore;
import org.apache.kylin.common.persistence.ResourceTool;
import org.apache.kylin.common.util.LocalFileMetadataTestCase;
import org.apache.kylin.cube.CubeDescManager;
import org.apache.kylin.cube.CubeInstance;
import org.apache.kylin.cube.CubeManager;
import org.apache.kylin.job.streaming.StreamDataLoader;
import org.apache.kylin.job.streaming.StreamingTableDataGenerator;
import org.apache.kylin.metadata.TableMetadataManager;
import org.apache.kylin.metadata.model.DataModelDesc;
import org.apache.kylin.metadata.model.DataModelManager;
import org.apache.kylin.metadata.model.TableRef;
import org.apache.kylin.metadata.model.TblColRef;
import org.apache.kylin.source.ISampleDataDeployer;
import org.apache.kylin.source.SourceManager;
import org.apache.kylin.source.datagen.ModelDataGenerator;
import org.apache.kylin.source.kafka.TimedJsonStreamParser;
import org.apache.maven.model.Model;
import org.apache.maven.model.io.xpp3.MavenXpp3Reader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.collect.Lists;
import com.google.common.io.Files;

public class DeployUtil {
    private static final Logger logger = LoggerFactory.getLogger(DeployUtil.class);

    public static void initCliWorkDir() throws IOException {
        execCliCommand("rm -rf " + getHadoopCliWorkingDir());
        execCliCommand("mkdir -p " + config().getKylinJobLogDir());
    }

    public static void deployMetadata(String localMetaData) throws IOException {
        // install metadata to hbase
        new ResourceTool().reset(config());
        new ResourceTool().copy(KylinConfig.createInstanceFromUri(localMetaData), config());

        // update cube desc signature.
        for (CubeInstance cube : CubeManager.getInstance(config()).listAllCubes()) {
            CubeDescManager.getInstance(config()).updateCubeDesc(cube.getDescriptor());//enforce signature updating
        }
    }

    public static void deployMetadata() throws IOException {
        deployMetadata(LocalFileMetadataTestCase.LOCALMETA_TEST_DATA);
    }

    public static void overrideJobJarLocations() {
        File jobJar = getJobJarFile();
        File coprocessorJar = getCoprocessorJarFile();

        config().overrideMRJobJarPath(jobJar.getAbsolutePath());
        config().overrideCoprocessorLocalJar(coprocessorJar.getAbsolutePath());
    }

    private static String getPomVersion() {
        try {
            MavenXpp3Reader pomReader = new MavenXpp3Reader();
            Model model = pomReader
                    .read(new InputStreamReader(new FileInputStream("../pom.xml"), StandardCharsets.UTF_8));
            return model.getVersion();
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    }

    private static File getJobJarFile() {
        return new File("../assembly/target", "kylin-assembly-" + getPomVersion() + "-job.jar");
    }

    private static File getCoprocessorJarFile() {
        return new File("../storage-hbase/target", "kylin-storage-hbase-" + getPomVersion() + "-coprocessor.jar");
    }

    private static void execCliCommand(String cmd) throws IOException {
        config().getCliCommandExecutor().execute(cmd);
    }

    private static String getHadoopCliWorkingDir() {
        return config().getCliWorkingDir();
    }

    private static KylinConfig config() {
        return KylinConfig.getInstanceFromEnv();
    }

    // ============================================================================

    public static void prepareTestDataForNormalCubes(String modelName) throws Exception {

        boolean buildCubeUsingProvidedData = Boolean.parseBoolean(System.getProperty("buildCubeUsingProvidedData"));
        if (!buildCubeUsingProvidedData) {
            System.out.println("build cube with random dataset");

            // data is generated according to cube descriptor and saved in resource store
            DataModelManager mgr = DataModelManager.getInstance(KylinConfig.getInstanceFromEnv());
            ModelDataGenerator gen = new ModelDataGenerator(mgr.getDataModelDesc(modelName), 10000);
            gen.generate();
        } else {
            System.out.println("build normal cubes with provided dataset");
        }

        // the special VIEW_SELLER_TYPE_DIM is a wrapper of TABLE_SELLER_TYPE_DIM_TABLE
        final String databaseName = "EDW";
        final Map<String, String> tableViewMap = Maps.newHashMap();
        tableViewMap.put("EDW.TEST_SELLER_TYPE_DIM_TABLE", "EDW.TEST_SELLER_TYPE_DIM");
        deployTablesInModelWithWrapperViews(modelName, databaseName, tableViewMap);
    }

    public static void prepareTestDataForStreamingCube(long startTime, long endTime, int numberOfRecords,
            String cubeName, StreamDataLoader streamDataLoader) throws IOException {
        CubeInstance cubeInstance = CubeManager.getInstance(KylinConfig.getInstanceFromEnv()).getCube(cubeName);
        List<String> data = StreamingTableDataGenerator.generate(numberOfRecords, startTime, endTime,
                cubeInstance.getRootFactTable(), cubeInstance.getProject());
        //load into kafka
        streamDataLoader.loadIntoKafka(data);
        logger.info("Write {} messages into {}", data.size(), streamDataLoader.toString());

        //csv data for H2 use
        TableRef factTable = cubeInstance.getModel().getRootFactTable();
        List<TblColRef> tableColumns = Lists.newArrayList(factTable.getColumns());
        TimedJsonStreamParser timedJsonStreamParser = new TimedJsonStreamParser(tableColumns, null);
        StringBuilder sb = new StringBuilder();
        for (String json : data) {
            List<String> rowColumns = timedJsonStreamParser
                    .parse(ByteBuffer.wrap(json.getBytes(StandardCharsets.UTF_8))).get(0).getData();
            sb.append(StringUtils.join(rowColumns, ","));
            sb.append(System.getProperty("line.separator"));
        }
        appendFactTableData(sb.toString(), cubeInstance.getRootFactTable());
    }

    public static void appendFactTableData(String factTableContent, String factTableName) throws IOException {
        // Write to resource store
        ResourceStore store = ResourceStore.getStore(config());

        InputStream in = new ByteArrayInputStream(factTableContent.getBytes("UTF-8"));
        String factTablePath = "/data/" + factTableName + ".csv";

        File tmpFile = File.createTempFile(factTableName, "csv");
        FileOutputStream out = new FileOutputStream(tmpFile);

        InputStream tempIn = null;
        try {
            if (store.exists(factTablePath)) {
                InputStream oldContent = store.getResource(factTablePath).content();
                IOUtils.copy(oldContent, out);
            }
            IOUtils.copy(in, out);
            IOUtils.closeQuietly(in);
            IOUtils.closeQuietly(out);

            store.deleteResource(factTablePath);
            tempIn = new FileInputStream(tmpFile);
            store.putResource(factTablePath, tempIn, System.currentTimeMillis());
        } finally {
            IOUtils.closeQuietly(out);
            IOUtils.closeQuietly(in);
            IOUtils.closeQuietly(tempIn);
        }

    }

    public static Set<String> buildExclusiveSet(String[] exclusiveTables) {
        Set<String> exclusiveSet = new HashSet<String>();
        if (exclusiveTables != null) {
            for (String table : exclusiveTables) {
                exclusiveSet.add(table);
            }
        }
        return exclusiveSet;
    }

    public static void deployTablesInModelWithWrapperViews(String modelName, String extraDatabase, Map<String, String> extraTableViews) throws Exception {
        deployTablesInModel(modelName, extraDatabase, extraTableViews, null);
    }

    public static void deployTablesInModelWithExclusiveTables(String modelName, String[] exclusiveTables) throws Exception {
        deployTablesInModel(modelName, null,  null, exclusiveTables);
    }

    public static void deployTablesInModel(String modelName) throws Exception {
        deployTablesInModel(modelName, null, null, null);
    }

    public static void deployTablesInModel(String modelName, String extraDatabase, Map<String, String>  extraTableViews, String[] exclusiveTables) throws Exception {
        TableMetadataManager metaMgr = TableMetadataManager.getInstance(config());
        DataModelManager modelMgr = DataModelManager.getInstance(config());
        DataModelDesc model = modelMgr.getDataModelDesc(modelName);

        Set<TableRef> tables = model.getAllTables();
        Set<String> TABLE_NAMES = new HashSet<String>();
        Set<String> exclusiveSet = buildExclusiveSet(exclusiveTables);

        for (TableRef tr : tables) {
            if (!tr.getTableDesc().isView()) {
                String tableName = tr.getTableName();
                String schema = tr.getTableDesc().getDatabase();
                String identity = String.format(Locale.ROOT, "%s.%s", schema, tableName);
                if (exclusiveSet.contains(identity)) {
                    continue;
                }
                TABLE_NAMES.add(identity);
            }
        }

        if (extraTableViews != null && !extraTableViews.isEmpty()) {
            TABLE_NAMES.addAll(extraTableViews.keySet()); // the wrapper view need this table
        }

        // scp data files, use the data from hbase, instead of local files
        File tempDir = Files.createTempDir();
        String tempDirAbsPath = tempDir.getAbsolutePath();
        for (String tablename : TABLE_NAMES) {
            tablename = tablename.toUpperCase(Locale.ROOT);

            File localBufferFile = new File(tempDirAbsPath + "/" + tablename + ".csv");
            localBufferFile.createNewFile();

            logger.info(String.format(Locale.ROOT, "get resource from hbase:/data/%s.csv", tablename));
            InputStream hbaseDataStream = metaMgr.getStore().getResource("/data/" + tablename + ".csv").content();
            FileOutputStream localFileStream = new FileOutputStream(localBufferFile);
            IOUtils.copy(hbaseDataStream, localFileStream);

            hbaseDataStream.close();
            localFileStream.close();

            localBufferFile.deleteOnExit();
        }
        tempDir.deleteOnExit();

        ISampleDataDeployer sampleDataDeployer = SourceManager.getSource(model.getRootFactTable().getTableDesc())
                .getSampleDataDeployer();

        // create hive database
        if (StringUtils.isNotEmpty(extraDatabase)) {
            sampleDataDeployer.createSampleDatabase(extraDatabase);
        }

        // create hive tables
        for (String tablename : TABLE_NAMES) {
            logger.info(String.format(Locale.ROOT, "get table desc %s", tablename));
            sampleDataDeployer.createSampleTable(metaMgr.getTableDesc(tablename, model.getProject()));
        }

        // load data to hive tables
        // LOAD DATA LOCAL INPATH 'filepath' [OVERWRITE] INTO TABLE tablename
        for (String tablename : TABLE_NAMES) {
            logger.info(String.format(Locale.ROOT, "load data into %s", tablename));
            sampleDataDeployer.loadSampleData(tablename, tempDirAbsPath);
        }

        // create the view automatically here
        if (extraTableViews != null && !extraTableViews.isEmpty()) {
            for (Map.Entry<String, String> tableView : extraTableViews.entrySet()) {
                sampleDataDeployer.createWrapperView(tableView.getKey(), tableView.getValue());
            }
        }
    }
}


text:
StateStack = {}
StateStack.__index = StateStack
function StateStack:Create()
    local this =
    {
        mStates = {}
    }

    setmetatable(this, self)
    return this
end

function StateStack:IsEmpty()
    return not next(self.mStates)
end

function StateStack:Push(state)
    table.insert(self.mStates, state)
    state:Enter()
end

function StateStack:Pop()

    local top = self.mStates[#self.mStates]
    table.remove(self.mStates)
    top:Exit()
    return top
end

function StateStack:Top()
    return self.mStates[#self.mStates]
end

function StateStack:Step()
    local top = self.mStates[#self.mStates]

    if not top then
        return
    end

    top:Step()
end

function StateStack:Render(renderer)
    for _, v in ipairs(self.mStates) do
        v:Render(renderer)
    end
end

redpajama_set_name: RedPajamaGithub


text:
require 'noir'
require 'spec_helper'

describe 'Noir::Options' do

  it 'is Class' do
    expect(Noir::Options.class).to eq(Class)
  end

  describe 'Noir::Options.exist?' do
    after {Noir::Options.class_variable_set :@@options, {}}

    it 'is return false if argument is nil.' do
      expect(Noir::Options.exist? nil).to eq(false)
    end

    it '(Help) is return false if ARGV not include "-h"' do
      expect(Noir::Options.exist? Noir::Options::Help).to eq(false)
    end

    it '(Help) is return true if ARGV include "-h"' do
      stub_const('ARGV', ['-h'])
      Noir::Options.parse_options_from_argv!
      expect(Noir::Options.exist? Noir::Options::Help).to eq(true)
    end

    it '(Help) is return false if ARGV not include "--help"' do
      expect(Noir::Options.exist? Noir::Options::Help).to eq(false)
    end

    it '(Help) is return true if ARGV include "--help"' do
      stub_const('ARGV', ['--help'])
      Noir::Options.parse_options_from_argv!
      expect(Noir::Options.exist? Noir::Options::Help).to eq(true)
    end

    it 'exit with output version if ARGV include "-v"' do
      stub_const('ARGV', ['-v'])
      expect {
        expect{Noir::Options.parse_options_from_argv!}.to raise_error(SystemExit)
      }.to output('noir ' + Noir::VERSION + "\n").to_stdout
    end

    it 'exit with output version if ARGV include "--version"' do
      stub_const('ARGV', ['--version'])
      expect {
        expect{Noir::Options.parse_options_from_argv!}.to raise_error(SystemExit)
      }.to output('noir ' + Noir::VERSION + "\n").to_stdout
    end
  end

end


text:
set -euo pipefail

APT_ARGS=(
"-qq"
"-y"
)

# Installing nvidia docker to use deepvariant_gpu Docker image.
# (1) Install nvidia driver:
# https://linuxhint.com/install-cuda-ubuntu/
sudo apt-get "${APT_ARGS[@]}" update
sudo apt-get "${APT_ARGS[@]}" install \
  build-essential \
  curl \
  "linux-headers-$(uname -r)" \
  nvidia-cuda-toolkit

# See https://www.tensorflow.org/install/source#gpu for versions required.
if ! dpkg-query -W cuda-11-3; then
  echo "Installing CUDA..."
  UBUNTU_VERSION="2004"
  curl -O https://developer.download.nvidia.com/compute/cuda/repos/ubuntu2004/x86_64/cuda-ubuntu2004.pin
  sudo mv cuda-ubuntu2004.pin /etc/apt/preferences.d/cuda-repository-pin-600
  # From https://forums.developer.nvidia.com/t/notice-cuda-linux-repository-key-rotation/212772
  sudo -H apt-key adv --fetch-keys "http://developer.download.nvidia.com/compute/cuda/repos/ubuntu${UBUNTU_VERSION}/x86_64/3bf863cc.pub"
  sudo add-apt-repository -y "deb https://developer.download.nvidia.com/compute/cuda/repos/ubuntu2004/x86_64/ /"
  sudo -H apt-get update "${APT_ARGS[@]}" > /dev/null
  sudo -H apt-get full-upgrade "${APT_ARGS[@]}" > /dev/null
  sudo -H apt-get install "${APT_ARGS[@]}" cuda-11-3
fi

echo "Checking for CUDNN..."
if [[ ! -e /usr/local/cuda-11/include/cudnn.h ]]; then
  echo "Installing CUDNN..."
  CUDNN_TAR_FILE="cudnn-11.3-linux-x64-v8.2.0.53.tgz"
  wget -q https://developer.download.nvidia.com/compute/redist/cudnn/v8.2.0/${CUDNN_TAR_FILE}
  tar -xzvf ${CUDNN_TAR_FILE}
  sudo cp -P cuda/include/cudnn.h /usr/local/cuda-11/include
  sudo cp -P cuda/lib64/libcudnn* /usr/local/cuda-11/lib64/
  sudo cp -P cuda/lib64/libcudnn* /usr/local/cuda-11/lib64/
  sudo chmod a+r /usr/local/cuda-11/lib64/libcudnn*
  sudo ldconfig
fi

# (2) Install Docker CE:
# https://docs.docker.com/engine/install/ubuntu/
curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -
sudo apt-key fingerprint 0EBFCD88
sudo add-apt-repository \
 "deb [arch=amd64] https://download.docker.com/linux/ubuntu \
 $(lsb_release -cs) \
 stable"
sudo apt-get "${APT_ARGS[@]}" update
sudo apt-get "${APT_ARGS[@]}" install docker-ce docker-ce-cli containerd.io

# (3) Install nvidia docker:
# https://docs.nvidia.com/datacenter/cloud-native/container-toolkit/install-guide.html#installing-on-ubuntu-and-debian
# Add the package repositories
distribution=$(. /etc/os-release;echo "$ID$VERSION_ID")
curl -s -L https://nvidia.github.io/nvidia-docker/gpgkey | sudo apt-key add -
curl -s -L "https://nvidia.github.io/nvidia-docker/$distribution/nvidia-docker.list" | sudo tee /etc/apt/sources.list.d/nvidia-docker.list

sudo apt-get update && sudo apt-get install "${APT_ARGS[@]}" nvidia-docker2
sudo systemctl restart docker

#### Test nvidia-smi with the latest official CUDA image
sudo docker run --gpus 1 nvidia/cuda:11.3.0-base-ubuntu20.04 nvidia-smi


text:
<?xml version="1.0" encoding="utf-8"?>
<selector
  xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_checked="true"  android:state_pressed="true" android:drawable="@color/home_tab_hot_app_p" />
    <item android:state_checked="false"  android:state_pressed="false"  android:drawable="@color/home_tab_hot_app_d" />
</selector>


text:
'use strict';

var Q = require('q');
var AbstractDevice = require('./AbstractDevice');

/**
 *
 */

var Contact = function (options, devices) {
	AbstractDevice.prototype.constructor.bind(this)(options, devices);
};

/**
 *
 */

Contact.prototype = Object.create(AbstractDevice.prototype);

/**
 *
 */

Contact.prototype.parseDeviceEvent = function(event) {
	event = this.parseState(event);
	return event;
};

/**
 *
 */

Contact.prototype.parseDeviceResponse = function(event) {
	event = this.parseState(event);
	return event;
};

/**
 *
 */

Contact.prototype.parseState = function(event) {
	var states = {'C8': 'open', '00': 'close'};
	var _raw = event.payload.substring(22, 24);
	event.state = states[_raw];
	return event;
};

module.exports = Contact;


text:
package gw.plugin.ij.lang.psi;

import com.intellij.codeInsight.daemon.ImplicitUsageProvider;
import com.intellij.psi.PsiElement;
import gw.plugin.ij.lang.parser.GosuCompositeElement;
import org.jetbrains.annotations.NotNull;

/**
 */
public class GosuImplicitUsageProvider implements ImplicitUsageProvider {
  @Override
  public boolean isImplicitUsage(@NotNull PsiElement element) {
    return element.getNode() instanceof GosuCompositeElement;
  }

  @Override
  public boolean isImplicitRead(@NotNull PsiElement element) {
    return element.getNode() instanceof GosuCompositeElement;
  }

  @Override
  public boolean isImplicitWrite(@NotNull PsiElement element) {
    return element.getNode() instanceof GosuCompositeElement;
  }
}


text:
import asyncio
from aiohttp import ContentTypeError
from tenacity import (retry, retry_if_exception_type, stop_after_attempt,
                      wait_chain, wait_fixed)
import copy
from .exceptions import (APIBadRequest, APIConnectionError, APIForbidden,
                         APIInactiveError, APIInvalidKey, APINotFound,
                         APIRateLimited)
import json

class ApiMixin:

    async def call_multiple(self,
                            endpoints,
                            user=None,
                            scopes=None,
                            key=None,
                            **kwargs):
        if key is None and user:
            doc = await self.fetch_key(user, scopes)
            key = doc["key"]
        tasks = []
        for e in endpoints:
            tasks.append(self.call_api(e, key=key, **kwargs))
        return await asyncio.gather(*tasks)

    async def cache_result(self, endpoint, result, used_key, user):
        if endpoint == "account" and user:
            doc = await self.bot.database.get(user, self)
            key = doc["key"]
            keys = doc["keys"]
            if key["account_name"] != result["name"]:
                if used_key == key["key"]:
                    old_name = copy.copy(key["account_name"])
                    new_name = result["name"]
                    key["account_name"] = new_name
                    for alt_key in keys:
                        if alt_key["account_name"] == old_name:
                            alt_key["account_name"] = new_name
                    await self.bot.database.set(user, {
                        "key": key,
                        "keys": keys
                    }, self)
                    await user.send("Your account name seems to have "
                                    "changed! I went ahead and updated it, "
                                    "from `{}` to `{}`.".format(
                                        old_name, new_name))
                    await self.bot.database.set(
                        user, {"name_changes": [old_name, new_name]},
                        self,
                        operator="push")

    @retry(retry=retry_if_exception_type(APIBadRequest),
           reraise=True,
           stop=stop_after_attempt(4),
           wait=wait_chain(wait_fixed(2), wait_fixed(4), wait_fixed(8)))
    async def call_api(self,
                       endpoint,
                       user=None,
                       scopes=None,
                       key=None,
                       schema_version=None,
                       schema_string=None):
        headers = {
            'User-Agent': "GW2Bot - a Discord bot",
            'Accept': 'application/json'
        }
        if key:
            headers.update({"Authorization": "Bearer " + key})
        if user:
            doc = await self.fetch_key(user, scopes)
            key = doc["key"]
            headers.update({"Authorization": "Bearer " + key})
        if schema_version:
            schema = schema_version.replace(microsecond=0).isoformat() + "Z"
            headers.update({"X-Schema-Version": schema})
        if schema_string:
            headers.update({"X-Schema-Version": schema_string})
        apiserv = 'https://api.guildwars2.com/v2/'
        url = apiserv + endpoint
        async with self.session.get(url, headers=headers) as r:
            if r.status != 200 and r.status != 206:
                try:
                    err = await r.json()
                    err_msg = err["text"]
                except (json.JSONDecodeError, KeyError, ContentTypeError):
                    err_msg = ""
                if r.status == 400:
                    if err_msg == "invalid key":
                        raise APIInvalidKey("Invalid key")
                    raise APIBadRequest("Bad request")
                if r.status == 404:
                    raise APINotFound("Not found")
                if r.status == 403:
                    if err_msg == "invalid key":
                        raise APIInvalidKey("Invalid key")
                    raise APIForbidden("Access denied")
                if r.status == 503 and err_msg == "API not active":
                    raise APIInactiveError("API is dead")
                if r.status == 429:
                    self.log.error("API Call limit saturated")
                    raise APIRateLimited(
                        "Requests limit has been saturated. Try again later.")
                else:
                    raise APIConnectionError("{} {}".format(r.status, err_msg))
            data = await r.json()
            asyncio.create_task(self.cache_result(endpoint, data, key, user))
            return data


text:
package org.gradle.api.internal.changedetection.rules;

import org.gradle.api.NonNullApi;
import org.gradle.api.Task;
import org.gradle.api.internal.changedetection.state.TaskExecution;
import org.gradle.internal.fingerprint.FileCollectionFingerprint;

import java.util.SortedMap;

@NonNullApi
public class InputFilePropertyTaskStateChanges extends AbstractPropertyTaskStateChanges<FileCollectionFingerprint> {

    public InputFilePropertyTaskStateChanges(TaskExecution previous, TaskExecution current, Task task) {
        super(previous, current, "Input file", task);
    }

    @Override
    protected SortedMap<String, ? extends FileCollectionFingerprint> getProperties(TaskExecution execution) {
        return execution.getInputFingerprints();
    }
}


text:
class <%= @scope_prefix %>SessionsController < DeviseJwt::SessionsController
  # def create
  #   super
  # end
  #
  # def destroy
  #   super
  # end
end


text:
Title: Code Cards v1.2
Date: 2011-01-11 23:13
Category: Sākums
Tags: 2011
Lang: en

I just wanted to mention, that since yestereday [Code Cards 1.2][1]  have been approved and is available on [App Store][2].

This update took 3 days to process. Nice work Apple. :)

P.s. This is more like a bug fix version.

  [1]: http://codecards.gm.lv/
  [2]: http://itunes.apple.com/us/app/code-cards/id412350680?mt=8&ls=1


text:
/** @jsx React.DOM */
var assert = require('chai').assert;
var _ = require('lodash');
var sinon = require('sinon');
var FilterValueFields = require('../../../../client/js/app/components/common/filter_value_fields.js');
var Geo = require('../../../../client/js/app/components/common/geo.js');
var Datepicker = require('../../../../client/js/app/components/common/datepicker.js');
var Select = require('../../../../client/js/app/components/common/select.js');
var ProjectUtils = require('../../../../client/js/app/utils/ProjectUtils');
var React = require('react/addons');
var TestUtils = React.addons.TestUtils;
var TestHelpers = require('../../../support/TestHelpers');

describe('components/common/filter_value_fields', function() {

  beforeEach(function() {
    this.project = TestHelpers.createProject();
    this.model = TestHelpers.createExplorerModel();;
    this.model.event_collection = 'click';
    this.filter = {
      property_name: 'propOne',
      operator: 'eq',
      property_value: 'abc',
      coercion_type: 'String'
    };
    this.index = 0;

    this.component = TestUtils.renderIntoDocument(<FilterValueFields model={this.model} filter={this.filter} project={this.project} index={this.index} />);
  });

  describe('setup', function() {
    it('is of the right type', function() {
      assert.isTrue(TestUtils.isCompositeComponentWithType(this.component, FilterValueFields));
    });

    describe('Datetime', function() {
      beforeEach(function(){
        this.component.props.filter.coercion_type = 'Datetime';
        this.component.forceUpdate();
      });

      it('has a Datetime component', function(){
        assert.lengthOf(TestUtils.scryRenderedComponentsWithType(this.component, Datepicker), 1);
      });
    });

    describe('Boolean', function() {
      beforeEach(function(){
        this.component.props.filter.coercion_type = 'Boolean';
        this.component.forceUpdate();
      });

      it('has a Select component', function(){
        assert.lengthOf(TestUtils.scryRenderedComponentsWithType(this.component, Select), 2);
      });

      it('has no input tags', function(){
        assert.lengthOf(TestUtils.scryRenderedDOMComponentsWithTag(this.component, 'input'), 0);
      });
    });

    describe('Null', function () {
      beforeEach(function () {
        this.component.props.filter.coercion_type = 'Null';
        this.component.forceUpdate();
        assert.lengthOf(TestUtils.scryRenderedDOMComponentsWithTag(this.component, 'input'), 1);
      });

      it('has a readonly input', function () {
        var input = TestUtils.scryRenderedDOMComponentsWithTag(this.component, 'input')[0];
        assert.isTrue(input.props.readOnly);
      });

      it('the input value has a placeholder of \'null\'', function () {
        var input = TestUtils.scryRenderedDOMComponentsWithTag(this.component, 'input')[0];
        assert.equal(input.props.placeholder, 'Null');
      });
    });

    describe('Geo', function () {
      beforeEach(function () {
        this.component.props.filter = {
          property_name: 'geoProp',
          coercion_type: 'Geo',
          operator: 'within',
          property_value: {
            coordinates: [],
            max_distance_miles: null
          }
        };
        sinon.stub(ProjectUtils, 'getPropertyType');
        this.component.forceUpdate();
      });

      afterEach(function () {
        ProjectUtils.getPropertyType.restore();
      });

      it('has a Geo component', function(){
        assert.lengthOf(TestUtils.scryRenderedComponentsWithType(this.component, Geo), 1);
      });

      it('has 3 inputs for geo-location query data', function(){
        assert.lengthOf(TestUtils.scryRenderedDOMComponentsWithTag(this.component, 'input'), 3);
      });
    });

    describe('not Boolean or Datetime or Null', function() {
      beforeEach(function(){
        this.component.props.filter.coercion_type = 'String';
        this.component.forceUpdate();
      });

      it('does not have a Datetime component', function(){
        assert.lengthOf(TestUtils.scryRenderedComponentsWithType(this.component, Datepicker), 0);
      });

      it('has one input', function(){
        assert.lengthOf(TestUtils.scryRenderedDOMComponentsWithTag(this.component, 'input'), 1);
      });

      it('has one select', function(){
        assert.lengthOf(TestUtils.scryRenderedComponentsWithType(this.component, Select), 1);
      });
    });

    describe('available coercion types', function () {
      describe('when property type is not geo', function () {
        it('has all the coercion types', function () {
          var defaultCoercionOptions = ['String', 'Number', 'Null', 'List', 'Boolean', 'Datetime']

          this.component.props.filter.property_name = 'stringProp';
          this.component.forceUpdate();

          var coercionTypeSelect = TestUtils.scryRenderedDOMComponentsWithTag(this.component, 'select')[0].getDOMNode();
          var coercionOptions = _.map(coercionTypeSelect.childNodes, function(node){
            return node.value;
          });
          coercionOptions = _.compact(coercionOptions);

          assert.sameMembers(defaultCoercionOptions, coercionOptions);
        });
      });
    });
    describe('available property value options when Boolean', function () {
      it('is true or false', function () {
        this.component.props.filter = { operator: 'exists', coercion_type: 'Boolean' };
        this.component.forceUpdate()
        var boolPropValueSelect = this.component.refs['boolean-value-set'].getDOMNode().lastChild

        var boolPropValueSelectOptions = _.map(boolPropValueSelect.childNodes, function(node){
          return node.value;
        });
        propertyValueOptions = _.compact(boolPropValueSelectOptions);

        assert.sameMembers(propertyValueOptions, ['true', 'false']);
      });
    });
  });
});


text:
require 'tmpdir'

class UISpecRunner
  class Drivers
    class WaxSim
      WAXSIM_BIN_DIR = File.expand_path(File.join(File.dirname(__FILE__), '..', '..', '..', 'ext', 'bin'))

      attr_reader :config

      def initialize(config)
        @config = config
      end

      def waxsim_path
        File.join(WAXSIM_BIN_DIR, 'waxsim')
      end

      def family_switch
        "-f #{config.family}" if config.family
      end

      def run_specs(env)
        env_args = env.map { |k,v| "-e #{k}=#{v} "}.join(' ')
        exit_status = nil
        command = %Q{#{waxsim_path} -s #{config.sdk_version} #{family_switch} #{env_args} "#{config.app_path}"}
        puts "Executing command: #{command}" if config.verbose?
        `#{command}`

        # TODO: Total hack. Can't figure out how to get the exit status any other way.
        # WaxSim can't get the child pid because the process isn't forked as a child. The output
        # can't be parsed directly because of funkiness with the file descriptors. Better ideas?
        exit_status = `tail /var/log/system.log| grep "Exiting with status code:"`.split(/code\:\s/).last.to_i

        return exit_status
      end
    end
  end
end


text:
from django.contrib.auth.models import User
from django.forms import ModelForm

class ToggleStaffForm(ModelForm):
    class Meta:
        model = User
        fields = ('is_staff',)
        help_texts = {
            'is_staff': 'Designates whether the user can modify staff specific models and non-staff object instances.'
        }
        labels = {
            'is_staff': 'User is Staff Member'
        }


text:
package org.apache.geode.internal.cache;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

import org.junit.Test;

import org.apache.geode.internal.cache.InitialImageOperation.RequestRVVMessage;

public class RequestRVVMessageTest {

  @Test
  public void shouldBeMockable() throws Exception {
    RequestRVVMessage mockRequestRVVMessage = mock(RequestRVVMessage.class);
    when(mockRequestRVVMessage.getProcessorType()).thenReturn(1);
    assertThat(mockRequestRVVMessage.getProcessorType()).isEqualTo(1);
  }
}


text:
export { default as Theme } from './Theme';
export { default as Login } from './Login';
export { default as Register } from './Register';
export { default as ForgotPassword } from './ForgotPassword';
export { default as RecoverPassword } from './RecoverPassword';
export { default as AddSite } from './AddSite';
export { default as Sites } from './Sites';
export { default as SiteHome } from './SiteHome';
export { default as CheckSite } from './CheckSite';
export { default as EditSite } from './EditSite';


text:
'use strict';

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

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _reactBootstrap = require('react-bootstrap');

var _reactRouterBootstrap = require('react-router-bootstrap');

var _lodash = require('lodash');

var _lodash2 = _interopRequireDefault(_lodash);

require('../css/strapmenu.css');

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

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var GENERATOR_FIELDS = ['path', 'name', 'icon', 'divideAfter'];

var Strapmenu = function (_React$Component) {
    _inherits(Strapmenu, _React$Component);

    function Strapmenu() {
        _classCallCheck(this, Strapmenu);

        return _possibleConstructorReturn(this, (Strapmenu.__proto__ || Object.getPrototypeOf(Strapmenu)).apply(this, arguments));
    }

    _createClass(Strapmenu, [{
        key: 'calculateRoutes',
        value: function calculateRoutes() {

            var _routes = this.props.routes;
            var mainRoute = _routes[0];

            if (!mainRoute.childRoutes || mainRoute.childRoutes.length < 1) {
                return console.error('No child routes.');
            }

            var generatedRoutes = [];

            // TODO : Sorting
            var flatten = function flatten(routerRoutes) {

                routerRoutes.forEach(function (route) {

                    if (route.exposed) {

                        generatedRoutes.push(_lodash2.default.pick(route, GENERATOR_FIELDS));

                        if (route.childRoutes) {
                            flatten(route.childRoutes);
                        }
                    }

                    if (route.divideAfter) {
                        generatedRoutes.push({ divider: true });
                    }
                });

                return generatedRoutes;
            };

            return flatten(mainRoute.childRoutes);
        }
    }, {
        key: 'render',
        value: function render() {

            if (!this.props.routes) {
                console.error('gimme routs');
                return _react2.default.createElement(
                    'div',
                    null,
                    'No routes found'
                );
            }

            var _routes = this.calculateRoutes();

            return _react2.default.createElement(
                _reactBootstrap.NavDropdown,
                this.props.dropdownProps,
                _lodash2.default.map(_routes, function (route) {

                    if (route.divider) return _react2.default.createElement(_reactBootstrap.MenuItem, { key: ['divider', _lodash2.default.random(1000)].join('_'), divider: true });

                    return _react2.default.createElement(
                        _reactRouterBootstrap.LinkContainer,
                        { key: route.path, to: { pathname: route.path } },
                        _react2.default.createElement(
                            _reactBootstrap.MenuItem,
                            null,
                            _react2.default.createElement(
                                'div',
                                { className: 'menu-item-icon' },
                                _react2.default.createElement('span', { className: route.icon })
                            ),
                            _react2.default.createElement(
                                'div',
                                { className: 'menu-item-title' },
                                route.name
                            )
                        )
                    );
                })
            );
        }
    }]);

    return Strapmenu;
}(_react2.default.Component);

Strapmenu.propTypes = {
    routes: _react2.default.PropTypes.arrayOf(_react2.default.PropTypes.object).isRequired,
    dropdownProps: _react2.default.PropTypes.shape({
        id: _react2.default.PropTypes.string.isRequired,
        title: _react2.default.PropTypes.string.isRequired
    })
};

Strapmenu.defaultProps = {
    dropdownProps: {
        id: 'navbar-dropdown',
        title: 'Dropdown'
    }
};

exports.default = Strapmenu;


text:
namespace Cedar.EventStore
{
    using Xunit.Abstractions;

    public class GesEventStoreTests : EventStoreAcceptanceTests
    {
        public GesEventStoreTests(ITestOutputHelper testOutputHelper)
            : base(testOutputHelper)
        {}

        protected override EventStoreAcceptanceTestFixture GetFixture()
        {
            return new GesEventStoreFixture();
        }
    }
}


text:
package cors.web;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class IndexController {

	@Autowired
	private ApplicationContext context;

	 @RequestMapping(value="/",method=RequestMethod.GET)
	    public String index() {
//		 context.getBean("mapperScannerConfigurer");
	        return "redirect:/medicalCase/query";
		}

}


text:
If you're looking for instructions on how to setup the Hyperledger Fabric development environment, see
the [development environment setup readme](https://github.com/hyperledger/fabric/blob/master/docs/dev-setup/devenv.md).

This folder contains the files which are used for bootstrapping the Hyperledger Fabric development environment.

Below is a deployment diagram of the current development environment. Note that version numbers may be out of date.
![Development Environment Deployment Diagram](./images/openchain-dev-env-deployment-diagram.png)

# Storage Backends

You may optionally choose a docker storage backend other than the default.

For a comparison of the assorted storage backends refer to [select a storage driver](https://docs.docker.com/engine/userguide/storagedriver/selectadriver/)

Presently, the default is set to AUFS, but this may change in the future.

To select a different storage backend (btrfs in this example), simply execute

```
vagrant destroy
DOCKER_STORAGE_BACKEND=btrfs vagrant up
```

Currently supported backends are btfs, and aufs, with more to be added in the future.

This work is licensed under a Creative Commons Attribution 4.0 International License.
s


text:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
class ResponseData {
}
exports.ResponseData = ResponseData;
//# sourceMappingURL=responsedata.model.js.map


text:
var Enrollment = (function($) {
  var options = $.extend(true, {}, $.config.enrollment);

  return Class.create({
    initialize: wrap(function(container) {
      $.Views.getAll(this, options.templates);

      this.downloadEnrollment();
      setInterval(this.downloadEnrollment.wrap(this), options.refresh*1000);

      var shadow = $($.shadowTemplate.render()).appendTo(container);
      shadow.wrap("

");
      this.sidebar = shadow.find('.dropShadowContent');
    }),

    downloadEnrollment: function() {
      // Copy the current enrollment data to a hash so we can figure out which courses have changed
      this.oldEnrollment = {};
      if($.enrollment) {
        var courses = $.scheduleManager.courses;
        for(var c = 0; c < courses.length; c++) {
          this.oldEnrollment[courses[c].id] = $.enrollment[courses[c].id];
        }
      }

      $.get(image_path(options.url));
    },

    // Callback when enrollment data is updated
    update: wrap(function() {
      this.changed = {};

      var courses = $.scheduleManager.courses;
      for(var c = 0; c < courses.length; c++) {
        var course = courses[c];
        var id = course.id;
        if(typeof id !== "number") continue;

        // If the data was not there before
        if(!this.oldEnrollment[id]) {
          this.changed[id] = true;
        } else {
          // If the data does not match the previous data
          var old = this.oldEnrollment[id];
          var cur = $.enrollment[id];
          if(cur === undefined || old[0] != cur[0] ) {
            this.changed[id] = true;
          }
        }
      }

      this.render();
      this.oldEnrollment = {};
      this.changed = {};
    }),

    render: function() {
      var html = this.enrollmentSidebar.render({
        changed: this.changed,
        courses: $.scheduleManager.courses.sort(function(a, b) { return a.sectionid < b.sectionid ? -1 : 1; })
      });
      this.sidebar.html(html);

      // IE throws a fit with the highlight effect
      if(!($.browser.msie && $.browser.version < 9)) {
        $('dd[data-changed=yes]', this.sidebar[0]).
          animate({backgroundColor: options.highlightColor}).
          animate({backgroundColor: '#FFF'}, options.highlightDuration);
      }
    }
  });
})(jQuery);


text:
import igraph as ig
import numpy as np
import fastlayout as fl
import time

# load graph data
g = ig.load( filename='data/medium_example_network.txt', format='ncol' )

# set various constants
dimension = 2
max_it = 500
temp = 1
# get number of nodes
nodes = len(g.vs)
# get edges in the right format
edgelist = np.array( [edge.tuple for edge in g.es], np.int32)

# call igraph first
# this is only to compare - timing as well as output
print 'igraph'
start = time.clock()
igLayout = g.layout_fruchterman_reingold()
elapsed = time.clock()
elapsed = elapsed - start
print "Time spent in (layout_fruchterman_reingold) is: ", elapsed
ig.plot(g, "output/plot_igraph.png", layout=igLayout)

# call all versions with old data format
# this is only for reference
print 'layout_fr (float baseline)'
start = time.clock()
pos = fl.layout_fr(nodes*dimension, edgelist, max_it, temp )
pos = np.reshape(pos, (nodes, dimension))
floatLayout = ig.Layout( tuple(map(tuple, pos )) )
elapsed = time.clock()
elapsed = elapsed - start
print "Time spent in (layout_fr) is: ", elapsed
ig.plot(g, "output/plot_fr_float_baseline.png", layout=floatLayout)

print 'layout_fr_omp'
start = time.clock()
pos = fl.layout_fr_omp( nodes*dimension, edgelist, max_it, temp )
pos = np.reshape(pos, (nodes, dimension))
float2Layout = ig.Layout( tuple(map(tuple, pos)) )
elapsed = time.clock()
elapsed = elapsed - start
print "Time spent in (layout_fr_omp) is: ", elapsed
ig.plot(g, "output/plot_fr_omp.png", layout=float2Layout)

print 'layout_fr_simd'
start = time.clock()
pos = fl.layout_fr_simd( nodes*dimension, edgelist, max_it, temp )
pos = np.reshape(pos, (nodes, dimension))
float3Layout = ig.Layout( tuple(map(tuple, pos)) )
elapsed = time.clock()
elapsed = elapsed - start
print "Time spent in (layout_fr_simd) is: ", elapsed
ig.plot(g, "output/plot_fr_simd.png", layout=float3Layout)

print 'layout_fr_omp_simd'
start = time.clock()
pos = fl.layout_fr_omp_simd( nodes*dimension, edgelist, max_it, temp )
pos = np.reshape( pos, (nodes, dimension) )
float6Layout = ig.Layout( tuple(map(tuple, pos)) )
elapsed = time.clock()
elapsed = elapsed - start
print "Time spent in (layout_fr_omp_simd) is: ", elapsed
ig.plot(g, "output/plot_fr_omp_simd.png", layout=float6Layout)

# call new implementations with strided data layout

# NOTE
# this one works different as it uses a different layout
# for the data, so no reshaping has to be done, but you
# have to zip first and second half of the array
print 'layout_fr_stride (strided float baseline)'
start = time.clock()
pos = fl.layout_fr_stride( nodes*dimension, edgelist, max_it, temp )
float6Layout = ig.Layout( tuple(zip(pos[0:nodes], pos[nodes:2*nodes])) )
elapsed = time.clock()
elapsed = elapsed - start
print "Time spent in (layout_fr_stride) is: ", elapsed
ig.plot(g, "output/plot_fr_stride.png", layout=float6Layout)

print 'layout_fr_stride_simd'
start = time.clock()
pos = fl.layout_fr_stride_simd( nodes*dimension, edgelist, max_it, temp )
myLayout = ig.Layout( tuple(zip(pos[0:nodes], pos[nodes:2*nodes])) )
elapsed = time.clock()
elapsed = elapsed - start
print "Time spent in (layout_fr_stride_simd) is: ", elapsed
ig.plot(g, "output/plot_fr_simd_stride.png", layout=myLayout)

print 'layout_fr_stride_omp'
start = time.clock()
pos = fl.layout_fr_stride_omp( nodes*dimension, edgelist, max_it, temp )
myLayout = ig.Layout( tuple(zip(pos[0:nodes], pos[nodes:2*nodes])) )
elapsed = time.clock()
elapsed = elapsed - start
print "Time spent in (layout_fr_stride_omp) is: ", elapsed
ig.plot(g, "output/plot_fr_omp_stride.png", layout=myLayout)

print 'layout_fr_stride_omp_simd'
start = time.clock()
pos = fl.layout_fr_stride_omp_simd( nodes*dimension, edgelist, max_it, temp )
myLayout = ig.Layout( tuple(zip(pos[0:nodes], pos[nodes:2*nodes])) )
elapsed = time.clock()
elapsed = elapsed - start
print "Time spent in (layout_fr_stride_omp_simd) is: ", elapsed
ig.plot(g, "output/plot_fr_omp_stride_simd.png", layout=myLayout)


text:
from litex.soc.tools.remote import RemoteClient

import time

# DDR3 init and test for a7ddrphy design
# use arty_ddr3 design with this script to
# find working bitslip/delay configuration

dfii_control_sel     = 0x01
dfii_control_cke     = 0x02
dfii_control_odt     = 0x04
dfii_control_reset_n = 0x08

dfii_command_cs     = 0x01
dfii_command_we     = 0x02
dfii_command_cas    = 0x04
dfii_command_ras    = 0x08
dfii_command_wrdata = 0x10
dfii_command_rddata = 0x20

wb = RemoteClient(debug=True)
wb.open()
regs = wb.regs

# # #

regs.sdram_dfii_control.write(0)

# release reset
regs.sdram_dfii_pi0_address.write(0x0)
regs.sdram_dfii_pi0_baddress.write(0)
regs.sdram_dfii_control.write(dfii_control_odt|dfii_control_reset_n)
time.sleep(0.1)

# bring cke high
regs.sdram_dfii_pi0_address.write(0x0)
regs.sdram_dfii_pi0_baddress.write(0)
regs.sdram_dfii_control.write(dfii_control_cke|dfii_control_odt|dfii_control_reset_n)
time.sleep(0.1)

# load mode register 2
regs.sdram_dfii_pi0_address.write(0x408)
regs.sdram_dfii_pi0_baddress.write(2)
regs.sdram_dfii_pi0_command.write(dfii_command_ras|dfii_command_cas|dfii_command_we|dfii_command_cs)
regs.sdram_dfii_pi0_command_issue.write(1)

# load mode register 3
regs.sdram_dfii_pi0_address.write(0x0)
regs.sdram_dfii_pi0_baddress.write(3)
regs.sdram_dfii_pi0_command.write(dfii_command_ras|dfii_command_cas|dfii_command_we|dfii_command_cs)
regs.sdram_dfii_pi0_command_issue.write(1)

# load mode register 1
regs.sdram_dfii_pi0_address.write(0x6);
regs.sdram_dfii_pi0_baddress.write(1);
regs.sdram_dfii_pi0_command.write(dfii_command_ras|dfii_command_cas|dfii_command_we|dfii_command_cs)
regs.sdram_dfii_pi0_command_issue.write(1)

# load mode register 0, cl=7, bl=8
regs.sdram_dfii_pi0_address.write(0x930);
regs.sdram_dfii_pi0_baddress.write(0);
regs.sdram_dfii_pi0_command.write(dfii_command_ras|dfii_command_cas|dfii_command_we|dfii_command_cs)
regs.sdram_dfii_pi0_command_issue.write(1)
time.sleep(0.1)

# zq calibration
regs.sdram_dfii_pi0_address.write(0x400);
regs.sdram_dfii_pi0_baddress.write(0);
regs.sdram_dfii_pi0_command.write(dfii_command_we|dfii_command_cs)
regs.sdram_dfii_pi0_command_issue.write(1)
time.sleep(0.1)

# hardware control
regs.sdram_dfii_control.write(dfii_control_sel)

def seed_to_data(seed, random=True):
    if random:
        return (1664525*seed + 1013904223) & 0xffffffff
    else:
        return seed

def write_pattern(length):
    for i in range(length):
        wb.write(wb.mems.main_ram.base + 4*i, seed_to_data(i))

def check_pattern(length):
    errors = 0
    for i in range(length):
        error = 0
        if wb.read(wb.mems.main_ram.base + 4*i) != seed_to_data(i):
            error = 1
            print("{}: 0x{:08x}, 0x{:08x} KO".format(i, wb.read(wb.mems.main_ram.base + 4*i), seed_to_data(i)))
        else:
            print("{}: 0x{:08x}, 0x{:08x} OK".format(i, wb.read(wb.mems.main_ram.base + 4*i), seed_to_data(i)))
        errors += error
    return errors

# find working bitslips and delays
for bitslip in range(4):
    for delay in range(32):
        for k in range(2):
            regs.ddrphy_dly_sel.write(1<<k)
            regs.ddrphy_rdly_dq_rst.write(1)
            for i in range(bitslip):
                # 7-series SERDES in DDR mode needs 3 pulses for 1 bitslip
                for j in range(3):
                    regs.ddrphy_rdly_dq_bitslip.write(1)
            for i in range(delay):
                regs.ddrphy_rdly_dq_inc.write(1)
        print("bitslip={}, delay={}".format(bitslip, delay))
        write_pattern(32)
        if check_pattern(32) == 0:
            print("bitslip={}, delay={}".format(bitslip, delay))
            write_pattern(1024)
            print("errors : %d" %check_pattern(1024))
            exit()

# # #

wb.close()


text:
<?php

namespace Symfony\Component\Messenger\Stamp;

/**
 * A stamp that should not be included with the Envelope if sent to a transport.
 *
 * @author Ryan Weaver <ryan@symfonycasts.com>
 */
interface NonSendableStampInterface extends StampInterface
{
}


text:
package com.datastax.driver.core;

import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

import com.datastax.driver.core.utils.CassandraVersion;

import static com.datastax.driver.core.Assertions.*;
import static com.datastax.driver.core.Host.State.DOWN;
import static com.datastax.driver.core.Host.State.UP;
import static com.datastax.driver.core.TestUtils.nonDebouncingQueryOptions;

/**
 * Due to C* gossip bugs, system.peers may report nodes that are gone from the cluster.
 *
 * This class tests scenarios where these nodes have been recommissioned to another cluster and
 * come back up. The driver must detect that they are not part of the cluster anymore, and ignore them.
 */
public class RecommissionedNodeTest {
    private static final Logger logger = LoggerFactory.getLogger(RecommissionedNodeTest.class);

    CCMBridge mainCcm, otherCcm;
    Cluster mainCluster;

    @Test(groups = "long")
    public void should_ignore_recommissioned_node_on_reconnection_attempt() throws Exception {
        mainCcm = CCMBridge.builder("main").withNodes(3).build();
        // node1 will be our "recommissioned" node, for now we just stop it so that it stays in the peers table.
        mainCcm.stop(1);
        mainCcm.waitForDown(1);

        // Now start the driver that will connect to node2 and node3, and consider node1 down
        mainCluster = Cluster.builder().addContactPoint(CCMBridge.IP_PREFIX + "2")
            .withQueryOptions(nonDebouncingQueryOptions()).build();
        mainCluster.connect();
        waitForCountUpHosts(mainCluster, 2);
        // From that point, reconnections to node1 have been scheduled.

        // Start another ccm that will reuse node1's address
        otherCcm = CCMBridge.builder("other").withNodes(1).build();
        otherCcm.waitForUp(1);

        // Give the driver the time to notice the node is back up and try to connect to it.
        TimeUnit.SECONDS.sleep(32);

        assertThat(countUpHosts(mainCluster)).isEqualTo(2);
    }

    @Test(groups = "long")
    public void should_ignore_recommissioned_node_on_control_connection_reconnect() throws Exception {
        mainCcm = CCMBridge.builder("main").withNodes(2).build();
        mainCcm.stop(1);
        mainCcm.waitForDown(1);

        // Start the driver, the control connection will be on node2
        mainCluster = Cluster.builder().addContactPoint(CCMBridge.IP_PREFIX + "2")
            .withQueryOptions(nonDebouncingQueryOptions()).build();
        mainCluster.connect();
        waitForCountUpHosts(mainCluster, 1);

        // Start another ccm that will reuse node1's address
        otherCcm = CCMBridge.builder("other").withNodes(1).build();
        otherCcm.waitForUp(1);

        // Stop node2, the control connection gets defunct
        mainCcm.stop(2);
        TimeUnit.SECONDS.sleep(32);

        // The driver should not try to reconnect the control connection to node1
        assertThat(mainCluster).hasClosedControlConnection();
    }

    @Test(groups = "long")
    public void should_ignore_recommissioned_node_on_session_init() throws Exception {
        // Simulate the bug before starting the cluster
        mainCcm = CCMBridge.builder("main").withNodes(2).build();
        mainCcm.stop(1);
        mainCcm.waitForDown(1);

        otherCcm = CCMBridge.builder("other").withNodes(1).build();
        otherCcm.waitForUp(1);

        // Start the driver, it should only connect to node 2
        mainCluster = Cluster.builder().addContactPoint(CCMBridge.IP_PREFIX + "2")
            .withQueryOptions(nonDebouncingQueryOptions()).build();

        // When we first initialize the Cluster, all hosts are marked UP
        assertThat(mainCluster).host(2).hasState(UP);
        assertThat(mainCluster).host(1).hasState(UP);

        // Create a session. This will try to open a pool to node 1 and find out that the cluster name doesn't match.
        mainCluster.connect();

        // Node 1 should now be DOWN with no reconnection attempt
        assertThat(mainCluster).host(1)
            .goesDownWithin(10, TimeUnit.SECONDS)
            .hasState(DOWN)
            .isNotReconnectingFromDown();
    }

    @Test(groups = "long")
    @CassandraVersion(major=2.0)
    public void should_ignore_node_that_does_not_support_protocol_version_on_session_init() throws Exception {
        // Simulate the bug before starting the cluster
        mainCcm = CCMBridge.builder("main").withNodes(2).build();
        mainCcm.stop(1);
        mainCcm.waitForDown(1);

        otherCcm = CCMBridge.builder("main").withNodes(1).withCassandraVersion("1.2.19").build();
        otherCcm.waitForUp(1);

        // Start the driver, it should only connect to node 2
        mainCluster = Cluster.builder().addContactPoint(CCMBridge.IP_PREFIX + "2")
            .withQueryOptions(nonDebouncingQueryOptions()).build();

        // Create a session. This will try to open a pool to node 1 and find that it doesn't support protocol version.
        mainCluster.connect();

        // Node 1 should now be DOWN with no reconnection attempt
        assertThat(mainCluster).host(1)
            .goesDownWithin(10, TimeUnit.SECONDS)
            .hasState(DOWN)
            .isNotReconnectingFromDown();
    }

    @BeforeMethod(groups = "long")
    public void clearFields() {
        // Clear cluster and ccm instances between tests.
        mainCluster = null;
        mainCcm = null;
        otherCcm = null;
    }

    @AfterMethod(groups = "long")
    public void teardown() {
        if (mainCluster != null)
            mainCluster.close();

        if (mainCcm != null)
            mainCcm.remove();
        if (otherCcm != null)
            otherCcm.remove();
    }

    private static int countUpHosts(Cluster cluster) {
        int ups = 0;
        for (Host host : cluster.getMetadata().getAllHosts()) {
            if (host.isUp())
                ups += 1;
        }
        return ups;
    }

    private static void waitForCountUpHosts(Cluster cluster, int expectedCount) throws InterruptedException {
        int maxRetries = 10;
        int interval = 6;

        for (int i = 0; i <= maxRetries; i++) {
            int actualCount = countUpHosts(cluster);
            if (actualCount == expectedCount)
                return;

            if (i == maxRetries)
                fail(String.format("Up host count didn't reach %d after %d seconds",
                                   expectedCount, i * interval));
            else
                logger.debug("Counted {} up hosts after {} seconds", actualCount, i * interval);

            TimeUnit.SECONDS.sleep(interval);
        }
    }
}


text:
'use strict';

const clone = require('clone');
const util = require('../util.js');
const crawlers = require('../crawlers');

const NAME = 'pacopacomama';
module.exports.name = function () {
    return NAME;
}

const TARGET = 'movie';
module.exports.target = function () {
    return TARGET;
}

function crawl (opt) {
    let crawler1 = crawlers["pacopacomama"];
    let crawler2 = crawlers["pacopacomama-en"];

    return Promise.all([
        crawler1.crawl(opt),
        crawler2.crawl(opt)
            .catch(err => {
                console.log(err);
                return null
            }),
    ])
    .then(data => {
        let d1 = data[0];
        let d2 = data[1];

        if (d1 == null) {
            return null;
        } else {
            let d = util.syncObjects(d1, d2)
            if (d2) {
                if (d2.genres.length > 0) d.genres = d2.genres;
            }

            return d;
        }
    });
}

module.exports.crawl = crawl;


text:
The Ceaseless Prayer app for iOS is built natively

# Download on the App Store

You can download the app on the [App Store](https://itunes.apple.com/us/app/ceaseless/id973610764?mt=8)

# Translating the app

In order to translate the app it's not necessary to install anything on your computer - you can just use the translation platform [lokalise](https://app.lokalise.com/project/338603745bd8cae0042d51.84066670/) and we'll take care of the rest.

# Development Setup

You may want to install [XCode](https://developer.apple.com/tools/xcode/).

# Working on the app

Coming soon.

# Testing

For testing we use [BrowserStack](https://browserstack.com)

![https://browserstack.com](Browserstack-logo@2x.png?raw=true "Browserstack logo")


text:
using Rabbit.Kernel;
using System.Collections.Generic;

namespace Rabbit.Web.Routes
{
    /// <summary>
    /// 一个抽象的路由发布者。
    /// </summary>
    public interface IRoutePublisher : IDependency
    {
        /// <summary>
        /// 发布路由。
        /// </summary>
        /// <param name="routes">路由集合。</param>
        void Publish(IEnumerable<RouteDescriptor> routes);
    }
}


text:
package org.opencb.commons.datastore.mongodb;

import com.mongodb.client.MongoCursor;
import org.bson.Document;
import org.opencb.commons.datastore.core.ComplexTypeConverter;

import java.io.Closeable;
import java.util.Iterator;

public class MongoDBIterator<E> implements Iterator<E>, Closeable {

    private MongoCursor<Document> iterator;
    private ComplexTypeConverter<E, Document> converter;
    private long numMatches;

    public MongoDBIterator(MongoCursor<Document> iterator, long numMatches) {
        this(iterator, null, numMatches);
    }

    public MongoDBIterator(MongoCursor<Document> iterator, ComplexTypeConverter<E, Document> converter, long numMatches) {
        this.iterator = iterator;
        this.converter = converter;
        this.numMatches = numMatches;
    }

    @Override
    public boolean hasNext() {
        return iterator != null && iterator.hasNext();
    }

    @Override
    public E next() {
        Document next = iterator.next();

        if (converter != null) {
            return converter.convertToDataModelType(next);
        } else {
            return (E) next;
        }
    }

    public long getNumMatches() {
        return numMatches;
    }

    @Override
    public void close() {
        if (iterator != null) {
            iterator.close();
        }
    }
}


text:
Lurn is a ruby gem for performing machine learning tasks. The API and design patterns in Lurn are inspired by scikit-learn, a popular machine learning library for Python.

# Documentation

[www.lurnrb.com](https://www.lurnrb.com)

## Installation

Add this line to your application's Gemfile:

```ruby
gem 'lurn'
```

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install lurn

## Usage

- Naive Bayes
  - [Bernoulli Naive Bayes](readmes/naive_bayes/bernoulli_naive_bayes.md)
  - [Multinomial Naive Bayes](readmes/naive_bayes/multinomial_naive_bayes.md)
- Nearest Neighbor Models
  - [K Nearest Neighbor Regression](readmes/neighbors/knn_regression.md)
  - [K Nearest Neighbor Classification](readmes/neighbors/knn_classification.md)
- Text Processing
  - [Bernoulli Vectorizer](readmes/text_processing/bernoulli_vectorizer.md)
- Model Evaluation
  - [ClassifierEvaluator](readmes/evaluation/classifier_evaluator.md)

## Development

After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.

To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org).

## Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/dansbits/lurn.

## License

The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT).


text:
import os
import sys
from mercurial.cmdutil import revrange, show_changeset
from mercurial.commands import templateopts
from mercurial.i18n import _
from mercurial.node import nullrev
from mercurial.util import Abort, canonpath

def revision_grapher(repo, start_rev, stop_rev):
    """incremental revision grapher

    This generator function walks through the revision history from
    revision start_rev to revision stop_rev (which must be less than
    or equal to start_rev) and for each revision emits tuples with the
    following elements:

      - Current revision.
      - Current node.
      - Column of the current node in the set of ongoing edges.
      - Edges; a list of (col, next_col) indicating the edges between
        the current node and its parents.
      - Number of columns (ongoing edges) in the current revision.
      - The difference between the number of columns (ongoing edges)
        in the next revision and the number of columns (ongoing edges)
        in the current revision. That is: -1 means one column removed;
        0 means no columns added or removed; 1 means one column added.
    """

    assert start_rev >= stop_rev
    curr_rev = start_rev
    revs = []
    while curr_rev >= stop_rev:
        node = repo.changelog.node(curr_rev)

        # Compute revs and next_revs.
        if curr_rev not in revs:
            # New head.
            revs.append(curr_rev)
        rev_index = revs.index(curr_rev)
        next_revs = revs[:]

        # Add parents to next_revs.
        parents = get_rev_parents(repo, curr_rev)
        parents_to_add = []
        for parent in parents:
            if parent not in next_revs:
                parents_to_add.append(parent)
        parents_to_add.sort()
        next_revs[rev_index:rev_index + 1] = parents_to_add

        edges = []
        for parent in parents:
            edges.append((rev_index, next_revs.index(parent)))

        n_columns_diff = len(next_revs) - len(revs)
        yield (curr_rev, node, rev_index, edges, len(revs), n_columns_diff)

        revs = next_revs
        curr_rev -= 1

def filelog_grapher(repo, path, start_rev, stop_rev):
    """incremental file log grapher

    This generator function walks through the revision history of a
    single file from revision start_rev to revision stop_rev (which must
    be less than or equal to start_rev) and for each revision emits
    tuples with the following elements:

      - Current revision.
      - Current node.
      - Column of the current node in the set of ongoing edges.
      - Edges; a list of (col, next_col) indicating the edges between
        the current node and its parents.
      - Number of columns (ongoing edges) in the current revision.
      - The difference between the number of columns (ongoing edges)
        in the next revision and the number of columns (ongoing edges)
        in the current revision. That is: -1 means one column removed;
        0 means no columns added or removed; 1 means one column added.
    """

    assert start_rev >= stop_rev
    curr_rev = start_rev
    revs = []
    filerev = repo.file(path).count() - 1
    while filerev >= 0:
        fctx = repo.filectx(path, fileid=filerev)

        # Compute revs and next_revs.
        if filerev not in revs:
            revs.append(filerev)
        rev_index = revs.index(filerev)
        next_revs = revs[:]

        # Add parents to next_revs.
        parents = [f.filerev() for f in fctx.parents() if f.path() == path]
        parents_to_add = []
        for parent in parents:
            if parent not in next_revs:
                parents_to_add.append(parent)
        parents_to_add.sort()
        next_revs[rev_index:rev_index + 1] = parents_to_add

        edges = []
        for parent in parents:
            edges.append((rev_index, next_revs.index(parent)))

        changerev = fctx.linkrev()
        if changerev <= start_rev:
            node = repo.changelog.node(changerev)
            n_columns_diff = len(next_revs) - len(revs)
            yield (changerev, node, rev_index, edges, len(revs), n_columns_diff)
        if changerev <= stop_rev:
            break
        revs = next_revs
        filerev -= 1

def get_rev_parents(repo, rev):
    return [x for x in repo.changelog.parentrevs(rev) if x != nullrev]

def fix_long_right_edges(edges):
    for (i, (start, end)) in enumerate(edges):
        if end > start:
            edges[i] = (start, end + 1)

def draw_edges(edges, nodeline, interline):
    for (start, end) in edges:
        if start == end + 1:
            interline[2 * end + 1] = "/"
        elif start == end - 1:
            interline[2 * start + 1] = "\\"
        elif start == end:
            interline[2 * start] = "|"
        else:
            nodeline[2 * end] = "+"
            if start > end:
                (start, end) = (end,start)
            for i in range(2 * start + 1, 2 * end):
                if nodeline[i] != "+":
                    nodeline[i] = "-"

def format_line(line, level, logstr):
    text = "%-*s %s" % (2 * level, "".join(line), logstr)
    return "%s\n" % text.rstrip()

def get_nodeline_edges_tail(
        node_index, p_node_index, n_columns, n_columns_diff, p_diff, fix_tail):
    if fix_tail and n_columns_diff == p_diff and n_columns_diff != 0:
        # Still going in the same non-vertical direction.
        if n_columns_diff == -1:
            start = max(node_index + 1, p_node_index)
            tail = ["|", " "] * (start - node_index - 1)
            tail.extend(["/", " "] * (n_columns - start))
            return tail
        else:
            return ["\\", " "] * (n_columns - node_index - 1)
    else:
        return ["|", " "] * (n_columns - node_index - 1)

def get_padding_line(ni, n_columns, edges):
    line = []
    line.extend(["|", " "] * ni)
    if (ni, ni - 1) in edges or (ni, ni) in edges:
        # (ni, ni - 1)      (ni, ni)
        # | | | |           | | | |
        # +---o |           | o---+
        # | | c |           | c | |
        # | |/ /            | |/ /
        # | | |             | | |
        c = "|"
    else:
        c = " "
    line.extend([c, " "])
    line.extend(["|", " "] * (n_columns - ni - 1))
    return line

def get_limit(limit_opt):
    if limit_opt:
        try:
            limit = int(limit_opt)
        except ValueError:
            raise Abort(_("limit must be a positive integer"))
        if limit <= 0:
            raise Abort(_("limit must be positive"))
    else:
        limit = sys.maxint
    return limit

def get_revs(repo, rev_opt):
    if rev_opt:
        revs = revrange(repo, rev_opt)
        return (max(revs), min(revs))
    else:
        return (repo.changelog.count() - 1, 0)

def graphlog(ui, repo, path=None, **opts):
    """show revision history alongside an ASCII revision graph

    Print a revision history alongside a revision graph drawn with
    ASCII characters.

    Nodes printed as an @ character are parents of the working
    directory.
    """

    limit = get_limit(opts["limit"])
    (start_rev, stop_rev) = get_revs(repo, opts["rev"])
    stop_rev = max(stop_rev, start_rev - limit + 1)
    if start_rev == nullrev:
        return
    cs_printer = show_changeset(ui, repo, opts)
    if path:
        cpath = canonpath(repo.root, os.getcwd(), path)
        grapher = filelog_grapher(repo, cpath, start_rev, stop_rev)
    else:
        grapher = revision_grapher(repo, start_rev, stop_rev)
    repo_parents = repo.dirstate.parents()
    prev_n_columns_diff = 0
    prev_node_index = 0

    for (rev, node, node_index, edges, n_columns, n_columns_diff) in grapher:
        # log_strings is the list of all log strings to draw alongside
        # the graph.
        ui.pushbuffer()
        cs_printer.show(rev, node)
        log_strings = ui.popbuffer().split("\n")[:-1]

        if n_columns_diff == -1:
            # Transform
            #
            #     | | |        | | |
            #     o | |  into  o---+
            #     |X /         |/ /
            #     | |          | |
            fix_long_right_edges(edges)

        # add_padding_line says whether to rewrite
        #
        #     | | | |        | | | |
        #     | o---+  into  | o---+
        #     |  / /         |   | |  # <--- padding line
        #     o | |          |  / /
        #                    o | |
        add_padding_line = (len(log_strings) > 2 and
                            n_columns_diff == -1 and
                            [x for (x, y) in edges if x + 1 < y])

        # fix_nodeline_tail says whether to rewrite
        #
        #     | | o | |        | | o | |
        #     | | |/ /         | | |/ /
        #     | o | |    into  | o / /   # <--- fixed nodeline tail
        #     | |/ /           | |/ /
        #     o | |            o | |
        fix_nodeline_tail = len(log_strings) <= 2 and not add_padding_line

        # nodeline is the line containing the node character (@ or o).
        nodeline = ["|", " "] * node_index
        if node in repo_parents:
            node_ch = "@"
        else:
            node_ch = "o"
        nodeline.extend([node_ch, " "])

        nodeline.extend(
            get_nodeline_edges_tail(
                node_index, prev_node_index, n_columns, n_columns_diff,
                prev_n_columns_diff, fix_nodeline_tail))

        # shift_interline is the line containing the non-vertical
        # edges between this entry and the next.
        shift_interline = ["|", " "] * node_index
        if n_columns_diff == -1:
            n_spaces = 1
            edge_ch = "/"
        elif n_columns_diff == 0:
            n_spaces = 2
            edge_ch = "|"
        else:
            n_spaces = 3
            edge_ch = "\\"
        shift_interline.extend(n_spaces * [" "])
        shift_interline.extend([edge_ch, " "] * (n_columns - node_index - 1))

        # Draw edges from the current node to its parents.
        draw_edges(edges, nodeline, shift_interline)

        # lines is the list of all graph lines to print.
        lines = [nodeline]
        if add_padding_line:
            lines.append(get_padding_line(node_index, n_columns, edges))
        lines.append(shift_interline)

        # Make sure that there are as many graph lines as there are
        # log strings.
        while len(log_strings) < len(lines):
            log_strings.append("")
        if len(lines) < len(log_strings):
            extra_interline = ["|", " "] * (n_columns + n_columns_diff)
            while len(lines) < len(log_strings):
                lines.append(extra_interline)

        # Print lines.
        indentation_level = max(n_columns, n_columns + n_columns_diff)
        for (line, logstr) in zip(lines, log_strings):
            ui.write(format_line(line, indentation_level, logstr))

        # ...and start over.
        prev_node_index = node_index
        prev_n_columns_diff = n_columns_diff

cmdtable = {
    "glog":
        (graphlog,
         [('l', 'limit', '', _('limit number of changes displayed')),
          ('p', 'patch', False, _('show patch')),
          ('r', 'rev', [], _('show the specified revision or range')),
         ] + templateopts,
         _('hg glog [OPTION]... [FILE]')),
}


text:
/**
 * Created by Panayiotis on 03/01/2016.
 */
public class GameUtil {
    //utility class for Game class

    public static Color oppositePlayer(Color color)
    {
        return color == Color.WHITE ? Color.BLACK : Color.WHITE;
    }

    public static boolean blackIsOutOfPawns(Board board) {

        for(int file = 0; file < 8; file++) {
            for(int rank = 0; rank < 8; rank++){
                if(board.getSquare(file, rank).occupiedBy() == Color.BLACK)
                    return false;
            }
        }
        return true;

    }

    public static boolean whiteIsOutOfPawns(Board board) {

        for(int file = 0; file < 8; file++) {
            for(int rank = 0; rank < 8; rank++){
                if(board.getSquare(file, rank).occupiedBy() == Color.WHITE)
                    return false;
            }
        }
        return true;

    }

    public static boolean pawnOnLastRank(Board board, Color playerColor) {

        for(int file = 0; file < 8; file++) {
            if(board.getSquare(file, 0).occupiedBy() == playerColor)
                return true;
            if(board.getSquare(file, 7).occupiedBy() == playerColor)
                return true;
        }
        return false;

    }

    public static boolean stealMate(Board board, Color currentPlayer, Move lastMove) {
        for(int file = 0; file < 8; file++) {
            for(int rank = 0; rank < 8; rank++){
                if(board.getSquare(file, rank).occupiedBy() == currentPlayer) {
                    if(canMove(board, file, rank, lastMove))
                        return false;
                }
            }
        }
        //no possible moves found, checked all pawns
        return true;
    }

    private static boolean canMove(Board board, int file, int rank, Move lastMove) {

        Color pawnColor = board.getSquare(file, rank).occupiedBy();
        if(pawnOnLastRank(board, pawnColor))
            return false;
        if(forwardMove(board, file, rank))
            return true;
        if(captureMove(board, file, rank))
            return true;
        if(enPassantCaptureMove(board, file, rank, lastMove))
            return true;

        return false;
    }

    private static boolean forwardMove(Board board, int file, int rank) {
        Color pawnColor = board.getSquare(file, rank).occupiedBy();
        int direction = getDirectionOfPawn(pawnColor);
        if(board.getSquare(file, rank + direction).occupiedBy() == Color.NONE)
            return true;
        return false;
    }

    private static boolean captureMove(Board board, int file, int rank) {
        Color pawnColor = board.getSquare(file, rank).occupiedBy();
        int direction = getDirectionOfPawn(pawnColor);

        if(file > 0 && board.getSquare(file - 1, rank + direction).occupiedBy() == oppositePlayer(pawnColor))
            return true;

        if(file < 7 && board.getSquare(file + 1, rank + direction).occupiedBy() == oppositePlayer(pawnColor))
            return true;

        return false;
    }

    private static boolean enPassantCaptureMove(Board board, int file, int rank, Move lastMove) {

       /* assert(lastMove == null):
                "lastMove shouldn't be null";*/

        Color pawnColor = board.getSquare(file, rank).occupiedBy();
        int direction = getDirectionOfPawn(pawnColor);

        if(!lastMove.isEnPassantCapture())
            return false;

        int enPassantPawnX = lastMove.getTo().getX();
        int enPassantPawnY = lastMove.getTo().getY();
        int toMovePawnX = board.getSquare(file, rank).getX();
        int toMovePawnY = board.getSquare(file, rank).getY();

        if(enPassantPawnY == toMovePawnY &&
                (enPassantPawnX == toMovePawnX + 1 || enPassantPawnX == toMovePawnX - 1))
            return true;

        return false;
    }

    public static boolean haveMovedPawn(int rank, Color playerColor) {
        switch(playerColor){
            case WHITE: return rank != 1;
            case BLACK: return rank != 6;
            default: assert(false): "Player should be BLACK/WHITE"; return false;
        }
    }

    public static int getDirectionOfPawn(Color pawn) {
        switch(pawn) {
            case WHITE: return 1;
            case BLACK: return -1;
            default: assert(false): "Pawn should be WHITE/BLACK"; return 0;
        }
    }

    public static boolean moveIsEnPassant(Move move) {
        Square from = move.getFrom();
        Square to = move.getTo();

        return (Math.abs(from.getY() - to.getY()) == 2);
    }

    public static boolean validMove(Square from, Square to, boolean isCapture,
                                    boolean isEnPassantCapture, Board board, Color player,
                                    Move lastMove) {

        if(from.occupiedBy() != player || to.occupiedBy() == player)
            return false;

        int direction = getDirectionOfPawn(player); // +1 for White, -1 for Black
        if(isEnPassantCapture) {

            int fileDifference = to.getX() - from.getX();
            if(to.getY() - direction < 0) return false;
            Square lastFrom = lastMove.getFrom();
            Square lastTo = lastMove.getTo();

            Square enPassantPawn = board.getSquare(to.getX(), to.getY() - direction);
            if(to.occupiedBy() == Color.NONE &&
                    (to.getY() == from.getY() + direction) &&
                    (fileDifference == 1 || fileDifference == -1) &&
                    (enPassantPawn.occupiedBy() == oppositePlayer(player)) &&
                    (Math.abs(lastTo.getY() - lastFrom.getY()) == 2) &&
                    (lastTo.getX() == enPassantPawn.getX()) &&
                    (lastTo.getY() == enPassantPawn.getY()))//that was the pawn moved
                return true;
            else
                return false;

        } else if(isCapture) {
            if(to.occupiedBy() == oppositePlayer(player) &&
                    (from.getX() + 1 == to.getX() || from.getX() - 1 == to.getX()) &&
                    (from.getY() + direction == to.getY()))
                return true;
            return false;
        } else {
            if((from.getY() == to.getY() - direction || from.getY() == to.getY() - 2 * direction) &&
                    (from.getX() == to.getX()) && to.occupiedBy() == Color.NONE &&
                    (board.getSquare(from.getX(), from.getY() + direction).occupiedBy() == Color.NONE))
                return true;
            return false;
        }
    }

    public static Move stringToMove(String san, Move lastMove, int nextMoveIndex, Board board, Color player) {

        if(san.length() != 5) //weak check, if notation is changed later must change too
            return null;

        String squareString;
        squareString = san.substring(0, 2);
        Square from = notationToSquare(squareString, board);
        squareString = san.substring(3, 5);
        Square to = notationToSquare(squareString, board);
        boolean isCapture = san.contains("x");
        boolean isEnPassantCapture = isCapture && (to.occupiedBy() == Color.NONE);

        //check if it's valid

        //extra care, in this case lastMove is null
        if(nextMoveIndex == 0) {
            if(from.occupiedBy() == player && to.getX() == from.getX()
                    && (to.getY() == from.getY() + 1 || to.getY() == from.getY() + 2)) {
                Move move = new Move(from, to, isCapture, isEnPassantCapture);
                return move;
            }
            //invalid move
            System.out.println("Invalid first move");
            return null;
        }

        //normal move, able to use lastMove
        if(validMove(from, to, isCapture, isEnPassantCapture, board, player, lastMove)) {
            Move move = new Move(from, to, isCapture, isEnPassantCapture);
            return move;
        }
        System.out.println("Invalid normal move!");
        return null;
    }

    private static Square notationToSquare(String squareString, Board board) {
        assert(squareString.length() == 2):
                "squareString should only have 2 characters";
        int file = squareString.charAt(0) - 'a';
        int rank = squareString.charAt(1) - '1';
        //reference to the board square
        Square square = board.getSquare(file, rank);
        square.setOccupier(board.getSquare(file, rank).occupiedBy());
        return square;
    }

    public static String gameResults(Color winner){
        switch(winner) {
            case WHITE: return "WHITE HAS WON!!";
            case BLACK: return "BLACK HAS WON!!";
            default:  return "STEALMATE!!";
        }
    }

    public static void printValidMoves(Move[] moves) {
        for(int i = 0; i < moves.length; i++) {
            //assert(moves[i] == null): "move shouldn't be null";
            if(moves[i] != null)
            System.out.print(" " + moveToString(moves[i]));
        }
        System.out.println();
    }

    public static String moveToString(Move move) {
        Square from = move.getFrom();
        Square to = move.getTo();
        String s;
        char moveType = move.isCapture() ? 'x' : '-';
        s = "" + (char)(from.getX() + 'a') + (char)(from.getY() + '1')
               + moveType + (char)(to.getX() + 'a') + (char)(to.getY() + '1');
        return s;
    }

}


text:
package org.xbib.catalog.entities.mab;

import org.xbib.catalog.entities.CatalogEntity;

import java.util.Map;

/**
 *
 */
public class Comment extends CatalogEntity {

    public Comment(Map<String, Object> params) {
        super(params);
    }
}


text:
// Copyright (c) 2012 Ecma International.  All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.

/*---
es5id: 15.2.3.5-4-87
description: >
    Object.create - 'enumerable' property of one property in
    'Properties' is a Boolean object (8.10.5 step 3.b)
---*/

        var accessed = false;

        var newObj = Object.create({}, {
            prop: {
                enumerable: new Boolean(true)
            }
        });
        for (var property in newObj) {
            if (property === "prop") {
                accessed = true;
            }
        }

assert(accessed, 'accessed !== true');


text:
int main()
{
  test_converting_assignment<int>();

  return boost::report_errors();
}


text:
Titanium.UI.setBackgroundColor('#000');

Ti.include('parse_json.js');
Ti.include('geonew.js');
Ti.include('config.js');

Titanium.App.addEventListener('pause', function(e) {
	Ti.App.fireEvent('closebc', {
		butclose : 't'
	});
});
//--------------------------------------------------------------------------------
var wMain = Ti.UI.createWindow({
	barImage: 'images/top_bar_free.jpg',
	//backgroundImage: 'images/back_pattern2.jpg',
});

//wMain.cityid = '1';

// declare global vars
var tabGroupWindows = {
	navtop: [],
	navbottom: []
};

var tabgroup = new Class_Tabgroup({
	tabgroup: {
		width: sc(480),
		top: sc(50),
		bottom: sc(0),

	},
	bar: {
		width: sc(480),
		height: sc(70),
		bottom: sc(0),
		backgroundImage: 'images/tabbar-new-back.jpg',
		//backgroundColor:'#344231',
		opacity: 0.7
	},
	content: {
		width: sc(480),
		//top: sc(63),
		bottom: sc(70)
	}
}, null, 'category', 'navbottom');

tabgroup.addTab({
	o: {
		name: 'category',
		on: 'images/home_press.png',
		off: 'images/home.png'
	},
	left: sc(0),
	top: sc(0),
	width: sc(120),
	height: sc(70),
	canScale: true,
	enableZoomControls: false
});
tabgroup.addTab({
	o: {
		name: 'map',
		off: 'images/map.png',
		on: 'images/map_press.png',
	},
	left: sc(120),
	top: sc(0),
	width: sc(120),
	height: sc(70),
	canScale: true,
	enableZoomControls: false,
	//zindex: 15
});
tabgroup.addTab({
	o: {
		name: 'purchases',
		off: 'images/study.png',
		on: 'images/study_press.png'
	},
	left: sc(240),
	top: sc(0),
	width: sc(120),
	height: sc(70),
	canScale: true,
	enableZoomControls: false
});
tabgroup.addTab({
	o: {
		name: 'settings',
		off: 'images/settings.png',
		on: 'images/settings_press.png'
	},
	right: sc(0),
	top: sc(0),
	width: sc(120),
	height: sc(70),
	canScale: true,
	enableZoomControls: false,
	//opacity: 0.7
});
tabgroup.create();
wMain.add(tabgroup.tabgroup);

Ti.App.addEventListener('setactt', function(event) {
	tabgroup.setActive('settings');
});
Ti.App.addEventListener('choseb', function(event) {
	tabgroup.setActive('category');
});
function openApp() {

	wMain.open({
		transition:Titanium.UI.iPhone.AnimationStyle.FLIP_FROM_LEFT
	});
	tabgroup.setActive('category');
}

openApp();
// tabgroup.closeOtherTabgroup = function() {
// Ti.App.fireEvent('removeTabGroupWindow', {
// tabgroup: 'navtop',
// });
// };
//---------------------------------------------------------------------------------


text:
package net.sf.esfinge.metadata.annotation.validator;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import net.sf.esfinge.metadata.validate.SiteValidoAnnotationValidator;

@ToValidateProperty(validationClass = SiteValidoAnnotationValidator.class)
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface SiteValido {
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    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:orientation="vertical"
    android:layout_margin="10dp">

<EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Name" />

    <TextView

        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="SCHEDULE"
        android:textSize="15dp"
        android:layout_marginTop="10dp"/>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="3"
        android:orientation="horizontal">

        <TextView
            android:layout_gravity="center"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1.5"
            android:text="MON"
            android:textSize="20dp"
            android:textStyle="bold" />

        <Button
            android:layout_gravity="center"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1.5"
            android:text="Add Time" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="3"
        android:orientation="horizontal"
        android:layout_gravity="center">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1.5"
            android:text="TUE  "
            android:layout_gravity="center"
            android:textSize="20dp"
            android:textStyle="bold" />

        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_weight="1.5"
            android:text="Add Time" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="3"
        android:orientation="horizontal">

        <TextView

            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1.5"
            android:text="WED "
            android:textSize="20dp"
            android:textStyle="bold"
            android:layout_gravity="center" />

        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_weight="1.5"
            android:text="Add Time" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="3"
        android:orientation="horizontal">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1.5"
            android:text="THU "
            android:textSize="20dp"
            android:textStyle="bold"
            android:layout_gravity="center" />

        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1.5"
            android:text="Add Time"
            android:layout_gravity="center" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="3"
        android:orientation="horizontal">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1.5"
            android:text="FRI"
            android:textSize="20dp"
            android:textStyle="bold"
            android:layout_gravity="center" />

        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1.5"
            android:text="Add Time"
            android:layout_gravity="center" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="3"
        android:orientation="horizontal">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1.5"
            android:text="SAT "
            android:textSize="20dp"
            android:textStyle="bold"
            android:layout_gravity="center" />

        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1.5"
            android:text="Add Time"
            android:layout_gravity="center" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="3"
        android:orientation="horizontal"
        android:layout_gravity="center">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1.5"
            android:text="SUN "
            android:layout_gravity="center"
            android:textSize="20dp"
            android:textStyle="bold" />

        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1.5"
            android:text="Add Time"
            android:layout_gravity="center" />
    </LinearLayout>

    <Button
        android:layout_marginTop="10dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="SUBMIT"
        android:background="@color/colorAccent" />

</LinearLayout>


text:
// **********
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
// **********

#ifndef SRC_PACK_WALKER_H_
#define SRC_PACK_WALKER_H_

#include "util/function.h"
#include "util/noexcept.h"
#include "util/string-view.h"
#include "util/vector.h"

// Recursively walk the file system under the following paths, calling op on
// each regular file (non-directory) found. Uses one thread per logical core, so
// op can be called multiple times in parallel.
void walk(Vector<StringView> paths, Function<void(StringView)> op) noexcept;

#endif  // SRC_PACK_WALKER_H_


text:
//
//  NSDICT.h
//  Ring
//
//  Created by Nguyen Hoang Nam on 25/5/16.
//  Copyright © 2016 Medpats Global Pte. Ltd. All rights reserved.
//

#ifndef NSDICT_h
#define NSDICT_h

#define NSDICT(firstKey, ...) NSDictionaryWithKeysAndValues(firstKey, __VA_ARGS__)
static __attribute__ ((sentinel)) NSDictionary * NSDictionaryWithKeysAndValues(id firstKey, ...) {
   va_list kvl;
   va_start(kvl, firstKey);

   size_t dyn_capacity;
   size_t dyn_count;
   __unsafe_unretained id * dyn_keys;
   __unsafe_unretained id * dyn_values;
   id key, value;

   // Do up to 16 using static allocation
   {
      NSUInteger static_capacity = 16;
      __unsafe_unretained id keys[static_capacity];
      __unsafe_unretained id values[static_capacity];
      NSUInteger count = 0;

      key = firstKey;
      value = va_arg(kvl, id);

      do {
         if (value) {
            keys[count] = key;
            values[count] = value;
            count++;
         }

         key = va_arg(kvl, id);
         if (!key) {
            va_end(kvl);
            return [NSDictionary dictionaryWithObjects:values forKeys:keys count:count];
         }
         value = va_arg(kvl, id);

         if (count == static_capacity) {
            dyn_capacity = static_capacity * 2;
            dyn_count  = static_capacity;
            dyn_keys   = (__unsafe_unretained id *)malloc(dyn_capacity * sizeof(id));
            dyn_values = (__unsafe_unretained id *)malloc(dyn_capacity * sizeof(id));

            memcpy(dyn_keys, keys, static_capacity * sizeof(id));
            memcpy(dyn_values, values, static_capacity * sizeof(id));
            break;
         }

      } while (1);
   }

   // For > 16 entries
   do {
      if (value) {
         dyn_keys[dyn_count] = key;
         dyn_values[dyn_count] = value;
         dyn_count++;
         if (dyn_count == dyn_capacity) {
            dyn_capacity += 16;
            dyn_keys = (__unsafe_unretained id *)realloc(dyn_keys, dyn_capacity * sizeof(id));
            dyn_values = (__unsafe_unretained id *)realloc(dyn_values, dyn_capacity * sizeof(id));
         }
      }

      key = va_arg(kvl, id);
      if (!key) break;
      value = va_arg(kvl, id);
   } while (1);

   va_end(kvl);

   NSDictionary * dict = [NSDictionary dictionaryWithObjects:dyn_values forKeys:dyn_keys count:dyn_count];
   free(dyn_keys);
   free(dyn_values);
   return dict;
}
#endif /* NSDICT_h */


text:
from blog.models import Tag, Blog, BlogTag
from rest_framework import serializers

class TagSerializer(serializers.HyperlinkedModelSerializer):

    class Meta:
        model = Tag
        fields = ('id', 'name', 'slug')

class BlogSerializer(serializers.HyperlinkedModelSerializer):
    tags = TagSerializer(read_only=False, many=True)
    author = serializers.ReadOnlyField(source='author.username')

    class Meta:
        model = Blog
        fields = ('id', 'title', 'published', 'body', 'tags', 'slug', 'author','views', 'created_at')

class BlogTagSerializer(serializers.HyperlinkedModelSerializer):
    tag = TagSerializer(read_only=True, many=False)
    blog = BlogSerializer(read_only=True, many=False)

    class Meta:
        model = BlogTag
        fields = ('id', 'tag', 'blog')