text:
package org.apache.expreval.expr;

import org.apache.expreval.client.InternalErrorException;
import org.apache.expreval.client.NullColumnValueException;
import org.apache.expreval.client.ResultMissingColumnException;
import org.apache.expreval.expr.literal.DoubleLiteral;
import org.apache.expreval.expr.literal.FloatLiteral;
import org.apache.expreval.expr.literal.IntegerLiteral;
import org.apache.expreval.expr.literal.LongLiteral;
import org.apache.expreval.expr.literal.ShortLiteral;
import org.apache.expreval.expr.node.BooleanValue;
import org.apache.expreval.expr.node.DateValue;
import org.apache.expreval.expr.node.GenericValue;
import org.apache.expreval.expr.node.NumberValue;
import org.apache.expreval.expr.node.ObjectValue;
import org.apache.expreval.expr.node.StringValue;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.filter.CompareFilter;
import org.apache.hadoop.hbase.filter.Filter;
import org.apache.hadoop.hbase.filter.WritableByteArrayComparable;
import org.apache.hadoop.hbase.hbql.client.HBqlException;
import org.apache.hadoop.hbase.hbql.filter.SingleColumnValueFilter;
import org.apache.hadoop.hbase.hbql.impl.AggregateValue;
import org.apache.hadoop.hbase.hbql.impl.InvalidServerFilterException;
import org.apache.hadoop.hbase.hbql.impl.InvalidTypeException;
import org.apache.hadoop.hbase.hbql.mapping.ColumnAttrib;
import org.apache.hadoop.hbase.hbql.util.Lists;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

public abstract class GenericExpression implements GenericValue {

    // These are used to cache type of the args for exprs with numberic args
    private Class<? extends GenericValue> highestRankingNumericArgFoundInValidate = NumberValue.class;
    private Class                         rankingClass                            = null;
    private boolean                       useDecimal                              = false;
    private boolean                       useByte                                 = false;
    private boolean                       useShort                                = false;
    private boolean                       useInteger                              = false;
    private boolean                       useLong                                 = false;
    private boolean                       useFloat                                = false;
    private boolean                       useDouble                               = false;

    private final ExpressionType type;
    private final List<GenericValue> genericValueList = Lists.newArrayList();
    private final AtomicBoolean      allArgsOptimized = new AtomicBoolean(false);

    private MultipleExpressionContext expressionContext = null;

    private Class getRankingClass() {
        return this.rankingClass;
    }

    protected GenericExpression(final ExpressionType type, final GenericValue... exprs) {
        this(type, Arrays.asList(exprs));
    }

    protected GenericExpression(final ExpressionType type, final List<GenericValue> genericValueList) {
        this.type = type;
        if (genericValueList != null)
            this.getGenericValueList().addAll(genericValueList);
    }

    protected GenericExpression(final ExpressionType type,
                                final GenericValue expr,
                                final List<GenericValue> genericValueList) {
        this.type = type;
        this.getGenericValueList().add(expr);
        if (genericValueList != null)
            this.getGenericValueList().addAll(genericValueList);
    }

    protected FunctionTypeSignature getTypeSignature() {
        return this.type.getTypeSignature();
    }

    public List<GenericValue> getGenericValueList() {
        return this.genericValueList;
    }

    protected List<GenericValue> getSubArgs(final int i) {
        return this.getGenericValueList().subList(i, this.getGenericValueList().size());
    }

    private Class<? extends GenericValue> getHighestRankingNumericArgFoundInValidate() {
        return this.highestRankingNumericArgFoundInValidate;
    }

    // These require getHighestRankingNumericArg() be called first to set value
    protected boolean useDecimal() {
        return this.useDecimal;
    }

    protected Number getValueWithCast(final long result) throws HBqlException {
        if (this.useByte)
            return (byte)result;
        else if (this.useShort)
            return (short)result;
        else if (this.useInteger)
            return (int)result;
        else if (this.useLong)
            return result;
        else
            throw new HBqlException("Invalid class: " + this.getRankingClass().getName());
    }

    protected Number getValueWithCast(final double result) throws HBqlException {
        if (this.useFloat)
            return (float)result;
        else if (this.useDouble)
            return result;
        else
            throw new HBqlException("Invalid class: " + this.getRankingClass().getName());
    }

    protected Class validateNumericArgTypes(final Object... objs) {

        if (this.getRankingClass() == null) {

            // If we do not already know the specific types, then look at the class of both args
            if (this.getHighestRankingNumericArgFoundInValidate() == NumberValue.class)
                this.rankingClass = NumericType.getHighestRankingNumericArg(objs);
            else
                this.rankingClass = this.getHighestRankingNumericArgFoundInValidate();

            this.useDecimal = NumericType.useDecimalNumericArgs(this.getRankingClass());

            this.useByte = NumericType.isAByte(this.getRankingClass());
            this.useShort = NumericType.isAShort(this.getRankingClass());
            this.useInteger = NumericType.isAnInteger(this.getRankingClass());
            this.useLong = NumericType.isALong(this.getRankingClass());
            this.useFloat = NumericType.isAFloat(this.getRankingClass());
            this.useDouble = NumericType.isADouble(this.getRankingClass());
        }

        return this.getRankingClass();
    }

    protected Class<? extends GenericValue> validateNumericTypes() throws HBqlException {

        if (this.getGenericValueList().size() != this.getTypeSignature().getArgCount())
            throw new InvalidTypeException("Incorrect number of arguments in " + this.asString());

        // Return the type of the highest ranking numeric arg
        int highestRank = -1;
        for (int i = 0; i < this.getTypeSignature().getArgCount(); i++) {

            final Class<? extends GenericValue> clazz = this.getExprArg(i).validateTypes(this, false);
            this.validateParentClass(this.getTypeSignature().getArg(i), clazz);

            final int rank = NumericType.getTypeRanking(clazz);
            if (rank > highestRank) {
                highestRank = rank;
                this.highestRankingNumericArgFoundInValidate = clazz;
            }
        }

        return this.getHighestRankingNumericArgFoundInValidate();
    }

    public boolean isAConstant() {

        if (this.getGenericValueList().size() == 0)
            return false;

        for (final GenericValue val : this.getGenericValueList())
            if (!val.isAConstant())
                return false;

        return true;
    }

    public boolean isDefaultKeyword() {
        return false;
    }

    public boolean isAnAggregateValue() {
        return false;
    }

    public void initAggregateValue(final AggregateValue aggregateValue) throws HBqlException {
        throw new InternalErrorException("Not applicable");
    }

    public void applyResultToAggregateValue(final AggregateValue aggregateValue, final Result result) throws HBqlException, ResultMissingColumnException, NullColumnValueException {
        throw new InternalErrorException("Not applicable");
    }

    public boolean hasAColumnReference() {
        for (final GenericValue val : this.getGenericValueList())
            if (val.hasAColumnReference())
                return true;
        return false;
    }

    public boolean isAColumnReference() {
        return false;
    }

    public void reset() {
        for (final GenericValue val : this.getGenericValueList())
            val.reset();
    }

    public void setExpressionContext(final MultipleExpressionContext expressionContext) throws HBqlException {

        this.expressionContext = expressionContext;

        for (final GenericValue val : this.getGenericValueList())
            val.setExpressionContext(expressionContext);
    }

    protected MultipleExpressionContext getExpressionContext() {
        return this.expressionContext;
    }

    private AtomicBoolean getAllArgsOptimized() {
        return this.allArgsOptimized;
    }

    protected void optimizeAllArgs() throws HBqlException {
        if (!this.getAllArgsOptimized().get())
            synchronized (this) {
                if (!this.getAllArgsOptimized().get()) {
                    for (int i = 0; i < this.getGenericValueList().size(); i++)
                        this.setArg(i, this.getExprArg(i).getOptimizedValue());
                    this.getAllArgsOptimized().set(true);
                }
            }
    }

    protected Filter newSingleColumnValueFilter(final ColumnAttrib attrib,
                                                final CompareFilter.CompareOp compareOp,
                                                final WritableByteArrayComparable comparator) throws HBqlException {

        // Bail if expression uses a row key.
        if (attrib.isAKeyAttrib())
            throw new InvalidServerFilterException("Cannot use a key attribute");

        final SingleColumnValueFilter filter = new SingleColumnValueFilter(attrib.getFamilyNameAsBytes(),
                                                                           attrib.getColumnNameAsBytes(),
                                                                           compareOp,
                                                                           comparator);
        filter.setFilterIfMissing(true);
        return filter;
    }

    protected Object getConstantValue(final int pos) throws HBqlException {
        try {
            return this.getExprArg(pos).getValue(null, null);
        }
        catch (ResultMissingColumnException e) {
            throw new InternalErrorException("Missing column: " + e.getMessage());
        }
        catch (NullColumnValueException e) {
            throw new InternalErrorException("Null value: " + e.getMessage());
        }
    }

    public GenericValue getExprArg(final int i) {
        return this.getGenericValueList().get(i);
    }

    public void setArg(final int i, final GenericValue val) {
        this.getGenericValueList().set(i, val);
    }

    public Class<? extends GenericValue> validateTypes(final GenericValue parentExpr,
                                                       final boolean allowCollections) throws HBqlException {

        if (this.getGenericValueList().size() != this.getTypeSignature().getArgCount())
            throw new InvalidTypeException("Incorrect number of arguments in " + this.asString());

        final FunctionTypeSignature typeSignature = this.getTypeSignature();

        for (int i = 0; i < typeSignature.getArgCount(); i++)
            this.validateParentClass(typeSignature.getArg(i), this.getExprArg(i).validateTypes(this, false));

        return typeSignature.getReturnType();
    }

    public GenericValue getOptimizedValue() throws HBqlException {

        this.optimizeAllArgs();

        if (!this.isAConstant())
            return this;

        try {
            final Object obj = this.getValue(null, null);

            if (this.getTypeSignature().getReturnType() == BooleanValue.class
                || this.getTypeSignature().getReturnType() == StringValue.class
                || this.getTypeSignature().getReturnType() == DateValue.class)
                return this.getTypeSignature().newLiteral(obj);

            if (TypeSupport.isParentClass(NumberValue.class, this.getTypeSignature().getReturnType())) {

                if (obj instanceof Short)
                    return new ShortLiteral((Short)obj);

                if (obj instanceof Integer)
                    return new IntegerLiteral((Integer)obj);

                if (obj instanceof Long)
                    return new LongLiteral((Long)obj);

                if (obj instanceof Float)
                    return new FloatLiteral((Float)obj);

                if (obj instanceof Double)
                    return new DoubleLiteral((Double)obj);
            }
            throw new InternalErrorException(this.getTypeSignature().getReturnType().getSimpleName());
        }
        catch (ResultMissingColumnException e) {
            throw new InternalErrorException("Missing column: " + e.getMessage());
        }
        catch (NullColumnValueException e) {
            throw new InternalErrorException("Null value: " + e.getMessage());
        }
    }

    public String asString() {

        final StringBuilder sbuf = new StringBuilder("(");

        boolean first = true;
        for (final GenericValue val : this.getGenericValueList()) {
            if (!first)
                sbuf.append(", ");
            sbuf.append(val.asString());
            first = false;
        }

        sbuf.append(")");

        return sbuf.toString();
    }

    public void validateParentClass(final Class<? extends GenericValue> parentClass,
                                    final Class<? extends GenericValue>... childrenClasses) throws InvalidTypeException {

        final List<Class<? extends GenericValue>> classList = Lists.newArrayList();

        for (final Class<? extends GenericValue> childClass : childrenClasses) {

            if (childClass != null) {
                if (TypeSupport.isParentClass(NumberValue.class, parentClass)) {
                    if (!TypeSupport.isParentClass(NumberValue.class, childClass)) {
                        classList.add(childClass);
                    }
                    else {
                        if (!NumericType.isAssignable(parentClass, childClass))
                            classList.add(childClass);
                    }
                }
                else {
                    if (!parentClass.isAssignableFrom(childClass))
                        classList.add(childClass);
                }
            }
        }

        if (classList.size() > 0) {
            final StringBuilder sbuf = new StringBuilder("Expecting type " + parentClass.getSimpleName()
                                                         + " but encountered type"
                                                         + ((classList.size() > 1) ? "s" : "") + " ");
            boolean first = true;
            for (final Class clazz : classList) {
                if (!first)
                    sbuf.append(", ");
                sbuf.append(clazz.getSimpleName());
                first = false;
            }

            sbuf.append(" in expression: " + this.asString());

            throw new InvalidTypeException(sbuf.toString());
        }
    }

    public String getInvalidTypeMsg(final Class<? extends GenericValue>... classes) {

        final List<Class> classList = Lists.newArrayList();

        for (final Class clazz : classes)
            if (clazz != null)
                classList.add(clazz);

        final StringBuilder sbuf = new StringBuilder("Invalid type");
        sbuf.append(((classList.size() > 1) ? "s " : " "));

        boolean first = true;
        for (final Class<? extends GenericValue> clazz : classes) {
            if (!first)
                sbuf.append(", ");
            sbuf.append(clazz.getSimpleName());
            first = false;
        }
        sbuf.append(" in expression " + this.asString());

        return sbuf.toString();
    }

    final List<Class<? extends GenericValue>> types = Arrays.asList(StringValue.class,
                                                                    NumberValue.class,
                                                                    DateValue.class,
                                                                    BooleanValue.class,
                                                                    ObjectValue.class);

    protected Class<? extends GenericValue> getGenericValueClass(final Class<? extends GenericValue> clazz) throws InvalidTypeException {

        for (final Class<? extends GenericValue> type : types)
            if (TypeSupport.isParentClass(type, clazz))
                return type;

        throw new InvalidTypeException(this.getInvalidTypeMsg(clazz));
    }

    public Filter getFilter() throws HBqlException {
        throw new InvalidServerFilterException();
    }
}


text:
[![Build Status](https://travis-ci.org/hexojs/hexo-deployer-git.svg?branch=master)](https://travis-ci.org/hexojs/hexo-deployer-git)  [![NPM version](https://badge.fury.io/js/hexo-deployer-git.svg)](http://badge.fury.io/js/hexo-deployer-git) [![Coverage Status](https://img.shields.io/coveralls/hexojs/hexo-deployer-git.svg)](https://coveralls.io/r/hexojs/hexo-deployer-git?branch=master) [![Build status](https://ci.appveyor.com/api/projects/status/liqy4nib33ht70so/branch/master?svg=true)](https://ci.appveyor.com/project/tommy351/hexo-deployer-git/branch/master)

Git deployer plugin for [Hexo].

## Notice: Fatal HttpRequestException Error on pushing to GitHub?
Update [Git for Windows](https://github.com/git-for-windows/git/releases) to the latest version. ([Details](https://github.com/Microsoft/Git-Credential-Manager-for-Windows#notice-experiencing-github-pushfetch-problems))

## Installation

``` bash
$ npm install hexo-deployer-git --save
```

## Options

You can configure this plugin in `_config.yml`.

``` yaml
# You can use this:
deploy:
  type: git
  repo: <repository url>
  branch: [branch]
  message: [message]
  name: [git user]
  email: [git email]
  extend_dirs: [extend directory]
  ignore_hidden: false # default is true
  ignore_pattern: regexp  # whatever file that matches the regexp will be ignored when deploying

# or this:
deploy:
  type: git
  message: [message]
  repo:
    github: <repository url>,[branch]
    coding: <repository url>,[branch]
  extend_dirs:
    - [extend directory]
    - [another extend directory]
  ignore_hidden:
    public: false
    [extend directory]: true
    [another extend directory]: false
  ignore_pattern:
    [folder]: regexp  # or you could specify the ignore_pattern under a certain directory
```

- **repo**: Repository URL
- **branch**: Git branch to deploy the static site to
- **message**: Commit message. The default commit message is `Site updated: {{ now('YYYY-MM-DD HH:mm:ss') }}`.
- **name** and **email**: User info for committing the change, overrides global config. This info is independent of git login.
- **extend_dirs**: Add some extensions directory to publish. e.g `demo`, `examples`
- **ignore_hidden** (Boolean|Object): whether ignore hidden files to publish. the github requires the `.nojekyll` in root.
  * Boolean: for all dirs.
  * Object: for public dir and extend dir:
    * `public`: the public dir defaults.
    * [extend directory]
- **ignore_pattern** (Object|RegExp): Choose the ignore pattern when deploying
  * RegExp: for all dirs.
  * Object: specify the ignore pattern under certain directory. For example, if you want to push the source files and generated files at the same time to two different branches. The option should be like
  ```yaml
  # _config.yaml
  deploy:
    - type: git
      repo: git@github.com:<username>/<username>.github.io.git
      branch: master
    - type: git
      repo: git@github.com:<username>/<username>.github.io.git
      branch: src
      extend_dirs: /
      ignore_hidden: false
      ignore_pattern:
          public: .
  ```

## How it works

`hexo-deployer-git` works by generating the site in `.deploy_git` and *force pushing* to the repo(es) in config.
If `.deploy_git` does not exist, a repo will initialized (`git init`).
Otherwise the curent repo (with its commit history) will be used.

Users can clone the deployed repo to `.deploy_git` to keep the commit history.
```
git clone <gh-pages repo> .deploy_git
```

## Reset

Remove `.deploy_git` folder.

``` bash
$ rm -rf .deploy_git
```

## License

MIT

[Hexo]: https://hexo.io/

redpajama_set_name: RedPajamaGithub


text:
[![License](https://img.shields.io/github/license/hall-lab/svtools.svg)](LICENSE.txt)
[![Build Status](https://travis-ci.org/hall-lab/svtools.svg?branch=master)](https://travis-ci.org/hall-lab/svtools)
[![Coverage Status](https://coveralls.io/repos/github/hall-lab/svtools/badge.svg?branch=master)](https://coveralls.io/github/hall-lab/svtools?branch=master)

[![bioconda-badge](https://img.shields.io/badge/install%20with-bioconda-brightgreen.svg?style=flat)](http://bioconda.github.io)
[![PyPI](https://img.shields.io/pypi/v/svtools.svg)](https://pypi.python.org/pypi/svtools)
[![DOI](https://zenodo.org/badge/16104/hall-lab/svtools.svg)](https://zenodo.org/badge/latestdoi/16104/hall-lab/svtools)

## Summary
`svtools` is a suite of utilities designed to help bioinformaticians construct and explore cohort-level structural variation calls. It is designed to efficiently merge and genotype calls from [`speedseq sv`](https://github.com/hall-lab/speedseq) across thousands to tens of thousands of genomes.

## Table of Contents
1. [Requirements](#requirements)
2. [Installation](#installation)
3. [Obtaining help](#obtaining-help)
4. [Usage](#usage)
5. [Citing `svtools`](#citing-svtools)
6. [Troubleshooting](#troubleshooting)

## Requirements
* A Linux-like environment with bash, awk, and sort
* A working installation of [`cnvnator-multi`](https://github.com/hall-lab/speedseq#cnvnator) (a component of [`speedseq sv`](https://github.com/hall-lab/speedseq))
* [Python2.7](https://www.python.org/)
   * [Numpy](http://www.numpy.org/)
   * [Scipy](https://www.scipy.org/)
   * [Pandas](http://pandas.pydata.org/)
   * [Statsmodels](http://statsmodels.sourceforge.net/)
   * [Pysam](https://github.com/pysam-developers/pysam) (≥0.8.1)

## Installation
We recommend you install using `conda`, but you may also install via `pip`. For more detailed instructions, see our [Installation guide](INSTALL.md).

### Installing via conda
```
conda install -c bioconda svtools
```

### Installing via pip
```
pip install svtools
```

## Obtaining help
Please see the documentation on, or linked to, this page. For additional help or to report a bug, please open an issue in the `svtools` repository: https://github.com/hall-lab/svtools/issues

## Usage
`svtools` consists of subcommands for processing VCF or BEDPE files of structural variants and one accessory script (`create_coordinates`).

```
usage: svtools [-h] [--version] [--support] subcommand ...

Comprehensive utilities to explore structural variation in genomes

optional arguments:
  -h, --help     show this help message and exit
  --version      show program's version number and exit
  --support      information on obtaining support

  subcommand     description
    lsort        sort N LUMPY VCF files into a single file
    lmerge       merge LUMPY calls inside a single file from svtools lsort
    vcfpaste     paste VCFs from multiple samples
    copynumber   add copynumber information using cnvnator-multi
    genotype     compute genotype of structural variants based on breakpoint depth
    afreq        add allele frequency information to a VCF file
    bedpetobed12 convert a BEDPE file to BED12 format for viewing in IGV or the
                 UCSC browser
    bedpetovcf   convert a BEDPE file to VCF
    vcftobedpe   convert a VCF file to a BEDPE file
    vcfsort      sort a VCF file
    bedpesort    sort a BEDPE file
    prune        cluster and prune a BEDPE file by position based on allele
                 frequency
    varlookup    look for variants common between two BEDPE files
    classify     reclassify DEL and DUP based on read depth information
```

## Citing svtools
Until `svtools` is published, please cite using its [DOI](https://zenodo.org/badge/latestdoi/16104/hall-lab/svtools). Note that this link corresponds to the latest version. If you used an earlier version then your DOI may be different and you can find it on [Zenodo](https://zenodo.org/search?ln=en&cc=software&p=svtools&action_search=).

## Troubleshooting
As issues arise and common problems are identified, we will list them here.

Note: For additional information and usage refer to the [Tutorial.md](Tutorial.md) file.


text:
/**
 */
package protolipse.protobuf.impl;

import org.eclipse.emf.ecore.EClass;

import protolipse.protobuf.ProtobufPackage;
import protolipse.protobuf.PublicImport;

/**
 *
 * An implementation of the model object 'Public Import'.
 *
 *
 * @generated
 */
public class PublicImportImpl extends ImportImpl implements PublicImport
{
  /**
   *
   *
   * @generated
   */
  protected PublicImportImpl()
  {
    super();
  }

  /**
   *
   *
   * @generated
   */
  @Override
  protected EClass eStaticClass()
  {
    return ProtobufPackage.Literals.PUBLIC_IMPORT;
  }

} //PublicImportImpl


text:
Games

				Posted on

				by

    	No Games yet, why don't you create one?


text:
requirejs.config({
    // The RequireJS docs advise against configuring paths to node_modules for use *in node*
    // but I do it for use *in the browser*, because it is just the test suite
    paths: {
        "solidstate"          : "../lib/solidstate",
        "jquery"              : "vendor/jquery-1.8.2"
    },
    packages: [
        { "name": "backbone",     "main": "backbone.js",              "location": "../node_modules/backbone"                  },
        { "name": "chai",         "main": "chai.js",                  "location": "../node_modules/chai"                      },
        { "name": "claire",       "main": "lib/index.js",             "location": "../node_modules/claire"                       },
        { "name": "knockout",     "main": "knockout-latest.debug.js", "location": "../node_modules/knockout/build/output"     },
        { "name": "mocha",        "main": "mocha.js",                 "location": "../node_modules/mocha"                     },
        { "name": "underscore",   "main": "underscore.js",            "location": "../node_modules/underscore"                },
        { "name": "URIjs",        "main": "URI.js",                   "location": "../node_modules/URIjs/src"                 },
        { "name": "when",         "main": "when.js",                  "location": "../node_modules/when"                      },
        { "name": "zoetropic",    "main": "zoetropic.js",             "location": "../node_modules/zoetropic/lib"             }
    ],
    shim: {
        "backbone": {
            exports: "Backbone",
            deps: ["underscore"]
        },
        "underscore": {
            exports: "_"
        }
    },
    urlArgs: "v=" + (new Date()).getTime()
});


text:
var $fixture;

beforeEach(function() {
	$fixture = $('#fixture').empty();
});

describe('#initDel', function() {
	it('call #initEl', function() {
		var module = makeSimpleModule();
		var spiedInitEl = spy.on(module, 'initEl');
		var $el = makeEl('module').appendTo($fixture);
		module.initDel({
			dName: 'module'
		});
		spiedInitEl.should.have.been.called();
	});

	it('set DelOptions', function() {
		var module = makeSimpleModule();
		module.initDel({key: null});
		expect(module.DelOptions).to.have.property('key')
	});
});

describe('#makeName', function() {
	beforeEach(function() {
		this.module = makeModule();
	});
	it ('return bem el', function() {
		var name = this.module.makeName('el');
		assert(name == 'module__el');
	});
	it('return bem el with mod', function() {
		var name = this.module.makeName('el', 'mod');
		assert(name == 'module__el--mod');
	});
});

describe('#makeSelector', function() {
	beforeEach(function() {
		this.module = makeModule();
	});
	it ('return bem el as selector', function() {
		var selector = this.module.makeSelector('el');
		assert(selector == '.module__el');
	});
	it('return bem el as selector with mod', function() {
		var selector = this.module.makeSelector('el', 'mod');
		assert(selector == '.module__el--mod');
	});
});

describe('#setName', function() {
	beforeEach(function() {
		this.module = makeModule();
	});
	it ('set name on module el', function() {
		this.module.$el.removeClass('module');
		this.module.setName();
		assert(this.module.$el.hasClass('module'));
	});
});

describe('#find', function() {
	beforeEach(function() {
		this.module = makeModule();
	});
	it ('#find el', function() {
		var $el = $('

');
		this.module.$el.append($el);
		assert(this.module.find('el')[0] == $el[0]);
	});
	it('#find el with mode', function() {
		var $el = $('

');
		this.module.$el.append($el);
		assert(this.module.find('el', 'mod')[0] == $el[0]);
	});
	it('#find not existing el should return empty collection', function() {
		assert(this.module.find('nonexist').length == 0);
	});
});

describe('#findIn', function() {
	beforeEach(function() {
		this.module = makeModule();
	});
	it ('find existing el', function() {
		$('body').append($('

'));
		var $jq = this.module.findIn('.jq', 'el');
		assert($jq.length);
		$jq.remove();
	});
	it('find non existing el should have no result', function() {
		assert(!this.module.findIn('.nonexist', 'el').length);
	});
});

describe('events', function() {
	var module;
	beforeEach(function() {
		this.module = makeModule();
	});

	it('#eventName', function() {
		assert(this.module.eventName('event') == 'event.module');
	});

	it ('#on', function() {
		this.module.on('event', function() {
			assert(true);
		});
		this.module.trigger('event');

	});

	it('#on - should create event with with bubbling', function() {
		var $child = $('
', {"class": this.module.makeName('child')});
		this.module.$el.append($child);
		this.module.on('click', 'child', function() {
			assert(true);
		});
		$child.trigger('click.module');
	});

	it('#off', function() {
		var triggered = false;
		this.module.on('event', function() {
			if (!triggered) {
				assert(true);
				triggered = true;
			} else {
				assert(false);
			}
		});
		this.module.trigger('event');
		this.module.off('event');
		this.module.trigger('event');
	});

	it('#off - should remove event with with bubbling', function() {
		var $child = $('
', {"class": this.module.makeName('child')});
		this.module.$el.append($child);
		var flag = true;
		this.module.on('click', 'child', function() {
			flag = false;
		});
		this.module.off('click', 'child');
		$child.trigger('click.module');
		assert(flag);
	});
});

describe('modifier', function() {
	var module;
	beforeEach(function() {
		this.module = makeModule();
	});
	it ('#modName', function() {
		assert(this.module.modName('mod') == 'module--mod');
	});

	it('#hasMod', function() {
		assert(!this.module.hasMod('mod'));
		this.module.$el.addClass('module--mod');
		assert(this.module.hasMod('mod'));
	});

	it('#addMod', function() {
		this.module.addMod('mod');
		assert(this.module.hasMod('mod'));
	});

	it('#removeMod', function() {
		this.module.addMod('mod');
		this.module.removeMod('mod');
		assert(!this.module.hasMod('mod'));
	});

	describe('#toggleMod', function() {
		it('(add)', function() {
			this.module.toggleMod('mod');
			assert(this.module.hasMod('mod'));
		});

		it('(remove)', function() {
			this.module.addMod('mod');
			this.module.toggleMod('mod');
			assert(!this.module.hasMod('mod'));
		});

		it('with true state', function() {
			this.module.toggleMod('mod', true);
			assert(this.module.hasMod('mod'));
		});
		it ('with false state', function() {
			this.module.addMod('mod');
			this.module.toggleMod('mod', false);
			assert(!this.module.hasMod('mod'));
		});
	});

	it('#filterByMod', function() {
		this.module.$el.addClass('module--mod');
		assert(this.module.filterByMod('mod')[0] == this.module.$el[0]);
	});
});

describe('#createEl', function() {
	var module;
	beforeEach(function() {
		this.module = makeModule();
	});

	it ('created el has proper class', function() {
		assert(this.module.createEl('el').hasClass('module__el'));
	});

	it('create el has proper tag name', function() {
		assert(this.module.createEl('el')[0].tagName.toLowerCase() == 'div');
	});
});

describe('#initEl', function() {
	it('exit if $el exists', function() {
		var module = makeSimpleModule();
		var $el = makeEl();
		module.$el = $el;
		module.initDel();
		module.$el[0].should.be.eql($el[0]);
	});

	it('set $el prop from DelOptions', function() {
		var module = makeSimpleModule();
		var $el = $('
');
		module.DelOptions = {$el: $el};
		module.initEl();
		expect(module.$el[0]).to.be.eql($el[0]);
	});

	it('make $el by dName if $el is not provided', function() {
		var module = makeSimpleModule();
		var $el = $('
', {'class': 'dName'});
		$fixture.append($el);
		module.DelOptions = {};
		module.dName = 'dName';
		module.initEl();
		expect(module.$el[0]).to.be.eql($el[0]);
	});

	it('transform $el to jQuery if it is not', function() {
		var module = makeSimpleModule();
		var $el = $('
');
		$fixture.append($el);
		module.DelOptions = {$el: $el[0]};
		module.initEl();
		expect(module.$el[0]).to.be.eql($el[0]);
	});
});

function makeModule(name, $el) {
	name = name || 'module';
	var Module = function(){
		this.$el = makeEl(name);
		this.initDel({dName: name});
	};
	Module.prototype = $.Del;
	var module = new Module();
	return module;
}

function makeSimpleModule () {
	function Module () {}
	Module.prototype = Object.create($.Del);
	return new Module;
}

function makeEl(className) {
  var $el = $('
', {
    class: className
  });
  return $el;
}
function l(x) {
	console.log(x);
}


text:
<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="match_parent">
    <ImageView
        android:id="@+id/album_placeholder"
        android:src="@drawable/ic_content_picture"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:layout_centerInParent="true"
        android:layout_alignParentTop="true"
        android:layout_above="@+id/album_line_page_indicator"/>
    <android.support.v4.view.ViewPager
        android:id="@+id/album_viewpager"
        android:layout_height="0dp"
        android:layout_width="match_parent"
        android:layout_alignParentTop="true"
        android:layout_above="@+id/album_line_page_indicator"/>
    <com.viewpagerindicator.UnderlinePageIndicator
        android:id="@+id/album_line_page_indicator"
        android:layout_width="match_parent"
        android:layout_height="2dp"
        android:layout_alignParentBottom="true"/>
</RelativeLayout>


text:
/**
 * Created by vbudhram on 8/5/14.
 */

describe('Yahoo Test', function () {
    var credentials = require('../../fantasyCredentials.json');

    var YAHOO = require('../utils/yahooUtils');
    var username = credentials.yahoo.username;
    var password = credentials.yahoo.password;

    it('should login user', function (done) {
        YAHOO.login(username, password).then(function(data){
            data.body.should.not.be.null;
            data.cookieJar.should.not.be.null;
            done();
        }, function(err){
            done(err);
        });
    });

    it('should get user team information', function (done) {
        YAHOO.getTeams(username, password).then(function (data) {
            console.log(JSON.stringify(data));
            done();
        }, function (err) {
            done(err);
        });
    });

    it('should save scoreboard for each league', function (done) {
        var username = credentials.yahoo.username;
        var password = credentials.yahoo.password;
        var url = 'http://football.fantasysports.yahoo.com/f1/14813';
        YAHOO.login(username, password).then(function(data){
            var cookieJar = data.cookieJar;
            YAHOO.getScoreboard(url, cookieJar).then(function(data){
                data.should.not.be.null;
                done();
            }, function(err){
                done(err);
            });
        });
    });
});


text:
id: 587d7fa8367417b2b2512bcc
title: Display Shapes with SVG
required:
  - src: 'https://cdnjs.cloudflare.com/ajax/libs/d3/4.3.0/d3.min.js'
challengeType: 6
videoUrl: ''
localeTitle: Отображать фигуры с помощью SVG
---

## Description
undefined

## Instructions

 Добавьте rect форму в svg используя append() , и присвойте ему атрибут width 25 и атрибут height 100. Также дайте атрибутам rect x и y каждый из которых установлен в 0.

## Tests

```yml
tests:
  - text: В вашем документе должен быть 1 элемент <code>rect</code> .
    testString: 'assert($("rect").length == 1, "Your document should have 1 <code>rect</code> element.");'
  - text: Элемент <code>rect</code> должен иметь атрибут <code>width</code> равный 25.
    testString: 'assert($("rect").attr("width") == "25", "The <code>rect</code> element should have a <code>width</code> attribute set to 25.");'
  - text: Элемент <code>rect</code> должен иметь атрибут <code>height</code> равный 100.
    testString: 'assert($("rect").attr("height") == "100", "The <code>rect</code> element should have a <code>height</code> attribute set to 100.");'
  - text: Элемент <code>rect</code> должен иметь атрибут <code>x</code> равный 0.
    testString: 'assert($("rect").attr("x") == "0", "The <code>rect</code> element should have an <code>x</code> attribute set to 0.");'
  - text: ''
    testString: 'assert($("rect").attr("y") == "0", "The <code>rect</code> element should have a <code>y</code> attribute set to 0.");'

```

## Challenge Seed

```html
<body>
  <script>
    const dataset = [12, 31, 22, 17, 25, 18, 29, 14, 9];

    const w = 500;
    const h = 100;

    const svg = d3.select("body")
                  .append("svg")
                  .attr("width", w)
                  .attr("height", h)
                  // Add your code below this line

                  // Add your code above this line
  </script>
</body>

```

## Solution

```js
// solution required
```


text:
<?php

namespace Rootpress\models;

/**
 * Rootpress Model Interface to obligate dev to implements some methods in their Rootpress entities
 */
interface RootpressModelInterface  {

    /**
     * Return the ACF => Attribute mapping
     * ACF name => [ACF key => typeAttribute]
     * @return array
     */
    public function getAttributeMapping();

}


text:
FOUNDATION_EXPORT double ZZDownloadCenterVersionNumber;
FOUNDATION_EXPORT const unsigned char ZZDownloadCenterVersionString[];


text:
package com.altinn.apps.fisher.net.jsobj;
/**
 * A JSONObject  for "Attachments"
 * Created into Java Object 'AttachmentObj' to use their fields directly
 */

import org.json.JSONException;
import org.json.JSONObject;

public class AttachmentObj implements JsonObj{

	public String mAttachmentLink;
	public String mFileName;
	public String mData;

	/*
	 * (non-Javadoc)
	 * @see com.altinn.apps.fisher.net.jsobj.JsonObj#parse(org.json.JSONObject)
	 */
	public AttachmentObj parse(JSONObject jsObj){
		AttachmentObj obj = new AttachmentObj();
		try{
			if(jsObj.has("FileName"))
				obj.mFileName = jsObj.getString("FileName");
			if(jsObj.has("AttachmentLink"))
				obj.mAttachmentLink = jsObj.getString("AttachmentLink");
			if(jsObj.has("Data"))
				obj.mData = jsObj.getString("Data");

		}catch(JSONException jse){
			obj = null;
		}catch(Exception e){
			obj = null;
		}
		return obj;
	}

	/**
	 * its a warper function for, which will support String type input.
	 */
	public AttachmentObj parse(String jsStrings) throws JSONException {
		JSONObject jsObj = new JSONObject(jsStrings);
		return parse(jsObj);
	}

	/*
	 * (non-Javadoc)
	 * @see com.altinn.apps.fisher.net.jsobj.JsonObj#createJson()
	 */
	public JSONObject createJson(){
		JSONObject  jsObj = null;
		try {
			jsObj = new JSONObject();
			if(mFileName != null)
				jsObj.put("FileName", mFileName);
			if(mAttachmentLink != null)
				jsObj.put("AttachmentLink", mAttachmentLink);
			if(mData != null)
				jsObj.put("Data", mData);
		} catch (JSONException e) {
			jsObj = null;
			e.printStackTrace();
		}

		return jsObj;
	}

}


text:
class CL {
    private int i;

    private int j;

    private int l;

    <caret>private int k;

    private int p;
}


text:
using System;
using System.Collections.Generic;
using System.Collections.Concurrent;
using System.IO;
using System.Net;

namespace Chauffeur.Tests.Jenkins.Client
{
    public class MockWebRequestFactory : IWebRequestCreate
    {
        #region Fields

        private readonly ConcurrentDictionary<Uri, MockWebResponse> _Responses = new ConcurrentDictionary<Uri, MockWebResponse>();

        #endregion

        #region Constructors

        /// <summary>
        ///     Initializes a new instance of the <see cref="MockWebRequestFactory" /> class.
        /// </summary>
        /// <param name="prefix">The prefix.</param>
        public MockWebRequestFactory(string prefix)
        {
            WebRequest.RegisterPrefix(prefix, this);
        }

        #endregion

        #region IWebRequestCreate Members

        /// <summary>
        ///     Creates a <see cref="T:System.Net.WebRequest" /> instance.
        /// </summary>
        /// <param name="uri">The uniform resource identifier (URI) of the Web resource.</param>
        /// <returns>
        ///     A <see cref="T:System.Net.WebRequest" /> instance.
        /// </returns>
        public WebRequest Create(Uri uri)
        {
            MockWebResponse response;

            _Responses.TryGetValue(uri, out response);
            return new MockWebRequest(uri, response);
        }

        #endregion

        #region Internal Methods

        /// <summary>
        ///     Expects the specified URI.
        /// </summary>
        /// <param name="uri">The URI.</param>
        /// <param name="response">The response.</param>
        internal void Expect(Uri uri, MockWebResponse response)
        {
            _Responses[uri] = response;
        }

        /// <summary>
        ///     Expects the specified URI.
        /// </summary>
        /// <param name="uri">The URI.</param>
        /// <param name="response">The response.</param>
        internal void Expect(Uri uri, string response)
        {
            this.Expect(uri, new MockWebResponse(response));
        }

        /// <summary>
        ///     Expects the specified URI.
        /// </summary>
        /// <param name="uri">The URI.</param>
        /// <param name="stream">The stream.</param>
        internal void Expect(Uri uri, Stream stream)
        {
            using (var streamReader = new StreamReader(stream))
            {
                this.Expect(uri, streamReader.ReadToEnd());
            }
        }

        #endregion
    }
}


text:
using base::android::JavaParamRef;
using base::android::ScopedJavaLocalRef;
using content::WebContents;

static ScopedJavaLocalRef<jobjectArray>
JNI_CertificateChainHelper_GetCertificateChain(
    JNIEnv* env,
    const JavaParamRef<jobject>& java_web_contents) {
  content::WebContents* web_contents =
      content::WebContents::FromJavaWebContents(java_web_contents);
  if (!web_contents)
    return ScopedJavaLocalRef<jobjectArray>();

  scoped_refptr<net::X509Certificate> cert =
      web_contents->GetController().GetVisibleEntry()->GetSSL().certificate;
  if (!cert)
    return ScopedJavaLocalRef<jobjectArray>();

  std::vector<std::string> cert_chain;
  cert_chain.reserve(1 + cert->intermediate_buffers().size());
  cert_chain.emplace_back(
      net::x509_util::CryptoBufferAsStringPiece(cert->cert_buffer()));
  for (const auto& handle : cert->intermediate_buffers()) {
    cert_chain.emplace_back(
        net::x509_util::CryptoBufferAsStringPiece(handle.get()));
  }

  return base::android::ToJavaArrayOfByteArray(env, cert_chain);
}


text:
package org.apache.cassandra.streaming;

import java.util.*;

import com.google.common.annotations.VisibleForTesting;

import org.apache.cassandra.locator.InetAddressAndPort;
import org.apache.cassandra.locator.RangesAtEndpoint;
import org.apache.cassandra.locator.Replica;
import org.apache.cassandra.utils.TimeUUID;

import static com.google.common.collect.Iterables.all;
import static org.apache.cassandra.service.ActiveRepairService.NO_PENDING_REPAIR;
import static org.apache.cassandra.streaming.StreamingChannel.Factory.Global.streamingFactory;
import static org.apache.cassandra.utils.TimeUUID.Generator.nextTimeUUID;

/**
 * {@link StreamPlan} is a helper class that builds StreamOperation of given configuration.
 *
 * This is the class you want to use for building streaming plan and starting streaming.
 */
public class StreamPlan
{
    private static final String[] EMPTY_COLUMN_FAMILIES = new String[0];
    private final TimeUUID planId = nextTimeUUID();
    private final StreamOperation streamOperation;
    private final List<StreamEventHandler> handlers = new ArrayList<>();
    private final StreamCoordinator coordinator;

    private boolean flushBeforeTransfer = true;

    /**
     * Start building stream plan.
     *
     * @param streamOperation Stream streamOperation that describes this StreamPlan
     */
    public StreamPlan(StreamOperation streamOperation)
    {
        this(streamOperation, 1, false, NO_PENDING_REPAIR, PreviewKind.NONE);
    }

    public StreamPlan(StreamOperation streamOperation, boolean connectSequentially)
    {
        this(streamOperation, 1, connectSequentially, NO_PENDING_REPAIR, PreviewKind.NONE);
    }

    public StreamPlan(StreamOperation streamOperation, int connectionsPerHost,
                      boolean connectSequentially, TimeUUID pendingRepair, PreviewKind previewKind)
    {
        this.streamOperation = streamOperation;
        this.coordinator = new StreamCoordinator(streamOperation, connectionsPerHost, streamingFactory(),
                                                 false, connectSequentially, pendingRepair, previewKind);
    }

    /**
     * Request data in {@code keyspace} and {@code ranges} from specific node.
     *
     * Here, we have to encode both _local_ range transientness (encoded in Replica itself, in RangesAtEndpoint)
     * and _remote_ (source) range transientmess, which is encoded by splitting ranges into full and transient.
     *
     * At the other end the distinction between full and transient is ignored it just used the transient status
     * of the Replica objects we send to determine what to send. The real reason we have this split down to
     * StreamRequest is that on completion StreamRequest is used to write to the system table tracking
     * what has already been streamed. At that point since we only have the local Replica instances so we don't
     * know what we got from the remote. We preserve that here by splitting based on the remotes transient
     * status.
     *
     * @param from endpoint address to fetch data from.
     * @param keyspace name of keyspace
     * @param fullRanges ranges to fetch that from provides the full version of
     * @param transientRanges ranges to fetch that from provides only transient data of
     * @return this object for chaining
     */
    public StreamPlan requestRanges(InetAddressAndPort from, String keyspace, RangesAtEndpoint fullRanges, RangesAtEndpoint transientRanges)
    {
        return requestRanges(from, keyspace, fullRanges, transientRanges, EMPTY_COLUMN_FAMILIES);
    }

    /**
     * Request data in {@code columnFamilies} under {@code keyspace} and {@code ranges} from specific node.
     *
     * @param from endpoint address to fetch data from.
     * @param keyspace name of keyspace
     * @param fullRanges ranges to fetch that from provides the full data for
     * @param transientRanges ranges to fetch that from provides only transient data for
     * @param columnFamilies specific column families
     * @return this object for chaining
     */
    public StreamPlan requestRanges(InetAddressAndPort from, String keyspace, RangesAtEndpoint fullRanges, RangesAtEndpoint transientRanges, String... columnFamilies)
    {
        //It should either be a dummy address for repair or if it's a bootstrap/move/rebuild it should be this node
        assert all(fullRanges, Replica::isSelf) || RangesAtEndpoint.isDummyList(fullRanges) : fullRanges.toString();
        assert all(transientRanges, Replica::isSelf) || RangesAtEndpoint.isDummyList(transientRanges) : transientRanges.toString();

        StreamSession session = coordinator.getOrCreateOutboundSession(from);
        session.addStreamRequest(keyspace, fullRanges, transientRanges, Arrays.asList(columnFamilies));
        return this;
    }

    /**
     * Add transfer task to send data of specific {@code columnFamilies} under {@code keyspace} and {@code ranges}.
     *
     * @param to endpoint address of receiver
     * @param keyspace name of keyspace
     * @param replicas ranges to send
     * @param columnFamilies specific column families
     * @return this object for chaining
     */
    public StreamPlan transferRanges(InetAddressAndPort to, String keyspace, RangesAtEndpoint replicas, String... columnFamilies)
    {
        StreamSession session = coordinator.getOrCreateOutboundSession(to);
        session.addTransferRanges(keyspace, replicas, Arrays.asList(columnFamilies), flushBeforeTransfer);
        return this;
    }

    /**
     * Add transfer task to send given streams
     *
     * @param to endpoint address of receiver
     * @param streams streams to send
     * @return this object for chaining
     */
    public StreamPlan transferStreams(InetAddressAndPort to, Collection<OutgoingStream> streams)
    {
        coordinator.transferStreams(to, streams);
        return this;
    }

    public StreamPlan listeners(StreamEventHandler handler, StreamEventHandler... handlers)
    {
        this.handlers.add(handler);
        if (handlers != null)
            Collections.addAll(this.handlers, handlers);
        return this;
    }

    /**
     * Set custom StreamConnectionFactory to be used for establishing connection
     *
     * @param factory StreamConnectionFactory to use
     * @return self
     */
    public StreamPlan connectionFactory(StreamingChannel.Factory factory)
    {
        this.coordinator.setConnectionFactory(factory);
        return this;
    }

    /**
     * @return true if this plan has no plan to execute
     */
    public boolean isEmpty()
    {
        return !coordinator.hasActiveSessions();
    }

    /**
     * Execute this {@link StreamPlan} asynchronously.
     *
     * @return Future {@link StreamState} that you can use to listen on progress of streaming.
     */
    public StreamResultFuture execute()
    {
        return StreamResultFuture.createInitiator(planId, streamOperation, handlers, coordinator);
    }

    /**
     * Set flushBeforeTransfer option.
     * When it's true, will flush before streaming ranges. (Default: true)
     *
     * @param flushBeforeTransfer set to true when the node should flush before transfer
     * @return this object for chaining
     */
    public StreamPlan flushBeforeTransfer(boolean flushBeforeTransfer)
    {
        this.flushBeforeTransfer = flushBeforeTransfer;
        return this;
    }

    public TimeUUID getPendingRepair()
    {
        return coordinator.getPendingRepair();
    }

    public boolean getFlushBeforeTransfer()
    {
        return flushBeforeTransfer;
    }

    @VisibleForTesting
    public StreamCoordinator getCoordinator()
    {
        return coordinator;
    }
}


text: Error:  Comuníquese con el Administrador.


text:
#ifndef FOLLY_EXCEPTION_H_
#define FOLLY_EXCEPTION_H_

#include <errno.h>

#include <cstdio>
#include <stdexcept>
#include <system_error>

#include <folly/Conv.h>
#include <folly/FBString.h>
#include <folly/Likely.h>
#include <folly/Portability.h>

namespace folly {

// Various helpers to throw appropriate std::system_error exceptions from C
// library errors (returned in errno, as positive return values (many POSIX
// functions), or as negative return values (Linux syscalls))
//
// The *Explicit functions take an explicit value for errno.

// Helper to throw std::system_error
[[noreturn]] inline void throwSystemErrorExplicit(int err, const char* msg) {
  throw std::system_error(err, std::system_category(), msg);
}

template <class... Args>
[[noreturn]] void throwSystemErrorExplicit(int err, Args&&... args) {
  throwSystemErrorExplicit(
      err, to<fbstring>(std::forward<Args>(args)...).c_str());
}

// Helper to throw std::system_error from errno and components of a string
template <class... Args>
[[noreturn]] void throwSystemError(Args&&... args) {
  throwSystemErrorExplicit(errno, std::forward<Args>(args)...);
}

// Check a Posix return code (0 on success, error number on error), throw
// on error.
template <class... Args>
void checkPosixError(int err, Args&&... args) {
  if (UNLIKELY(err != 0)) {
    throwSystemErrorExplicit(err, std::forward<Args>(args)...);
  }
}

// Check a Linux kernel-style return code (>= 0 on success, negative error
// number on error), throw on error.
template <class... Args>
void checkKernelError(ssize_t ret, Args&&... args) {
  if (UNLIKELY(ret < 0)) {
    throwSystemErrorExplicit(-ret, std::forward<Args>(args)...);
  }
}

// Check a traditional Unix return code (-1 and sets errno on error), throw
// on error.
template <class... Args>
void checkUnixError(ssize_t ret, Args&&... args) {
  if (UNLIKELY(ret == -1)) {
    throwSystemError(std::forward<Args>(args)...);
  }
}

template <class... Args>
void checkUnixErrorExplicit(ssize_t ret, int savedErrno, Args&&... args) {
  if (UNLIKELY(ret == -1)) {
    throwSystemErrorExplicit(savedErrno, std::forward<Args>(args)...);
  }
}

// Check the return code from a fopen-style function (returns a non-nullptr
// FILE* on success, nullptr on error, sets errno).  Works with fopen, fdopen,
// freopen, tmpfile, etc.
template <class... Args>
void checkFopenError(FILE* fp, Args&&... args) {
  if (UNLIKELY(!fp)) {
    throwSystemError(std::forward<Args>(args)...);
  }
}

template <class... Args>
void checkFopenErrorExplicit(FILE* fp, int savedErrno, Args&&... args) {
  if (UNLIKELY(!fp)) {
    throwSystemErrorExplicit(savedErrno, std::forward<Args>(args)...);
  }
}

template <typename E, typename V, typename... Args>
void throwOnFail(V&& value, Args&&... args) {
  if (!value) {
    throw E(std::forward<Args>(args)...);
  }
}

/**
 * If cond is not true, raise an exception of type E.  E must have a ctor that
 * works with const char* (a description of the failure).
 */
#define CHECK_THROW(cond, E) \
  ::folly::throwOnFail<E>((cond), "Check failed: " #cond)

}  // namespace folly

#endif /* FOLLY_EXCEPTION_H_ */


text:
package cn.enilu.flash.api.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;

@Configuration
public class QuartzConfiguration {

    @Bean(name = "scheduler")
    public SchedulerFactoryBean schedulerFactory() {
        SchedulerFactoryBean bean = new SchedulerFactoryBean();
        return bean;
    }
}


text:
'use strict';

var gulp = require('gulp');
var exec = require('exec-sync');
var util = require('util');

gulp.task('link', function () {
  var srcDir = process.env.PWD;
  var cmd = util.format('ln -s -f %s/src %s/node_modules', srcDir, srcDir);
  console.log(cmd);
  exec(cmd);

  cmd = util.format('ln -s -f %s/recipe %s/node_modules', srcDir, srcDir);
  console.log(cmd);
  exec(cmd);
});


text:
package org.databene.commons.validator;

import static org.junit.Assert.*;

import org.databene.commons.CharSet;
import org.junit.Test;

/**
 * Tests the {@link CharacterValidator}.
 * Created: 17.12.2009 19:03:03
 * @since 0.5.0
 * @author Volker Bergmann
 */
public class CharacterValidatorTest {

	@Test
	public void test() {
		CharacterValidator validator = new CharacterValidator(new CharSet('0', '9'));
		assertFalse(validator.valid('a'));
		assertTrue(validator.valid('0'));
		assertTrue(validator.valid('9'));
		assertFalse(validator.valid('X'));
		assertFalse(validator.valid('-'));
	}

}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>WiXParams - FAKE - F# Make</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="">
    <meta name="author" content="Steffen Forkmann, Mauricio Scheffer, Colin Bull">

    <link href="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.2.1/css/bootstrap-combined.min.css" rel="stylesheet">

    <link type="text/css" rel="stylesheet" href="http://fsharp.github.io/FAKE/content/style.css" />

fsharp.org

github page

FAKE - F# Make

WiXParams

WiX parameter type

Record Fields

Record Field	Description

            AdditionalCandleArgs

            Signature:string list

            Go to GitHub source

            AdditionalLightArgs

            Signature:string list

            Go to GitHub source

            TimeOut

            Signature:TimeSpan

            Go to GitHub source

            ToolDirectory

            Signature:string

            Go to GitHub source

FAKE - F# Make

Home page

Get FAKE via NuGet

Source Code on GitHub

License (MS-PL)

Who is using FAKE?

Release Notes

Contributing to FAKE

Ask a question

Articles

Getting started

NuGet package restore

Using FxCop in a build

Generating AssemblyInfo

Create NuGet packages

Running specific targets

Running FAKE from command line

Creating custom tasks

TeamCity integration

Running canopy tests

Octopus Deploy

TypeScript support

Fake.Deploy

Documentation

API Reference


text:
<?php
require '../config.inc.php';

$config = $ijsxc_config['ice'];

$data = array ();
$data ['ttl'] = $config['ttl'] ?  : 3600 * 24; // one day (according to TURN-REST-API)
$data ['url'] = $config['url'];
$data ['username'] = $config['username'] ?  : ($config['secret'] ? (time () + $data ['ttl']) . ':username'  : '');
$data ['credential'] = $config['credential'] ?  : ($config['secret'] ? base64_encode ( hash_hmac ( 'sha1', $data ['username'], $config['secret'], true ) ) : '');

echo json_encode($data);
?>


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<ns2:attributeTranslationResultList xmlns:ns2="http://further.utah.edu/mdr" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
	<attributeTranslationResult>
		<translatedAttribute>id.code</translatedAttribute>
		<properties>
			<entry>
				<key xsi:type="xs:string">ATTR_JAVA_TYPE</key>
				<value xsi:type="xs:string">java.lang.Long</value>
			</entry>
		</properties>
	</attributeTranslationResult>
	<attributeTranslationResult>
		<translatedAttribute>id.obsvtnStudyCodeDwid</translatedAttribute>
		<properties>
			<entry>
				<key xsi:type="xs:string">ATTR_JAVA_TYPE</key>
				<value xsi:type="xs:string">java.lang.Long</value>
			</entry>
		</properties>
	</attributeTranslationResult>
</ns2:attributeTranslationResultList>


text:
var fs = require('fs'),
	esprima = require('esprima'),
	estraverse = require('estraverse'),
	Finder = require('fs-finder'),
	clc = require('cli-color'),
	error = clc.red.bold,

	conf = JSON.parse(fs.readFileSync(process.argv[2], encoding="ascii")),
	location = conf.location,
	constantsValues = conf.constantsValues,
	excludesFiles = conf.excludesFiles;

	inspectLocation(location);

function inspectLocation(location) {
	console.log('Inspecting', location);
	Finder.from(location).findFiles('*.js', function(files) {
		var ast,
			fileFullPath,
			filename,
			faults = {};
		for (var file in files) {
			fileFullPath = files[file];
			filename = fileFullPath.replace(/^.*[\\\/]/, '');

			if (filename && excludesFiles.indexOf(filename) === -1) {
				try {
					ast = esprima.parse(fs.readFileSync(fileFullPath), {loc:true});
					estraverse.traverse(ast, {
						enter: function (node, parent) {
							if (node.type === 'Literal') {
								for (var item in constantsValues) {
									if (node.value === constantsValues[item]) {
										faults[node.value] = faults[node.value] || {count:0, locations:[]};
										faults[node.value].count++;
										faults[node.value].locations.push({file:filename, loc:node.loc});
									}
								}
							}
						},
						leave: function(node, parent) {
						}
					});
				} catch(e) {
				}
			}
		};

		for (var prop in faults) {
			if (faults.hasOwnProperty(prop)) {
				console.log(error('Fount "' + prop + '"', faults[prop].count, 'times:'));
				var location = null;
				for (var i = 0; i < faults[prop].count; i++) {
					location = faults[prop].locations[i];
					console.log(clc.red('\t', location.file, 'Line', location.loc.start.line));
				}
			}
		}
	});
}


text:
  <ng-template #showResults>

          {{result.code}}

        <ng-template [ngIf]="result.highlight.text != undefined">

        </ng-template>
        <ng-template [ngIf]="result.highlight.text == undefined">

            <ng-template [ngIf]="result.highlight[alternativeField.key] != undefined">

{{('LBL_' + alternativeField.key.toUpperCase()) | translate}}

            </ng-template>

        </ng-template>

        {{ 'LBL_NO_RESULTS' | translate }}

  </ng-template>
  <ng-template #searching>

        Searching...

  </ng-template>


text:
"""
Binary Trees
author: Chris Lee
created: October 11, 2013
"""

"""
Implementing Binary Trees
"""
import numpy.random as rand
import itertools

class BinaryTree:
	def __init__ (self, depth = 0, parent = None):
		self.depth = depth
		self.assignValue()

		self.parent = parent
		self.left = BinaryTree(depth = depth - 1, parent = self) if depth > 0 else None
		self.right = BinaryTree(depth = depth - 1, parent = self) if depth > 0 else None

	#Assign unique value to node
	def assignValue(self):
		index = rand.randint(len(uniqueList))
		self.value = uniqueList[index]
		del(uniqueList[index])

	#Find common parent without storing nodes
	def getRandomNodes(self, number):
		nodes = []
		for _ in itertools.repeat(None,number):
			node = self
			for _ in itertools.repeat(None,rand.randint(self.depth)):
				node = node.left if rand.randint(2) == 0 else node.right
			nodes.append(node)
		return nodes

	def commonParent(self, nodes):
		print "="*(50 + 2*len(nodes)), "\n  Searching for a common parent for nodes:", ",".join([str(x.value) for x in nodes]), "\n", "="*(50 + 2*len(nodes))

		#Check Node inputs
		if None in [x.parent for x in nodes]:
			print "Warning: root node has no parent."

		if len(set(nodes)) != len(nodes):
			print "Warning: nodes are identical"

		#Bring to the same depth
		maxDepth = max([x.depth for x in nodes])
		while min([x.depth for x in nodes]) != maxDepth:
			nodes = [x.parent if x.depth < maxDepth else x for x in nodes]

		#Set for uniqueness
		nodes = set(nodes)
		while len(nodes) > 1:
			nodes = set([x.parent for x in list(nodes)])

		print "Common Parent:"
		return list(nodes)[0]

	"""
	Printing Binary Trees
	Simple Printer - up to 5
	"""

	def buildTree(self, treeBuilder = dict()):
		treeBuilder[self.depth] = treeBuilder.get(self.depth,[]) + [str(self.value)]
		treeBuilder = self.left.buildTree(treeBuilder = treeBuilder) if self.left != None else treeBuilder
		treeBuilder = self.right.buildTree(treeBuilder = treeBuilder) if self.right != None else treeBuilder
		return treeBuilder

	def lineBuilder(self,integers, spaces):
		tabs = (spaces - sum([len(str(x)) for x in integers]))/(len(integers) + 1)
		return "".join([tabs*" " + str(x) for x in integers])

	def printTree(self):
		printDict = self.buildTree()
		spaces = 88
		for depth in range(self.depth,0,-1):
			print self.lineBuilder(printDict[depth],spaces)
		return 1

if __name__ == "__main__":
	global uniqueList
	depth = 5
	uniqueList = range(pow(2,depth + 1))
	tree = BinaryTree(depth = depth)
	#nodeA,nodeB = tree.getRandomNodes(number = 2)
	#print nodeA.value
	print "==========================\n     Here's the tree!\n=========================="
	tree.printTree()
	print tree.commonParent(tree.getRandomNodes(number = 5)).value


text:
package org.pcu.connectors.collectors;

import static com.github.tomakehurst.wiremock.client.WireMock.delete;
import static com.github.tomakehurst.wiremock.client.WireMock.deleteRequestedFor;
import static com.github.tomakehurst.wiremock.client.WireMock.noContent;
import static com.github.tomakehurst.wiremock.client.WireMock.ok;
import static com.github.tomakehurst.wiremock.client.WireMock.post;
import static com.github.tomakehurst.wiremock.client.WireMock.postRequestedFor;
import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching;
import static com.github.tomakehurst.wiremock.client.WireMock.urlPathMatching;
import static org.assertj.core.api.Assertions.assertThat;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.platform.runner.JUnitPlatform;
import org.junit.runner.RunWith;
import org.pcu.connectors.collectors.api.PcuCollectorConfig;
import org.pcu.connectors.collectors.filesystem.internal.PcuFilesystemNorconexCollector;
import org.pcu.integration.TemporaryFolderExtension;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.tomakehurst.wiremock.WireMockServer;
import com.github.tomakehurst.wiremock.verification.LoggedRequest;
import com.google.common.base.Charsets;

import ru.lanwen.wiremock.ext.WiremockResolver;
import ru.lanwen.wiremock.ext.WiremockResolver.Wiremock;
import ru.lanwen.wiremock.ext.WiremockUriResolver;
import ru.lanwen.wiremock.ext.WiremockUriResolver.WiremockUri;

@ExtendWith({ TemporaryFolderExtension.class, WiremockResolver.class, WiremockUriResolver.class })
@RunWith(JUnitPlatform.class)
public class PcuAgentTest {

	@RegisterExtension
	public TemporaryFolderExtension temporaryFolder = new TemporaryFolderExtension();

	@Test
	public void norconexCollectorOnFileSampleOk(@Wiremock WireMockServer server, @WiremockUri String uri)
			throws IOException, URISyntaxException {

		// wiremock stub
		assertThat(server.isRunning()).isTrue();
		server.stubFor(post("/ingest").willReturn(ok()));
		server.stubFor(post(urlPathMatching("/ingest/(.*)")).willReturn(ok()));
		server.stubFor(delete(urlPathMatching("/indexes/(.*)")).willReturn(noContent()));

		// pcu agent configuration
		String confFileName = UUID.randomUUID().toString();
		File confFile = temporaryFolder.newFile(confFileName + ".json");
		String workDirFolderName = UUID.randomUUID().toString();
		File workDir = temporaryFolder.newFolder(workDirFolderName);
		File fileFolder = createTemporaryFolderWithFileSample();
		String variablesFilePath = createTempVariables(workDir.getAbsolutePath(), fileFolder.getAbsolutePath());
		String xmlFilePath = createTempXml();

		ObjectMapper mapper = new ObjectMapper();
		PcuCollectorConfig config = new PcuCollectorConfig();
		config.setCollectorId("collectorId");
		config.setDatasourceId("datasourceId");

		config.setPcuPlatformUrl(uri);
		config.set(PcuFilesystemNorconexCollector.EXTERNAL_CONFIG_XML_KEY, xmlFilePath);
		config.set(PcuFilesystemNorconexCollector.EXTERNAL_CONFIG_VARIABLES_KEY, variablesFilePath);
		mapper.writeValue(confFile, config);

		// first run pcu agent
		String[] args = new String[] { confFile.getAbsolutePath() };
		PcuAgent.main(args);

		List<String> workDirFileNames = Arrays.asList(workDir.listFiles()).stream().map(File::getAbsolutePath)
				.collect(Collectors.toList());

		assertThat(workDirFileNames).contains(workDir.getAbsolutePath() + "/crawlstore");
		assertThat(workDirFileNames).contains(workDir.getAbsolutePath() + "/logs");
		assertThat(workDirFileNames).contains(workDir.getAbsolutePath() + "/progress");

		Files.delete(Paths.get(fileFolder.getAbsolutePath() + "/20171206 POSS/PCU@POSS_20171206.pdf"));

		// second run pcu agent after deleting a file
		PcuAgent.main(args);

		// check stub calls
		List<LoggedRequest> ingestRequests = server.findAll(postRequestedFor(urlMatching("/ingest")));
		List<LoggedRequest> deleteRequests = server.findAll(deleteRequestedFor(urlPathMatching("/indexes/(.*)")));

		assertThat(ingestRequests).hasSize(3);
		assertThat(ingestRequests.get(0).getUrl()).isEqualTo("/ingest");
		assertThat(ingestRequests.get(1).getUrl()).isEqualTo("/ingest");
		assertThat(ingestRequests.get(2).getUrl()).isEqualTo("/ingest");
		assertThat(deleteRequests).hasSize(1);
		assertThat(deleteRequests.get(0).getUrl()).matches("/indexes/documents/types/document/documents/(.*)");
	}

	private String createTempVariables(String workDir, String targetPath) throws IOException {
		String filename = UUID.randomUUID().toString();
		File tmpFile = File.createTempFile(filename, ".variables");
		InputStream is = PcuAgentTest.class.getClassLoader()
				.getResourceAsStream("norconex-filesystem-config.variables");
		String content = IOUtils.toString(is, Charsets.UTF_8);
		content = content.replace("${workDir}", workDir).replace("${targetPath}", targetPath);
		FileUtils.writeStringToFile(tmpFile, content, Charsets.UTF_8);
		return tmpFile.getAbsolutePath();
	}

	private String createTempXml() throws IOException {
		String filename = UUID.randomUUID().toString();
		File tmpFile = File.createTempFile(filename, ".xml");
		InputStream is = PcuAgentTest.class.getClassLoader().getResourceAsStream("norconex-filesystem-config.xml");
		FileUtils.copyInputStreamToFile(is, tmpFile);
		return tmpFile.getAbsolutePath();
	}

	private File createTemporaryFolderWithFileSample() throws IOException, URISyntaxException {
		File newFileFolder = temporaryFolder.newFolder("file");
		File existingFileFolder = new File(PcuAgentTest.class.getClassLoader().getResource("file").toURI());
		FileUtils.copyDirectory(existingFileFolder, newFileFolder);
		return newFileFolder;
	}

}


text:
using System;

namespace Infra
{
    [Serializable]
    public class JsonResponseData
    {
        public string RedirectUrl { get; set; }
        public bool Success { get; set; }
        public string Message { get; set; }
        public object Obj { get; set; }
        public string ErrorType { get; set; }
        public int Status { get; set; }

        public JsonModelErrorData[] ModelErrors { get; set; }
    }
}


text:
PIN
            <input type="text" ng-model="user.pin" maxlength="6">

    <input type="button" class="btn-confirm" value="CADASTRAR PIN" ng-click="new()"/>


text:
require 'spec_helper'

describe I18n, "Ukrainian pluralization" do
  let(:backend) { I18n.backend }
  let(:hash) { { one: 'one', few: 'few', many: 'many', other: 'other' } }

  context "should pluralize correctly" do
    it { expect(backend.pluralize(:uk, hash, 1)).to eq 'one' }
    it { expect(backend.pluralize(:uk, hash, 2)).to eq 'few' }
    it { expect(backend.pluralize(:uk, hash, 3)).to eq 'few' }
    it { expect(backend.pluralize(:uk, hash, 5)).to eq 'many' }
    it { expect(backend.pluralize(:uk, hash, 10)).to eq 'many' }
    it { expect(backend.pluralize(:uk, hash, 11)).to eq 'many' }
    it { expect(backend.pluralize(:uk, hash, 21)).to eq 'one' }
    it { expect(backend.pluralize(:uk, hash, 29)).to eq 'many' }
    it { expect(backend.pluralize(:uk, hash, 131)).to eq 'one' }
    it { expect(backend.pluralize(:uk, hash, 1.31)).to eq 'other' }
    it { expect(backend.pluralize(:uk, hash, 2.31)).to eq 'other' }
    it { expect(backend.pluralize(:uk, hash, 3.31)).to eq 'other' }
  end
end


text:
package org.drools.workbench.screens.guided.dtree.client.widget.factories;

import javax.enterprise.context.ApplicationScoped;

import com.ait.lienzo.client.core.shape.Circle;
import com.ait.lienzo.shared.core.types.Color;
import org.drools.workbench.models.guided.dtree.shared.model.nodes.ConstraintNode;
import org.drools.workbench.models.guided.dtree.shared.model.nodes.impl.ConstraintNodeImpl;
import org.drools.workbench.screens.guided.dtree.client.widget.shapes.ConstraintShape;
import org.uberfire.ext.wires.core.api.factories.FactoryHelper;
import org.uberfire.ext.wires.core.api.shapes.WiresBaseShape;
import org.uberfire.ext.wires.core.client.util.ShapesUtils;

@ApplicationScoped
public class ConstraintNodeFactory extends BaseGuidedDecisionTreeNodeFactory<Circle> {

    private static final String DESCRIPTION = "Constraint";

    private static final int SHAPE_RADIUS = 25;

    @Override
    public String getShapeDescription() {
        return DESCRIPTION;
    }

    /**
     * This returns a new Shape following a drag operation from the palette
     * @param helper
     * @return
     */
    @Override
    public WiresBaseShape getShape( final FactoryHelper helper ) {
        final ConstraintFactoryHelper cnHelper = (ConstraintFactoryHelper) helper;
        final ConstraintNode node = cnHelper.getContext();

        //The ConstraintNode associated with the FactoryHelper is used to show the Constraint Field name on the
        //drag proxy. We need to create a new instance of the ConstraintNode for use in the Decision Tree Widget
        return new ConstraintShape( makeShape(),
                                    new ConstraintNodeImpl( node.getClassName(),
                                                            node.getFieldName() ),
                                    cnHelper.isReadOnly() );
    }

    /**
     * This returns a new Shape representing an existing Node
     * @param node
     * @param isReadOnly
     * @return
     */
    public ConstraintShape getShape( final ConstraintNode node,
                                     final boolean isReadOnly ) {
        return new ConstraintShape( makeShape(),
                                    node,
                                    isReadOnly );
    }

    @Override
    protected String getNodeLabel( final FactoryHelper helper ) {
        if ( helper instanceof ConstraintFactoryHelper ) {
            return ( (ConstraintFactoryHelper) helper ).getContext().getFieldName();
        }
        return null;
    }

    @Override
    public boolean builds( final WiresBaseShape shapeType ) {
        return shapeType instanceof ConstraintShape;
    }

    @Override
    protected Circle makeShape() {
        final Circle circle = new Circle( SHAPE_RADIUS );
        circle.setStrokeColor( Color.rgbToBrowserHexColor( 100,
                                                           100,
                                                           100 ) )
                .setStrokeWidth( ShapesUtils.RGB_STROKE_WIDTH_SHAPE )
                .setFillColor( Color.rgbToBrowserHexColor( 0,
                                                           255,
                                                           0 ) )
                .setDraggable( false );
        return circle;
    }

    @Override
    protected double getWidth() {
        return ( SHAPE_RADIUS + ShapesUtils.RGB_STROKE_WIDTH_SHAPE ) * 2;
    }

    @Override
    protected double getHeight() {
        return ( SHAPE_RADIUS + ShapesUtils.RGB_STROKE_WIDTH_SHAPE ) * 2;
    }

}


text:
require File.dirname(__FILE__) + '/spec_helper.rb'

include RR

describe TableScanHelper do
  before(:each) do
    @scan = Object.new
    @scan.extend TableScanHelper
  end

  it "rank_rows should calculate the correct rank of rows based on their primary keys" do
    @scan.stub!(:primary_key_names).and_return(['first_id', 'second_id'])
    @scan.rank_rows({'first_id' => 1, 'second_id' => 1}, {'first_id' => 1, 'second_id' => 1}).should == 0
    @scan.rank_rows({'first_id' => 1, 'second_id' => 1}, {'first_id' => 1, 'second_id' => 2}).should == -1
    @scan.rank_rows({'first_id' => 2, 'second_id' => 1}, {'first_id' => 1, 'second_id' => 1}).should == 1

    # should rank strings according to database logic ('a' < 'A')
    # instead of the Ruby logic (which is the other way round)
    @scan.rank_rows({'first_id' => 'a', 'second_id' => 1}, {'first_id' => 'B', 'second_id' => 1}).should == -1
    @scan.rank_rows({'first_id' => 'a', 'second_id' => 1}, {'first_id' => 'A', 'second_id' => 1}).should == -1
    @scan.rank_rows({'first_id' => 'a', 'second_id' => 1}, {'first_id' => 'a', 'second_id' => 1}).should == 0

    lambda {@scan.rank_rows(nil,nil)}.should raise_error(RuntimeError, 'At least one of left_row and right_row must not be nil!')
    @scan.rank_rows(nil, {'first_id' => 1, 'second_id' => 1}).should == 1
    @scan.rank_rows({'first_id' => 1, 'second_id' => 1}, nil).should == -1
  end

  it "table_scan_class should return TableScan for non-proxied sessions" do
    TableScanHelper.scan_class(Session.new(standard_config)).should == DirectTableScan
  end

  it "table_scan_class should return ProxiedTableScan for proxied sessions" do
    ensure_proxy
    TableScanHelper.scan_class(Session.new(proxied_config)).should == ProxiedTableScan
  end
end


text:
package com.newsenglish.gary.myapplication;

import android.animation.ObjectAnimator;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.newsenglish.gary.myapplication.adapter.ListViewAdapter;
import com.newsenglish.gary.myapplication.view.MyPlayer;

import org.w3c.dom.Text;

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

import static com.newsenglish.gary.myapplication.preferences.Preferences.DEFAULT_DURATION;
import static com.newsenglish.gary.myapplication.preferences.Preferences.TAB_TYPE_BBCNEWS;
import static com.newsenglish.gary.myapplication.preferences.Preferences.TAB_TYPE_LOCALENGLISH;
import static com.newsenglish.gary.myapplication.preferences.Preferences.TAB_TYPE_NEWSWORD;
import static com.newsenglish.gary.myapplication.preferences.Preferences.TAB_TYPE_SIXMIN;

public class WebActivity extends AppCompatActivity implements View.OnClickListener {
    private Context context;

    private String webTitleStr = "";
    private String webPicurl = "";
    private String webTimeStr = "";
    private String webtypeStr = "";
    private int webType = 0;
    private long click_time = 0;

    private ImageView webPic;
    private TextView webTitle;
    private TextView webTime;
    private TextView nowTime;
    private TextView fullTime;
    private ImageView backImg;
    private ImageView playBtn;
    private MyPlayer player; // 播放器
    private SeekBar musicProgress; // 音乐进度

    private String url = "";

    private TextView enAndCh;
    private TextView englishTxt;
    private TextView allTxt;
    private boolean isPlay = false;
    Handler handler = new Handler();
    private LinearLayout webLayout;
    private ProgressBar progressBar;
    //设置菜单
    private ListView weblistView;
    private ArrayAdapter adapter;
    private TextView webMenu;
    private LinearLayout webItemLayout;
    private boolean isOpen = false;
    private String[] webname = {"BBC六分钟英语", "BBC地道英语", "BBC新闻", "BBC新闻词汇"};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_web);
        context = WebActivity.this;
        initView();
        initEvent();

    }

    private void setView() {
        Glide.with(this).load(webPicurl).into(webPic);
        webTitle.setText(webTitleStr);
        switch (webType) {
            case TAB_TYPE_SIXMIN: {
                webtypeStr = "BBC六分钟英语";
            }
            break;
            case TAB_TYPE_LOCALENGLISH: {
                webtypeStr = "BBC地道英语";
            }
            break;
            case TAB_TYPE_BBCNEWS: {
                webtypeStr = "BBC新闻";
            }
            break;
            case TAB_TYPE_NEWSWORD: {
                webtypeStr = "BBC新闻词汇";
            }
            break;
        }
        webTime.setText(webtypeStr + "\t\t\t" + webTimeStr);
    }

    private void initEvent() {
        playBtn.setOnClickListener(this);
        enAndCh.setOnClickListener(this);
        englishTxt.setOnClickListener(this);
        allTxt.setOnClickListener(this);
        webMenu.setOnClickListener(this);
        backImg.setOnClickListener(this);
    }

    private void initView() {
        //获取数据
        webTitleStr = getIntent().getStringExtra("webtitle");
        webPicurl = getIntent().getStringExtra("webpic");
        webTimeStr = getIntent().getStringExtra("webtime");
        webType = getIntent().getIntExtra("webtype", 0);
        url = "http://staticvip.iyuba.com/sounds/minutes/" + getIntent().getStringExtra("webmp3");
        //初始化控件
        musicProgress = (SeekBar) findViewById(R.id.progressBar);
        webLayout = (LinearLayout) findViewById(R.id.web_layout);
        webLayout.setVisibility(View.INVISIBLE);
        progressBar = (ProgressBar) findViewById(R.id.progress);
        musicProgress.setOnSeekBarChangeListener(new SeekBarChangeEvent());
        playBtn = (ImageView) findViewById(R.id.play);
        webPic = (ImageView) findViewById(R.id.web_pic);
        webTitle = (TextView) findViewById(R.id.web_title);
        webTime = (TextView) findViewById(R.id.type_date);
        enAndCh = (TextView) findViewById(R.id.en_ch);
        selectTxt(enAndCh);
        englishTxt = (TextView) findViewById(R.id.en_txt);
        allTxt = (TextView) findViewById(R.id.all_txt);
        backImg = (ImageView) findViewById(R.id.back_tomain);
        backImg.setVisibility(View.VISIBLE);

        webMenu = (TextView) findViewById(R.id.home);
        webMenu.setText("Menu");

        weblistView = (ListView) findViewById(R.id.web_list);
        webItemLayout = (LinearLayout) findViewById(R.id.web_item_layout);
        adapter = new ArrayAdapter(context, R.layout.name_item, webname);
        weblistView.setAdapter(adapter);
        setView();

        progressBar.setVisibility(View.GONE);
        webLayout.setVisibility(View.VISIBLE);
        //初始化音乐播放器
        nowTime = (TextView) findViewById(R.id.nowtime);
        fullTime = (TextView) findViewById(R.id.fulltim);
        player = new MyPlayer(musicProgress, nowTime, fullTime);
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                handler.post(playurlThread);
            }
        });

    }

    Runnable playurlThread = new Runnable() {
        @Override
        public void run() {
            player.playUrl(url);
        }
    };

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.play: {
                if (isPlay == false) {
                    playBtn.setImageResource(R.mipmap.pause);
                    player.play();
                    isPlay = true;
                } else {
                    playBtn.setImageResource(R.mipmap.play);
                    player.pause();
                    isPlay = false;
                }
            }
            break;
            case R.id.en_ch: {
                clearAllTxt();
                selectTxt(enAndCh);
            }
            break;
            case R.id.en_txt: {
                clearAllTxt();
                selectTxt(englishTxt);
            }
            break;
            case R.id.all_txt: {
                clearAllTxt();
                selectTxt(allTxt);
            }
            break;
            case R.id.back_tomain: {
                this.finish();
                backImg.setVisibility(View.GONE);
            }
            break;
            case R.id.home: {
                if (System.currentTimeMillis() - click_time > DEFAULT_DURATION) {
                    if (isOpen == false) {
                        isOpen = true;
                        showList();
                    } else {
                        isOpen = false;
                        hideList();
                    }
                }
            }
            break;
        }
    }

    private void clearAllTxt() {
        enAndCh.setBackgroundColor(getResources().getColor(R.color.unselect_color));
        englishTxt.setBackgroundColor(getResources().getColor(R.color.unselect_color));
        allTxt.setBackgroundColor(getResources().getColor(R.color.unselect_color));
    }

    private void selectTxt(TextView txt) {
        txt.setBackgroundColor(getResources().getColor(R.color.select_color));
    }

    //展示菜单
    private void showList() {
        ObjectAnimator animaa = ObjectAnimator.ofFloat(webItemLayout,
                "translationY", 0f, weblistView.getMeasuredHeight() * 1.0f)
                .setDuration(500);
        animaa.start();
    }

    //隐藏菜单
    private void hideList() {
        ObjectAnimator anim = ObjectAnimator.ofFloat(webItemLayout, "translationY", weblistView.getMeasuredHeight() * 1.0f, 0.0F)
                .setDuration(500);
        anim.start();
    }

    // 进度改变
    class SeekBarChangeEvent implements SeekBar.OnSeekBarChangeListener {
        int progress;

        @Override
        public void onProgressChanged(SeekBar seekBar, int progress,
                                      boolean fromUser) {
            // 原本是(progress/seekBar.getMax())*player.mediaPlayer.getDuration()
            this.progress = progress * player.mediaPlayer.getDuration()
                    / seekBar.getMax();
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            // seekTo()的参数是相对与影片时间的数字,而不是与seekBar.getMax()相对的数字
            player.mediaPlayer.seekTo(progress);
        }

    }

    private void showProgress() {

        progressBar.setVisibility(View.VISIBLE);

    }

    private void hideProgress() {
        progressBar.setVisibility(View.GONE);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (player != null) {
            player.stop();
            player = null;
            handler.removeCallbacks(playurlThread);
        }
    }

}


text:
<?php

namespace sisconee\AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * Servicio
 *
 * @ORM\Table(name="servicio", uniqueConstraints={@ORM\UniqueConstraint(name="nombre_UNIQUE", columns={"nombre"}), @ORM\UniqueConstraint(name="codcliente_EE_UNIQUE", columns={"codcliente_EE"}), @ORM\UniqueConstraint(name="codRF_UNIQUE", columns={"codRF"})}, indexes={@ORM\Index(name="fk_servicio_tipo_servicio1", columns={"id_tipo_servicio"}), @ORM\Index(name="fk_servicio_entidad1", columns={"id_entidad"}), @ORM\Index(name="fk_servicio_municipio", columns={"id_municipio"}), @ORM\Index(name="fk_servicio_provincia1", columns={"id_provincia"})})
 * @ORM\Entity(repositoryClass="ServicioRepository")
 */
class Servicio
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer", nullable=false)
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="nombre", type="string", length=100, nullable=true)
     */
    private $nombre;

    /**
     * @var string
     *
     * @ORM\Column(name="codcliente_EE", type="string", length=10, nullable=true)
     */
    private $codClienteEE;

    /**
     * @var string
     *
     * @ORM\Column(name="codRF", type="string", length=6, nullable=true)
     */
    private $codRutaFolio;

    /**
     * @var boolean
     *
     * @ORM\Column(name="horariopico", type="boolean", nullable=true)
     */
    private $horarioPico;

    /**
     * @var boolean
     *
     * @ORM\Column(name="activo", type="boolean", nullable=true)
     */
    private $activo;

    /**
     * @var \Entidad
     *
     * @ORM\ManyToOne(targetEntity="Entidad")
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="id_entidad", referencedColumnName="id")
     * })
     */
    private $entidad;

    /**
     * @var \Municipio
     *
     * @ORM\ManyToOne(targetEntity="Municipio")
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="id_municipio", referencedColumnName="id")
     * })
     */
    private $municipio;

    /**
     * @var \Provincia
     *
     * @ORM\ManyToOne(targetEntity="Provincia")
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="id_provincia", referencedColumnName="id")
     * })
     */
    private $provincia;

    /**
     * @var \TipoServicio
     *
     * @ORM\ManyToOne(targetEntity="TipoServicio", inversedBy="servicios")
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="id_tipo_servicio", referencedColumnName="id")
     * })
     */
    private $tipoServicio;

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set id
     *
     * @param integer $id
     * @return Servicio
     */
    public function setId($id)
    {
        $this->id = $id;

        return $this;
    }

    /**
     * Set nombre
     *
     * @param string $nombre
     * @return Servicio
     */
    public function setNombre($nombre)
    {
        $this->nombre = $nombre;

        return $this;
    }

    /**
     * Get nombre
     *
     * @return string
     */
    public function getNombre()
    {
        return $this->nombre;
    }

    /**
     * Set codClienteEE
     *
     * @param string $codClienteEE
     * @return Servicio
     */
    public function setCodClienteEE($codClienteEE)
    {
        $this->codClienteEE = $codClienteEE;

        return $this;
    }

    /**
     * Get codClienteEE
     *
     * @return string
     */
    public function getCodClienteEE()
    {
        return $this->codClienteEE;
    }

    /**
     * Set codRutaFolio
     *
     * @param string $codRutaFolio
     * @return Servicio
     */
    public function setCodRutaFolio($codRutaFolio)
    {
        $this->codRutaFolio = $codRutaFolio;

        return $this;
    }

    /**
     * Get codRutaFolio
     *
     * @return string
     */
    public function getCodRutaFolio()
    {
        return $this->codRutaFolio;
    }

    /**
     * Set horarioPico
     *
     * @param boolean $horarioPico
     * @return Servicio
     */
    public function setHorarioPico($horarioPico)
    {
        $this->horarioPico = $horarioPico;

        return $this;
    }

    /**
     * Get horarioPico
     *
     * @return boolean
     */
    public function getHorarioPico()
    {
        return $this->horarioPico;
    }

    /**
     * Set activo
     *
     * @param boolean $activo
     * @return Servicio
     */
    public function setActivo($activo)
    {
        $this->activo = $activo;

        return $this;
    }

    /**
     * Get activo
     *
     * @return boolean
     */
    public function getActivo()
    {
        return $this->activo;
    }

    /**
     * Set entidad
     *
     * @param \sisconee\AppBundle\Entity\Entidad $entidad
     * @return Servicio
     */
    public function setEntidad(\sisconee\AppBundle\Entity\Entidad $entidad = null)
    {
        $this->entidad = $entidad;

        return $this;
    }

    /**
     * Get entidad
     *
     * @return \sisconee\AppBundle\Entity\Entidad
     */
    public function getEntidad()
    {
        return $this->entidad;
    }

    /**
     * Set municipio
     *
     * @param \sisconee\AppBundle\Entity\Municipio $municipio
     * @return Servicio
     */
    public function setMunicipio(\sisconee\AppBundle\Entity\Municipio $municipio = null)
    {
        $this->municipio = $municipio;

        return $this;
    }

    /**
     * Get municipio
     *
     * @return \sisconee\AppBundle\Entity\Municipio
     */
    public function getMunicipio()
    {
        return $this->municipio;
    }

    /**
     * Set provincia
     *
     * @param \sisconee\AppBundle\Entity\Provincia $provincia
     * @return Servicio
     */
    public function setProvincia(\sisconee\AppBundle\Entity\Provincia $provincia = null)
    {
        $this->provincia = $provincia;

        return $this;
    }

    /**
     * Get provincia
     *
     * @return \sisconee\AppBundle\Entity\Provincia
     */
    public function getProvincia()
    {
        return $this->provincia;
    }

    /**
     * Set tipoServicio
     *
     * @param \sisconee\AppBundle\Entity\TipoServicio $tipoServicio
     * @return Servicio
     */
    public function setTipoServicio(\sisconee\AppBundle\Entity\TipoServicio $tipoServicio = null)
    {
        $this->tipoServicio = $tipoServicio;

        return $this;
    }

    /**
     * Get tipoServicio
     *
     * @return \sisconee\AppBundle\Entity\TipoServicio
     */
    public function getTipoServicio()
    {
        return $this->tipoServicio;
    }

    public function __toString()
    {
        return $this->getNombre();
    }
}


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

namespace GRA.Controllers.ViewModel.Avatar
{
    public class ShareViewModel
    {
        public string AvatarId { get; set; }
        public string AvatarImageUrl { get; set; }
        public string FacebookShareUrl { get; set; }
        public string TwitterShareUrl { get; set; }
    }
}


text:
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using Frontenac.Blueprints.Contracts;
using Frontenac.Blueprints.Util;

namespace Frontenac.Blueprints.Impls.TG
{
    [Serializable]
    internal class TinkerIndex : IIndex
    {
        protected readonly Type IndexClass;
        protected readonly string IndexName;

        internal ConcurrentDictionary<string, ConcurrentDictionary<object, ConcurrentDictionary<string, IElement>>> Index =
            new ConcurrentDictionary<string, ConcurrentDictionary<object, ConcurrentDictionary<string, IElement>>>();

        public TinkerIndex(string indexName, Type indexClass)
        {
            if (indexClass == null)
                throw new ArgumentNullException(nameof(indexClass));

            if (!(typeof(IVertex).IsAssignableFrom(indexClass) ||
                  typeof(IEdge).IsAssignableFrom(indexClass)))
                throw new ArgumentException("indexClass must be assignable from IVertex of IEdge");

            IndexName = indexName;
            IndexClass = indexClass;
        }

        public string Name
        {
            get { return IndexName; }
        }

        public Type Type
        {
            get { return IndexClass; }
        }

        public void Put(string key, object value, IElement element)
        {
            IndexContract.ValidatePut(key, value, element);

            var keyMap = Index.Get(key);
            if (keyMap == null)
            {
                keyMap = new ConcurrentDictionary<object, ConcurrentDictionary<string, IElement>>();
                Index.Put(key, keyMap);
            }
            var objects = keyMap.Get(value);
            if (null == objects)
            {
                objects = new ConcurrentDictionary<string, IElement>();
                keyMap.Put(value, objects);
            }
            objects.TryAdd(element.Id.ToString(), element);
        }

        public IEnumerable<IElement> Get(string key, object value)
        {
            IndexContract.ValidateGet(key, value);

            var keyMap = Index.Get(key);
            if (null == keyMap)
                return new WrappingCloseableIterable<IElement>(Enumerable.Empty<IElement>());

            var set = keyMap.Get(value);
            return null == set
                       ? new WrappingCloseableIterable<IElement>(Enumerable.Empty<IElement>())
                       : new WrappingCloseableIterable<IElement>(new List<IElement>(set.Values));
        }

        public IEnumerable<IElement> Query(string key, object query)
        {
            throw new NotImplementedException();
        }

        public long Count(string key, object value)
        {
            IndexContract.ValidateCount(key, value);

            var keyMap = Index.Get(key);
            if (null == keyMap)
                return 0;
            var set = keyMap.Get(value);
            return null == set ? 0 : set.LongCount();
        }

        public void Remove(string key, object value, IElement element)
        {
            IndexContract.ValidateRemove(key, value, element);

            var keyMap = Index.Get(key);
            if (null != keyMap)
            {
                var objects = keyMap.Get(value);
                if (null != objects)
                {
                    IElement removedElement;
                    objects.TryRemove(element.Id.ToString(), out removedElement);
                    if (objects.Count == 0)
                    {
                        ConcurrentDictionary<string, IElement> removedElements;
                        keyMap.TryRemove(value, out removedElements);
                    }
                }
            }
        }

        public void RemoveElement(IElement element)
        {
            if (element == null)
                throw new ArgumentNullException(nameof(element));

            if (!IndexClass.IsInstanceOfType(element)) return;

            foreach (var map in Index.Values)
            {
                foreach (var set in map.Values)
                {
                    IElement removedElement;
                    set.TryRemove(element.Id.ToString(), out removedElement);
                }
            }
        }

        public override string ToString()
        {
            return this.IndexString();
        }
    }
}