text:
KWFutureObject * dispatch_async_and_return_exception_future(dispatch_block_t block) {
	NSException __block * exception = nil;
	dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
		@try {
			block();
		} @catch (NSException * e) {
			exception = e;
		}
	});
	return expectFutureValue(exception);
}

SPEC_BEGIN(INModelProviderTests)

INModelProvider __block * provider;
beforeEach(^{
	provider = [[INModelProvider alloc] initWithClass:[INMessage class] andNamespaceID:@"1" andUnderlyingPredicate:nil];
});

describe(@"initWithClass:andNamespaceID:andUnderlyingPredicate:", ^{
	it(@"should register the provider for database updates", ^{
		NSHashTable * observers = [[INDatabaseManager shared] observers];
		[[theValue([observers containsObject: provider]) should] beTrue];
	});
});

describe(@"setItemSortDescriptors:", ^{
	it(@"should trigger an eventual refresh", ^{
		NSSortDescriptor * descriptor = [NSSortDescriptor sortDescriptorWithKey: @"subject" ascending:NO];
		[provider setItemSortDescriptors: @[descriptor]];
		[[provider shouldEventually] receive:@selector(refresh)];
	});
	it(@"should not refresh if the sort descriptor is identical to the current one", ^{
		[provider setItemSortDescriptors: @[[NSSortDescriptor sortDescriptorWithKey: @"subject" ascending:NO]]];
		[provider refresh]; // clears the queued call to 'refresh'
		[provider setItemSortDescriptors: @[[NSSortDescriptor sortDescriptorWithKey: @"subject" ascending:NO]]];
		[[provider shouldNotEventually] receive:@selector(refresh)];
	});
});

describe(@"setItemFilterPredicate:", ^{
	it(@"should trigger an eventual refresh", ^{
		[provider setItemFilterPredicate: [NSPredicate predicateWithFormat:@"ID = 4"]];
		[[provider shouldEventually] receive:@selector(refresh)];
	});
	it(@"should not refresh if the predicate is identical to the current one", ^{
		[provider setItemFilterPredicate: [NSPredicate predicateWithFormat:@"ID = 4"]];
		[provider refresh]; // clears the queued call to 'refresh'
		[provider setItemFilterPredicate: [NSPredicate predicateWithFormat:@"ID = 4"]];
		[[provider shouldNotEventually] receive:@selector(refresh)];
	});
});

describe(@"setItemRange:", ^{
	it(@"should trigger an eventual refresh", ^{
		[provider setItemRange: NSMakeRange(0, 100)];
		[[provider shouldEventually] receive:@selector(refresh)];
	});
	it(@"should not refresh if the range is identical to the current one", ^{
		[provider setItemRange:NSMakeRange(0, 100)];
		[provider refresh]; // clears the queued call to 'refresh'
		[provider setItemRange:NSMakeRange(0, 100)];
		[[provider shouldNotEventually] receive:@selector(refresh)];
	});
});

describe(@"refresh", ^{
	it(@"should fetch items from cache", ^{
		[[provider should] receive: @selector(fetchFromCache)];
		[provider refresh];
	});

	context(@"when cache policy is INModelProviderCacheThenNetwork", ^{
		it(@"should trigger a fetch from the API", ^{
			[provider setItemCachePolicy: INModelProviderCacheThenNetwork];
			[[provider should] receive:@selector(fetchFromAPI)];
			[provider refresh];
		});
	});

	context(@"when cache policy is INModelProviderCacheOnly", ^{
		it(@"should not trigger a fetch from the API", ^{
			[provider setItemCachePolicy: INModelProviderCacheOnly];
			[[provider shouldNot] receive:@selector(fetchFromAPI)];
			[provider refresh];
		});
	});
});

describe(@"fetchPredicate", ^{
	it(@"should return a predicate that includes the namespace constraint", ^{
		NSPredicate * predicate = [provider fetchPredicate];
		[[theValue([predicate containsOrMatches: @"namespaceID == \"1\""]) should] beTrue];
	});

	it(@"should return a predicate that includes the underlying predicate if one exists", ^{
		NSPredicate * underlying = [NSPredicate predicateWithFormat:@"threadID = %@", @"2"];
		provider = [[INModelProvider alloc] initWithClass:[INMessage class] andNamespaceID:@"1" andUnderlyingPredicate: underlying];

		NSPredicate * predicate = [provider fetchPredicate];
		[[theValue([predicate containsOrMatches: @"threadID == \"2\""]) should] beTrue];
	});

	it(@"should return a predicate that includes the item filter predicate", ^{
		NSPredicate * filterPredicate = [NSPredicate predicateWithFormat:@"subject LIKE %@", @"Happy Day"];
		[provider setItemFilterPredicate: filterPredicate];

		NSPredicate * predicate = [provider fetchPredicate];
		[[theValue([predicate containsOrMatches: @"subject LIKE \"Happy Day\""]) should] beTrue];
	});

	it(@"should return a compound predicate ANDing the others if more than one is specified", ^{
		NSPredicate * underlyingPredicate = [NSPredicate predicateWithFormat:@"threadID = %@", @"2"];
		provider = [[INModelProvider alloc] initWithClass:[INMessage class] andNamespaceID:@"1" andUnderlyingPredicate: underlyingPredicate];

		NSPredicate * filterPredicate = [NSPredicate predicateWithFormat:@"subject LIKE %@", @"Happy Day"];
		[provider setItemFilterPredicate: filterPredicate];

		NSCompoundPredicate * result = (NSCompoundPredicate *)[provider fetchPredicate];
		[[theValue([result compoundPredicateType]) should] equal: theValue((NSAndPredicateType))];
		[[[result subpredicates] should] contain: filterPredicate];
		[[[result subpredicates] should] contain: underlyingPredicate];
	});
});

describe(@"managerDidPersistModels:", ^{
	NSMutableArray __block * currentItems;
	NSMutableArray __block * savedItems;
	beforeEach(^{
		currentItems = [NSMutableArray array];
		savedItems = [NSMutableArray array];

		for (int ii = 0; ii < 10; ii ++) {
			[currentItems addObject: [[INMessage alloc] init]];
		}
		[provider setItems: currentItems];
		[savedItems addObject: currentItems[2]];
	});

	it(@"should only be run on the main thread", ^{
		KWFutureObject * exception = dispatch_async_and_return_exception_future(^{
			[provider managerDidPersistModels: @[]];
		});
		[[exception shouldEventually] beNonNil];
	});

	context(@"if the delegate responds to provider:dataAltered:", ^{
		it(@"should send changes", ^{
			id delegateMock = [KWMock mockForProtocol: @protocol(INModelProviderDelegate)];
			[[delegateMock should] receive:@selector(provider:dataAltered:)];
			[provider setDelegate: delegateMock];
			[provider managerDidPersistModels: savedItems];
		});
	});

	context(@"if the delegate only responds to providerDataChanged:", ^{
		it(@"should call that instead", ^{
			// FAILING:
			// Filed bug report: https://github.com/allending/Kiwi/issues/511

			id delegateMock = [KWMock mock];
			[delegateMock stub: @selector(providerDataChanged:)];
			BOOL responds = [delegateMock respondsToSelector: @selector(providerDataChanged:)];

			[[delegateMock should] receive:@selector(providerDataChanged:)];
			[provider setDelegate: delegateMock];
			[provider managerDidPersistModels: savedItems];
		});
	});
});

describe(@"managerDidUnpersistModels:", ^{

	NSMutableArray __block * items = nil;
	NSMutableArray __block * twoItems = nil;
	beforeEach(^{
		items = [NSMutableArray array];
		for (int ii = 0; ii < 5; ii ++) {
			[items addObject: [[INMessage alloc] init]];
		}

		twoItems = [NSMutableArray array];
		[twoItems addObject: items[1]];
		[twoItems addObject: items[4]];

		// not usually called directly, but we want to set up the collection to remove items
		[provider setItems: items];
	});

	it(@"should only be run on the main thread", ^{
		KWFutureObject * exception = dispatch_async_and_return_exception_future(^{
			[provider managerDidUnpersistModels: @[]];
		});
		[[exception shouldEventually] beNonNil];
	});

	context(@"if the delegate responds to provider:dataAltered:", ^{
		it(@"should send a correct set of changes", ^{
			id delegateMock = [KWMock mockForProtocol: @protocol(INModelProviderDelegate)];
			KWCaptureSpy * changesSpy = [delegateMock captureArgument:@selector(provider:dataAltered:) atIndex:0];
			[provider setDelegate: delegateMock];
			[provider managerDidUnpersistModels: twoItems];

			INModelProviderChangeSet * changeSet = [changesSpy argument];
			[[[changeSet changes] should] haveCountOf: 2];

			INModelProviderChange * change1 = [changeSet changes][0];
			[[[change1 item] should] equal: twoItems[0]];
			[[theValue([change1 index]) should] equal: theValue(1)];

			INModelProviderChange * change2 = [changeSet changes][1];
			[[[change2 item] should] equal: twoItems[1]];
			[[theValue([change2 index]) should] equal: theValue(4)];
		});

		it(@"should not send an empty change set", ^{
			NSMutableArray * twoItemsNotInSet = [NSMutableArray array];
			for (int ii = 0; ii < 2; ii ++)
				[twoItemsNotInSet addObject: [[INMessage alloc] init]];

			id delegateMock = [KWMock mockForProtocol: @protocol(INModelProviderDelegate)];
			[[delegateMock shouldNot] receive: @selector(provider:dataAltered:)];
			[provider managerDidUnpersistModels: twoItemsNotInSet];
		});
	});

	context(@"if the delegate only responds to providerDataChanged:", ^{
		it(@"should call providerDataChanged:", ^{
			id delegateMock = [KWMock mock];
			[delegateMock expect: @selector(providerDataChanged:)];

			[provider setDelegate: delegateMock];
			[provider managerDidUnpersistModels: twoItems];
		});
	});
});

describe(@"managerDidReset", ^{
	it(@"should only be run on the main thread", ^{
		KWFutureObject * exception = dispatch_async_and_return_exception_future(^{
			[provider managerDidReset];
		});
		[[exception shouldEventually] beNonNil];
	});

	it(@"should reload the items array", ^{
		NSMutableArray * oldItems = [NSMutableArray array];
		[oldItems addObject: [[INMessage alloc] init]];
		[provider setItems: oldItems];
		[provider managerDidReset];

		[[expectFutureValue([provider items]) shouldNotEventually] beIdenticalTo: oldItems];
	});
});

SPEC_END


text:
package libra.preprocess.stage1;

import java.io.IOException;
import java.util.Collection;
import java.util.Iterator;
import libra.common.hadoop.io.datatypes.IntArrayWritable;
import libra.common.hadoop.io.datatypes.CompressedSequenceWritable;
import libra.common.helpers.FileSystemHelper;
import libra.common.report.Report;
import libra.common.hadoop.io.format.sequence.SequenceFileInputFormat;
import libra.preprocess.common.PreprocessorConfigException;
import libra.preprocess.common.PreprocessorRoundConfig;
import libra.preprocess.common.filetable.FileTable;
import libra.preprocess.common.helpers.KmerFilterHelper;
import libra.preprocess.common.kmerfilter.KmerFilter;
import libra.preprocess.common.kmerfilter.KmerFilterPart;
import libra.preprocess.common.kmerfilter.KmerFilterPartTable;
import libra.preprocess.common.kmerfilter.KmerFilterTable;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.NullOutputFormat;

/**
 *
 * @author iychoi
 */
public class KmerFilterBuilder {

    private static final Log LOG = LogFactory.getLog(KmerFilterBuilder.class);

    public KmerFilterBuilder() {

    }

    private void validatePreprocessorConfig(PreprocessorRoundConfig ppConfig) throws PreprocessorConfigException {
        if(ppConfig.getSamplePath().size() <= 0) {
            throw new PreprocessorConfigException("cannot find input sample path");
        }

        if(ppConfig.getFileTable() == null || ppConfig.getFileTable().samples() <= 0) {
            throw new PreprocessorConfigException("cannot find input sample path");
        }

        if(ppConfig.getKmerSize() <= 0) {
            throw new PreprocessorConfigException("invalid kmer size");
        }

        if(ppConfig.getKmerFilterPath()== null) {
            throw new PreprocessorConfigException("cannot find kmer filter path");
        }
    }

    public int runJob(Configuration conf, PreprocessorRoundConfig ppConfig) throws Exception {
        // check config
        validatePreprocessorConfig(ppConfig);

        Job job = Job.getInstance(conf, "Libra - Building Kmer Filter");
        conf = job.getConfiguration();

        // set user configuration
        ppConfig.saveTo(conf);

        Report report = new Report();

        job.setJarByClass(KmerFilterBuilder.class);

        // Mapper
        job.setMapperClass(KmerFilterBuilderMapper.class);
        job.setInputFormatClass(SequenceFileInputFormat.class);
        job.setMapOutputKeyClass(CompressedSequenceWritable.class);
        job.setMapOutputValueClass(IntArrayWritable.class);

        // Combiner
        job.setCombinerClass(KmerFilterBuilderCombiner.class);

        // Partitioner
        job.setPartitionerClass(KmerFilterBuilderPartitioner.class);

        // Reducer
        job.setReducerClass(KmerFilterBuilderReducer.class);

        // Specify key / value
        job.setOutputKeyClass(NullWritable.class);
        job.setOutputValueClass(NullWritable.class);

        // Inputs
        Path[] inputFiles = FileSystemHelper.makePathFromString(conf, ppConfig.getFileTable().getSamples());
        FileInputFormat.addInputPaths(job, FileSystemHelper.makeCommaSeparated(inputFiles));

        LOG.info("Input sample files : " + inputFiles.length);
        for(Path inputFile : inputFiles) {
            LOG.info("> " + inputFile.toString());
        }

        job.setOutputFormatClass(NullOutputFormat.class);

        // reducers
        int reducers = conf.getInt("mapred.reduce.tasks", 1);
        if(ppConfig.getTaskNum() > 0) {
            reducers = ppConfig.getTaskNum();
        }

        job.setNumReduceTasks(reducers);
        LOG.info("# of Reducers : " + reducers);

        // Execute job and return status
        boolean result = job.waitForCompletion(true);

        // commit results
        if(result) {
            commit(new Path(ppConfig.getKmerFilterPath()), ppConfig.getFileTable(), conf);
        }

        report.addJob(job);

        // report
        if(ppConfig.getReportPath() != null && !ppConfig.getReportPath().isEmpty()) {
            report.writeTo(ppConfig.getReportPath());
        }

        return result ? 0 : 1;
    }

    private void commit(Path filterPath, FileTable fileTable, Configuration conf) throws IOException {
        String filterTableFileName = KmerFilterHelper.makeKmerFilterTableFileName(fileTable.getName());
        Path filterTableOutputFile = new Path(filterPath, filterTableFileName);

        LOG.info("Creating a kmer filter table file : " + filterTableFileName);

        Collection<String> samples = fileTable.getSamples();

        KmerFilterPart[] filterParts = new KmerFilterPart[fileTable.samples()];
        KmerFilter[] filter = new KmerFilter[fileTable.samples()];
        Iterator<String> iterator = samples.iterator();
        for(int i=0;i<fileTable.samples();i++) {
            String sample_name = iterator.next();
            filterParts[i] = new KmerFilterPart(sample_name);
            filter[i] = new KmerFilter(sample_name);
        }

        Path[] kmerFilterTablePartFiles = KmerFilterHelper.getKmerFilterPartTableFilePaths(conf, filterPath);
        for(Path filterTablePartFile : kmerFilterTablePartFiles) {
            FileSystem fs = filterTablePartFile.getFileSystem(conf);
            KmerFilterPartTable table = KmerFilterPartTable.createInstance(fs, filterTablePartFile);
            int idx = 0;
            for(KmerFilterPart filterPart : table.getFilterPart()) {
                filterParts[idx].incrementTotalKmers(filterPart.getTotalKmers());
                filterParts[idx].incrementUniqueKmers(filterPart.getUniqueKmers());
                filterParts[idx].incrementSumOfSquare(filterPart.getSumOfSquare());
                idx++;
            }
        }

        KmerFilterTable filterTable = new KmerFilterTable();
        filterTable.setName(fileTable.getName());

        for(int j=0;j<fileTable.samples();j++) {
            filter[j].setTotalKmers(filterParts[j].getTotalKmers());
            filter[j].setUniqueKmers(filterParts[j].getUniqueKmers());
            filter[j].setSumOfSquare(filterParts[j].getSumOfSquare());

            filterTable.addFilter(filter[j]);
        }

        // save
        FileSystem outputFileSystem = filterTableOutputFile.getFileSystem(conf);

        filterTable.saveTo(outputFileSystem, filterTableOutputFile);

        // delete part files
        for(Path filterTablePartFile : kmerFilterTablePartFiles) {
            FileSystem fs = filterTablePartFile.getFileSystem(conf);
            fs.delete(filterTablePartFile, true);
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
layout: post
title: JSON Server
excerpt: Accelerate your prototyping process by mocking your APIs using JSON Server
authors:
    - kelfarsaoui
lang: en
permalink: /json-server/
categories:
    - JSON
    - API
    - NodeJS
tags:
    - JSON
    - API
    - NodeJS
cover: /assets/2017-08-16-json-server/cover.jpg
---

Hello, Today I'm going to talk about [json-server](https://github.com/typicode/json-server){:rel="nofollow noreferrer"}, what is it? why use it? and especially how to use it?

`json-server` is a cool `npm` module, that provides an [Express](https://github.com/expressjs/express){:rel="nofollow noreferrer"} server that serves a JSON API.

## Why use it?

Let's say you are starting to work on your awesome (Javascript, PHP, IOS, Android, … whatever) app, and you want to consume remote data of some, not finished yet, API. The first step you take consists in setting up some mocks, either hard coded in some constant (please, don't do this), or using a static JSON file, which will be a pain in the neck. Why? You're a good developer who likes to do the right thing. You want to test your app against data updates. You want to perform HTTP requests (like `GET`, `POST` …etc.), and you want to persist your updates. Unfortunately, you can't do all of this using a static file, you need to look for a way to make it dynamic. So, unless your pal who's developing the API has finished their work, you're gonna need some serious help.

Here comes `json-server`, it allows you to mock the API, and provide dynamic access to data. By dynamic, I mean that we can read, add, update, and delete data (`GET`, `POST`, `PUT`, `PATCH`, `DELETE`).

It provides common URL use cases like:
- [Routes](#routes) (`/articles/1`)
- [Filters](#filters) (`/articles/1/comments?author.username=rpierlot`)
- [Pagination](#pagination) (`/articles?_page=2&_limit=10`)
- [Full text search](#full-text-search) (`/articles?q=graphql`)
- [Relationships](#relationships) (`/articles?_embed=comments`)

and other miscellaneous stuff like:
- `CORS` & `JSONP`
- Ability to access remote schemas
- [Randomly generated data](#random-data)
- [Custom routes](#custom-routes)
- [Middlewares](#middlewares)
- [Ability to use `json-server` as a module in your NodeJS server](#nodejs-module)

Okay, let's get to it.

## How to use it?

This will take less than 5 minutes!

### Requirements

- NodeJS & `npm`
- An API consumer (Your code, `curl`, postman, or simply your browser)

### Installation

It's pretty straightforward to set up:

```bash
$ npm install -g json-server

# Or with yarn
$ yarn global add json-server

# Then create a folder in which we will put our db.json file:
$ mkdir blog && cd $_

# create our schema file
$ touch db.json
```

To fill it in, we can either do it by hand or use a random json generator (my favorite is [json-generator](http://json-generator.com)){:rel="nofollow noreferrer"}

```json
{
  "articles": [
    {
      "id": 1,
      "title": "Build an API using GO",
      "authorId": 2
    },
    {
      "id": 2,
      "title": "Build an API using API Platform",
      "authorId": 1
    }
  ],
  "comments": [
    {
      "id": 1,
      "body": "Brilliant",
      "articleId": 1
    },
    {
      "id": 2,
      "body": "Awesome",
      "articleId": 2
    }
  ],
  "authors": [
    {
      "id": 1,
      "username": "rpierlot",
      "title": "Romain Pierlot"
    },
    {
      "id": 2,
      "username": "qneyrat",
      "title": "Quentin Neyrat"
    }
  ]
}
```

Now we can run `json-server` so that we can access the endpoints that `json-server` created for us

```bash
$ json-server db.json

  \{^_^}/ hi!

  Loading db.json
  Done

  Resources
  http://localhost:3000/articles
  http://localhost:3000/comments
  http://localhost:3000/authors

  Home
  http://localhost:3000

  Type s + enter at any time to create a snapshot of the database
```

Great, we've set up our API mock. Now we can test our endpoints:

```bash
$ curl http://localhost:3000/articles
[
  {
    "id": 1,
    "title": "Build an API using GO",
    "authorId": 2
  },
  {
    "id": 2,
    "title": "Build an API using API Platform",
    "authorId": 1
  }
]

$ curl http://localhost:3000/articles/1
{
  "id": 1,
  "title": "Build an API using GO",
  "authorId": 2
}
```

### Routes

We can use almost all kinds of URIs to perform requests:
For example, to insert (create) a new author, we might use:
`POST http://localhost:3000/authors`

```bash
$ curl --data-urlencode "title=Vincent Composieux" --data "username=vcomposieux" http://localhost:3000/authors
{
  "title": "Vincent Composieux",
  "username": "vcomposieux",
  "id": 3
}
```

To read an article with article id 2: `GET http://localhost:3000/articles/2`. The same URI would be used for `PUT` and `DELETE`, to update and delete, respectively.

Now, when it comes to creating a new comment in an article, one option might be: `POST http://localhost:3000/comments` And that could work to create a comment, but it's arguably outside the context of an article.

As a matter of fact, this URI is not as intuitive as it could be. It could be argued that the following URI would offer better clarity: `POST http://localhost:3000/articles/1/comments`. Now we know we're creating a comment in article id 1.

```bash
$ curl --data-urlencode "body=Cool article ;-)" http://localhost:3000/articles/1/comments
{
  "body": "Cool article ;-)",
  "articleId": 1,
  "id": 4
}
```

Same with creating an article by author id 3:

```bash
$ curl --data-urlencode "title=GraphQL" http://localhost:3000/authors/3/articles
{
  "title": "GraphQL",
  "authorId": "3",
  "id": 3
}
```

#### Filters, sort & operators

**Filtering** is done using query parameters: `GET http://localhost:3000/articles?title=GraphQL`.

**Sort** is as easy as adding `_sort` & `_order` (`asc` & `desc`) query parameters:

`GET http://localhost:3000/articles?_sort=likes`

(Assuming we have added the `likes` field to each article). The order is ascending by default.

In case we want to sort by multiple properties, we can write our properties separated by a comma:

`GET http://localhost:3000/articles?_sort=author,score&_order=desc,asc`

**Operators** are suffixes used to augment our query parameters:

* `_gt` (greater than), `_lt` (less than), `_gte` (greater than or equal) and `_lte` (less than or equal): `GET http://localhost:3000/comments?score_gte=5` (assuming we have a `score` field in the comments)
* `_ne`(not equal) negation of an expression `GET http://localhost:3000/comments?articleId_ne=2`
* `_like` is an operator that can be applied to string properties, it gives the same result as an `SQL`'s `LIKE`. `GET http://localhost:3000/articles?title_like=API`

#### Pagination

We can use the built-in query parameters `_page` & `_limit` to paginate our results.
`json-server` exposes `X-Total-Count` and the `Link` header that contain links to the first, next and last pages.

`GET http://localhost:3000/articles?_page=1&_limit=1`

```http
HTTP/1.1 200 OK
X-Powered-By: Express
Vary: Origin, Accept-Encoding
Access-Control-Allow-Credentials: true
Cache-Control: no-cache
Pragma: no-cache
Expires: -1
X-Total-Count: 3
Access-Control-Expose-Headers: X-Total-Count, Link
Link: <http://localhost:3000/articles?_page=1&_limit=1>; rel="first", <http://localhost:3000/articles?_page=2&_limit=1>; rel="next", <http://localhost:3000/articles?_page=3&_limit=1>; rel="last"
X-Content-Type-Options: nosniff
Content-Type: application/json; charset=utf-8
Content-Length: 89
ETag: W/"59-24+hjZrVFdbtnn+FgcogU6QvujI"
Date: Sun, 30 Jul 2017 17:22:34 GMT
Connection: keep-alive
```

#### Full text search

We can implement a search feature in our app using full-text search by simply adding a `q` query parameter.

```bash
$ curl http://localhost:3000/articles?q=api
[
  {
    "id": 1,
    "title": "Build an API using GO",
    "author": "qneyrat"
  },
  {
    "id": 2,
    "title": "Build an API using API Platform",
    "author": "rpierlot"
  }
]
```

#### Relationships

We can see relationships using `_embed` & `_expand` parameters.
* `_embed` allows us to see the children resources like `comments`: `GET http://localhost:3000/articles?_embed=comments`
* `_expand` allows us to see the parent resources like `articles`: `GET http://localhost:3000/comments?_expand=article`

```bash
$ curl http://localhost:3000/articles?author=vincent&_embed=comments
[
  {
    "title": "GraphQL",
    "author": "vincent",
    "id": 3,
    "comments": [
      {
        "body": "nice",
        "articleId": 3,
        "id": 3
      },
      {
        "body": "great!",
        "articleId": 3,
        "id": 4
      }
    ]
  }
]

$ curl http://localhost:3000/comments?_expand=article
[
  {
    "id": 1,
    "body": "Brilliant",
    "articleId": 1,
    "article": {
      "id": 1,
      "title": "Build an API using GO",
      "author": "qneyrat"
    }
  },
  {
    "id": 2,
    "body": "Awesome",
    "articleId": 2,
    "article": {
      "id": 2,
      "title": "Build an API using API Platform",
      "author": "rpierlot"
    }
  },
  ...
]
```

Until now, we've seen only the routes part of `json-server`, there are a lot more things we can do, let's see what's next.

### Randomly generated data

The [basic example in Typicode's docs](https://github.com/typicode/json-server#generate-random-data) presents a simple script that generates the `users` endpoint. Here we are going to write endpoints that serve randomly generated data using a data faker module. Personally, I use [faker.js](https://github.com/Marak/faker.js), but there are others that you can explore like [Chance](https://github.com/chancejs/chancejs) and [Casual](https://github.com/boo1ean/casual){:rel="nofollow noreferrer"}.

The random aspect of the generation occurs only once, and that's when we run the script. This means that `json-server` won't give us a different response for each request. Eventually, we have to install our fake data tool, then write the generation script:

```bash
$ yarn add faker
$ touch generate.js
```

Keep in mind that the script must export a function that exclusively returns an object with keys (endpoints) inside.

```js
// generate.js
const faker = require('faker');

module.exports = () => ({
  messages: [...Array(3)].map((value, index) => ({
    id: index + 1,
    name: faker.hacker.noun(),
    status: faker.hacker.adjective(),
    description: faker.hacker.phrase(),
  })),
});
```

Then run json-server by giving it the generation script:

```bash
$ json-server generate.js

  \{^_^}/ hi!

  Loading generate.js
  Done

  Resources
  http://localhost:3000/messages

  Home
  http://localhost:3000

  Type s + enter at any time to create a snapshot of the database
```

And the results would be something like:

```bash
$ curl http://localhost:3000/messages
[
  {
    "id": 1,
    "name": "driver",
    "status": "cross-platform",
    "description": "If we connect the system, we can get to the ADP panel through the redundant PCI protocol!"
  },
  {
    "id": 2,
    "name": "monitor",
    "status": "1080p",
    "description": "Try to synthesize the CSS driver, maybe it will navigate the bluetooth matrix!"
  },
  {
    "id": 3,
    "name": "hard drive",
    "status": "virtual",
    "description": "Use the redundant SMS program, then you can compress the bluetooth port!"
  }
]
```

And we can still perform requests on it as we've seen in the [routes](#routes) section.

### Custom routes

Let's imagine we are supposed to perform requests on several different endpoints on our future API, and these endpoints don't have the same URIs:

```url
/api/dashboard
/api/groups/ducks/stats
/auth/users
/rpierlot/articles
```

`json-server` allows us to specify route rewrites. We can address this problem by using a map that resolves the actual routes in our json schema:

```json
{
  "/api/:view": "/:view",
  "/api/groups/:planet/stats": "/stats?planet=:planet",
  "/:user/articles": "/articles?author=:user",
  "/auth/users": "/users"
}
```

So, when we start `json-server` it shows us the route rewrites we are using :

```bash
$ json-server --watch db2.json --routes routes.json

  \{^_^}/ hi!

  Loading db2.json
  Loading routes.json
  Done

  Resources
  http://localhost:3000/users
  http://localhost:3000/dashboard
  http://localhost:3000/stats
  http://localhost:3000/articles

  Other routes
  /api/:view -> /:view
  /api/groups/:planet/stats -> /stats?planet=:planet
  /:user/articles -> /articles?author=:user
  /auth/users -> /users

  Home
  http://localhost:3000

  Type s + enter at any time to create a snapshot of the database
  Watching...
```

Now we can perform our custom requests to see the results:

```bash
$ curl http://localhost:3000/api/dashboard
{
  "visits": 3881,
  "views": 625128,
  "shares": 7862
}

$ curl http://localhost:3000/api/groups/ducks/stats
[
  {
    "planet": "ducks",
    "stats": {
      "points": 5625,
      "ships": 8
    }
  }
]
```

### Middlewares

In case we want to augment our `json-server` instance with a specific behavior, we have the possibility to do so using custom middlewares, these middlewares are passed to the express server the same way we would do it when developing a classic express app. In this section, we're going to explore a useful example of a feature that is usually necessary.

Imagine we want to access a resource on the API, but it turns out that this resource is secured. We can say that it's just about data and assume that we'll be satisfied by just returning it, then we use `json-server` to provide the data without worrying about security. But, we know that something's odd, we want our app to be ready when our future API is ready, in order to test the whole thing together. So, instead of bypassing it, let's use middlewares to set up an authentication layer.

```js
// auth.js
const auth = require('basic-auth');

module.exports = (req, res, next) => {
  var user = auth(req);

  if (typeof user === 'undefined' || user.name !== 'kamal' || user.pass !== 'secret') {
    // We will discuss this line later in this section.
    res.header('WWW-Authenticate', 'Basic realm="Access to the API"');
    return res.status(401).send({ error: 'Unauthorized' });
  }

  next();
};
```

Now run the `json-server` command with the `--middlewares` option:

```bash
$ json-server --watch db2.json --routes routes.json --middlewares auth.js
```

Notice: the `--middlewares` option accepts a list of files. `--middlewares file1.js file2.js file3.js`.

Now let's test our authentication layer:

```bash
$ curl http://localhost:3000/api/groups/ducks/stats
{
  "error": "Unauthorized"
}
```

And we can see `json-server`'s log with the `401` HTTP status:

```bash
GET /api/groups/ducks/stats 401 12.180 ms - 29
```

When we display the headers of this response, we recognize this header `WWW-Authenticate: Basic realm="Access to the API"`:

```http
HTTP/1.1 401 Unauthorized
X-Powered-By: Express
Vary: Origin, Accept-Encoding
Access-Control-Allow-Credentials: true
Cache-Control: no-cache
Pragma: no-cache
Expires: -1
WWW-Authenticate: Basic realm="Access to the API"
Content-Type: application/json; charset=utf-8
Content-Length: 29
ETag: W/"1d-t1Z3N2Fd2Yqi/vcyFQaHaMeQEew"
Date: Thu, 03 Aug 2017 09:59:57 GMT
Connection: keep-alive
```

Here is what Mozilla Developer Network tells about it:

> The `WWW-Authenticate` and `Proxy-Authenticate` response headers define the authentication method that should be used to gain access to a resource. They need to specify which authentication scheme is used so that the client that wishes to authorize knows how to provide the credentials.
>
> [HTTP authentication : `WWW-Authenticate` and `Proxy-Authenticate` headers](https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication#WWW-Authenticate_and_Proxy-Authenticate_headers){:rel="nofollow noreferrer"}

Then we test again, and this time we add credentials to our request (Notice: `curl`'s `--user` option is not restricted to basic authentication, we can do other types of authentication, [see here](https://ec.haxx.se/http-auth.html)){:rel="nofollow noreferrer"}:

```bash
$ curl --user kamal:secret http://localhost:3000/api/groups/ducks/stats
[
  {
    "planet": "ducks",
    "stats": {
      "points": 5625,
      "ships": 8
    }
  }
]
```

Great! Obviously, it's a `200` HTTP status :-D

```bash
GET /api/groups/ducks/stats 200 4.609 ms - 94
```

### As a NodeJS module

`json-server` is an `express` application, which means that we can use it in an existing node/express app to achieve special behaviors. Here is a simple example that shows how to customize the logger:

`json-server` uses [`morgan`](https://github.com/expressjs/morgan) for logs, and the default format that it uses is the [`dev`](https://github.com/expressjs/morgan#dev) log format, which doesn't expose all the info that we want, we need to use the [standard Apache combined log outpout format](https://github.com/expressjs/morgan#combined){:rel="nofollow noreferrer"} instead:

```js
// server.js
import express from 'express';
import api from './api';

const port = 9001;
const app = express();
const API_ROOT = `http://localhost:${port}/api`;

app.use('/api', api);

app.listen(port, error => {
  if (error) {
    console.error(error);
  } else {
    console.info('==> 🌎  Listening on port %s. Open up %s in your browser.', port, API_ROOT);
  }
});
```

```js
// api.js
import { create, defaults, rewriter, router } from 'json-server';
import morgan from 'morgan';
import rewrites from './routes.json';

const server = create();
const apiEndpoints = router('db2.json');
// Deactivate the existing logger
const middlewares = defaults({ logger: false });

// Here we use our own logging format
server.use(morgan('combined', { colors: true }));

server.use(rewriter(rewrites));
server.use(middlewares);
server.use(apiEndpoints);

export default server;
```

Then we run our server:

```bash
$ nodemon --exec babel-node server.js
==> 🌎  Listening on port 9001. Open up http://localhost:9001/api/ in your browser.
```

Here we can see our custom logs in the console:

```bash
$ curl --user kamal:secret http://localhost:9001/api/groups/ducks/stats
::1 - kamal [11/Aug/2017:15:04:58 +0000] "GET /api/groups/ducks/stats HTTP/1.1" 200 187 "-" "curl/7.51.0"

# or with Chrome
::1 - - [10/Aug/2017:08:57:04 +0000] "GET /api/ HTTP/1.1" 200 - "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36"
```

## Conclusion

`json-server` has drastically decreased the time of scaffolding an API. Amongst the possibilities that we've seen, there are lots of use cases you can explore in order to use json-server, like logging customization, testing, reconciliation between micro-services, serverless applications ...etc.

I hope this post did shed some light on how we can use json-server. I tried to bring some useful use cases we encounter every day. If you still want to learn more about using it or even its inner working, I recommend exploring its [github project](https://github.com/typicode/json-server){:rel="nofollow noreferrer"}.

Thanks for reading!


text:
package test.outparams;

import org.apache.axis.AxisFault;
import org.apache.axis.Message;
import org.apache.axis.MessageContext;
import org.apache.axis.handlers.BasicHandler;
import org.apache.axis.message.RPCElement;
import org.apache.axis.message.RPCParam;
import org.apache.axis.message.SOAPEnvelope;

public class ServiceHandler extends BasicHandler {
    public static final String OUTPARAM1 = "Output param value";
    public static final Float OUTPARAM2 = new Float(4.56);
    public static final Integer RESPONSE = new Integer(5);

    public void invoke(MessageContext msgContext) throws AxisFault {
        SOAPEnvelope env = new SOAPEnvelope();

        RPCParam retVal = new RPCParam("return", RESPONSE);
        RPCParam outParam1 = new RPCParam("out1", OUTPARAM1);
        RPCParam outParam2 = new RPCParam("out2", OUTPARAM2);

        RPCElement rpc = new RPCElement("namespace", "response", new Object []
                            { retVal, outParam1, outParam2 });

        env.addBodyElement(rpc);

        msgContext.setResponseMessage(new Message(env));
    }
}


text:
<?php

namespace Example;

/**
 * @coversNothing
 * @codeCoverageIgnore
 *
 * @internal
 */
class BindTestWithExample implements BindTestInterface
{
    public function example()
    {
        // TODO: Implement example() method.
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimary">#3F51B5</color>
    <color name="colorPrimaryDark">#303F9F</color>
    <color name="colorAccent">#FF4081</color>
    <color name="white">#ffffff</color>
    <color name="listview_driver">#eeeeee</color>
    <color name="green">#e581ff02</color>
    <color name="bg">#4d4d4d</color>
    <color name="white_color">#ffffffff</color>
    <color name="fulltransparent">#00ffffff</color>

    <color name="orange">#ffa500</color><!--橙色 -->
    <color name="grey">#808080</color><!--灰色 -->
    <color name="black">#000000</color><!--黑色 -->
</resources>


text:
exports.accessToken = 'thisIsAnAccessToken';
exports.albumId = 'someAlbumId';


text:
    <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
    <title>or-tools/src/util/: operations_research::PermutationApplier< IndexType > Class Template Reference - Doxy</title>
    <link rel="shortcut icon" href="../../../favicon.ico">

    <link href="../../../doxygen.css" rel="stylesheet" type="text/css">
    <link href="../../../tabs.css" rel="stylesheet" type="text/css">

          Generated on: Thu Mar 29 07:46:58 PDT 2012
            for custom file set

        <tt>//
            doxy/
            or-tools/
            src/
            util/
            </tt>

Main Page

Related Pages

Namespaces

Classes

Files

Class List

Class Hierarchy

Class Members

operations_research::PermutationApplier

operations_research::PermutationApplier< IndexType > Class Template Reference
Note that this template is not implemented in an especially performance-sensitive way.
More...

#include <permutation.h>

List of all members.

Public Member Functions

 	PermutationApplier (PermutationCycleHandler< IndexType > *cycle_handler)

void 	Apply (IndexType permutation[], int permutation_start, int permutation_end)

Detailed Description

template<typename IndexType>

 class operations_research::PermutationApplier< IndexType >

Note that this template is not implemented in an especially performance-sensitive way.

In particular, it makes multiple virtual method calls for each element of the permutation.

Definition at line 179 of file permutation.h.

Constructor & Destructor Documentation

template<typename IndexType>

          operations_research::PermutationApplier< IndexType >::PermutationApplier
          (
          PermutationCycleHandler< IndexType > *
           cycle_handler
           )
           [inline, explicit]

Definition at line 181 of file permutation.h.

Member Function Documentation

template<typename IndexType>

          void operations_research::PermutationApplier< IndexType >::Apply
          (
          IndexType
           permutation[],

          int
           permutation_start,

          int
           permutation_end

          )
          		 [inline]

Definition at line 185 of file permutation.h.

The documentation for this class was generated from the following file:

or-tools/src/util/permutation.h


text:
import logging
from flask import g
from flask_appbuilder.security.sqla import models as sqla_models
from flask_appbuilder.security.sqla.manager import SecurityManager
from sqlalchemy import or_

from airflow import models, settings
from airflow.www_rbac.app import appbuilder

###########################################################################
#                               VIEW MENUS
###########################################################################
viewer_vms = {
    'Airflow',
    'DagModelView',
    'Browse',
    'DAG Runs',
    'DagRunModelView',
    'Task Instances',
    'TaskInstanceModelView',
    'SLA Misses',
    'SlaMissModelView',
    'Jobs',
    'JobModelView',
    'Logs',
    'LogModelView',
    'Docs',
    'Documentation',
    'Github',
    'About',
    'Version',
    'VersionView',
}

user_vms = viewer_vms

op_vms = {
    'Admin',
    'Configurations',
    'ConfigurationView',
    'Connections',
    'ConnectionModelView',
    'Pools',
    'PoolModelView',
    'Variables',
    'VariableModelView',
    'XComs',
    'XComModelView',
}

###########################################################################
#                               PERMISSIONS
###########################################################################

viewer_perms = {
    'menu_access',
    'can_index',
    'can_list',
    'can_show',
    'can_chart',
    'can_dag_stats',
    'can_dag_details',
    'can_task_stats',
    'can_code',
    'can_log',
    'can_get_logs_with_metadata',
    'can_tries',
    'can_graph',
    'can_tree',
    'can_task',
    'can_task_instances',
    'can_xcom',
    'can_gantt',
    'can_landing_times',
    'can_duration',
    'can_blocked',
    'can_rendered',
    'can_pickle_info',
    'can_version',
}

user_perms = {
    'can_dagrun_clear',
    'can_run',
    'can_trigger',
    'can_add',
    'can_edit',
    'can_delete',
    'can_paused',
    'can_refresh',
    'can_success',
    'muldelete',
    'set_failed',
    'set_running',
    'set_success',
    'clear',
    'can_clear',
}

op_perms = {
    'can_conf',
    'can_varimport',
}

# global view-menu for dag-level access
dag_vms = {
    'all_dags'
}

dag_perms = {
    'can_dag_read',
    'can_dag_edit',
}

###########################################################################
#                     DEFAULT ROLE CONFIGURATIONS
###########################################################################

ROLE_CONFIGS = [
    {
        'role': 'Viewer',
        'perms': viewer_perms,
        'vms': viewer_vms | dag_vms
    },
    {
        'role': 'User',
        'perms': viewer_perms | user_perms | dag_perms,
        'vms': viewer_vms | dag_vms | user_vms,
    },
    {
        'role': 'Op',
        'perms': viewer_perms | user_perms | op_perms | dag_perms,
        'vms': viewer_vms | dag_vms | user_vms | op_vms,
    },
]

EXISTING_ROLES = {
    'Admin',
    'Viewer',
    'User',
    'Op',
    'Public',
}

class AirflowSecurityManager(SecurityManager):

    def init_role(self, role_name, role_vms, role_perms):
        """
        Initialize the role with the permissions and related view-menus.

        :param role_name:
        :param role_vms:
        :param role_perms:
        :return:
        """
        pvms = self.get_session.query(sqla_models.PermissionView).all()
        pvms = [p for p in pvms if p.permission and p.view_menu]

        role = self.find_role(role_name)
        if not role:
            role = self.add_role(role_name)

        role_pvms = []
        for pvm in pvms:
            if pvm.view_menu.name in role_vms and pvm.permission.name in role_perms:
                role_pvms.append(pvm)
        role.permissions = list(set(role_pvms))
        self.get_session.merge(role)
        self.get_session.commit()

    def get_user_roles(self, user=None):
        """
        Get all the roles associated with the user.
        """
        if user is None:
            user = g.user
        if user.is_anonymous():
            public_role = appbuilder.config.get('AUTH_ROLE_PUBLIC')
            return [appbuilder.security_manager.find_role(public_role)] \
                if public_role else []
        return user.roles

    def get_all_permissions_views(self):
        """
        Returns a set of tuples with the perm name and view menu name
        """
        perms_views = set()
        for role in self.get_user_roles():
            for perm_view in role.permissions:
                perms_views.add((perm_view.permission.name, perm_view.view_menu.name))
        return perms_views

    def get_accessible_dag_ids(self, username=None):
        """
        Return a set of dags that user has access to(either read or write).

        :param username: Name of the user.
        :return: A set of dag ids that the user could access.
        """
        if not username:
            username = g.user

        if username.is_anonymous() or 'Public' in username.roles:
            # return an empty list if the role is public
            return set()

        roles = {role.name for role in username.roles}
        if {'Admin', 'Viewer', 'User', 'Op'} & roles:
            return dag_vms

        user_perms_views = self.get_all_permissions_views()
        # return all dags that the user could access
        return set([view for perm, view in user_perms_views if perm in dag_perms])

    def has_access(self, permission, view_name, user=None):
        """
        Verify whether a given user could perform certain permission
        (e.g can_read, can_write) on the given dag_id.

        :param str permission: permission on dag_id(e.g can_read, can_edit).
        :param str view_name: name of view-menu(e.g dag id is a view-menu as well).
        :param str user: user name
        :return: a bool whether user could perform certain permission on the dag_id.
        """
        if not user:
            user = g.user
        if user.is_anonymous():
            return self.is_item_public(permission, view_name)
        return self._has_view_access(user, permission, view_name)

    def _get_and_cache_perms(self):
        """
        Cache permissions-views
        """
        self.perms = self.get_all_permissions_views()

    def _has_role(self, role_name_or_list):
        """
        Whether the user has this role name
        """
        if not isinstance(role_name_or_list, list):
            role_name_or_list = [role_name_or_list]
        return any(
            [r.name in role_name_or_list for r in self.get_user_roles()])

    def _has_perm(self, permission_name, view_menu_name):
        """
        Whether the user has this perm
        """
        if hasattr(self, 'perms'):
            if (permission_name, view_menu_name) in self.perms:
                return True
        # rebuild the permissions set
        self._get_and_cache_perms()
        return (permission_name, view_menu_name) in self.perms

    def has_all_dags_access(self):
        """
        Has all the dag access in any of the 3 cases:
        1. Role needs to be in (Admin, Viewer, User, Op).
        2. Has can_dag_read permission on all_dags view.
        3. Has can_dag_edit permission on all_dags view.
        """
        return (
            self._has_role(['Admin', 'Viewer', 'Op', 'User']) or
            self._has_perm('can_dag_read', 'all_dags') or
            self._has_perm('can_dag_edit', 'all_dags'))

    def clean_perms(self):
        """
        FAB leaves faulty permissions that need to be cleaned up
        """
        logging.info('Cleaning faulty perms')
        sesh = self.get_session
        pvms = (
            sesh.query(sqla_models.PermissionView)
            .filter(or_(
                sqla_models.PermissionView.permission == None,  # NOQA
                sqla_models.PermissionView.view_menu == None,  # NOQA
            ))
        )
        deleted_count = pvms.delete()
        sesh.commit()
        if deleted_count:
            logging.info('Deleted {} faulty permissions'.format(deleted_count))

    def _merge_perm(self, permission_name, view_menu_name):
        """
        Add the new permission , view_menu to ab_permission_view_role if not exists.
        It will add the related entry to ab_permission
        and ab_view_menu two meta tables as well.

        :param str permission_name: Name of the permission.
        :param str view_menu_name: Name of the view-menu

        :return:
        """
        permission = self.find_permission(permission_name)
        view_menu = self.find_view_menu(view_menu_name)
        pv = None
        if permission and view_menu:
            pv = self.get_session.query(self.permissionview_model).filter_by(
                permission=permission, view_menu=view_menu).first()
        if not pv and permission_name and view_menu_name:
            self.add_permission_view_menu(permission_name, view_menu_name)

    def create_custom_dag_permission_view(self):
        """
        Workflow:
        1. when scheduler found a new dag, we will create an entry in ab_view_menu
        2. we fetch all the roles associated with dag users.
        3. we join and create all the entries for ab_permission_view_menu
           (predefined permissions * dag-view_menus)
        4. Create all the missing role-permission-views for the ab_role_permission_views

        :return: None.
        """
        # todo(Tao): should we put this function here or in scheduler loop?
        logging.info('Fetching a set of all permission, view_menu from FAB meta-table')

        def merge_pv(perm, view_menu):
            """Create permission view menu only if it doesn't exist"""
            if view_menu and perm and (view_menu, perm) not in all_pvs:
                self._merge_perm(perm, view_menu)

        all_pvs = set()
        for pv in self.get_session.query(self.permissionview_model).all():
            if pv.permission and pv.view_menu:
                all_pvs.add((pv.permission.name, pv.view_menu.name))

        # create perm for global logical dag
        for dag in dag_vms:
            for perm in dag_perms:
                merge_pv(perm, dag)

        # Get all the active / paused dags and insert them into a set
        all_dags_models = settings.Session.query(models.DagModel)\
            .filter(or_(models.DagModel.is_active, models.DagModel.is_paused))\
            .filter(~models.DagModel.is_subdag).all()

        for dag in all_dags_models:
            for perm in dag_perms:
                merge_pv(perm, dag.dag_id)

        # for all the dag-level role, add the permission of viewer
        # with the dag view to ab_permission_view
        all_roles = self.get_all_roles()
        user_role = self.find_role('User')

        dag_role = [role for role in all_roles if role.name not in EXISTING_ROLES]
        update_perm_views = []

        # todo(tao) need to remove all_dag vm
        dag_vm = self.find_view_menu('all_dags')
        ab_perm_view_role = sqla_models.assoc_permissionview_role
        perm_view = self.permissionview_model
        view_menu = self.viewmenu_model

        # todo(tao) comment on the query
        all_perm_view_by_user = settings.Session.query(ab_perm_view_role)\
            .join(perm_view, perm_view.id == ab_perm_view_role
                  .columns.permission_view_id)\
            .filter(ab_perm_view_role.columns.role_id == user_role.id)\
            .join(view_menu)\
            .filter(perm_view.view_menu_id != dag_vm.id)
        all_perm_views = set([role.permission_view_id for role in all_perm_view_by_user])

        for role in dag_role:
            # Get all the perm-view of the role
            existing_perm_view_by_user = self.get_session.query(ab_perm_view_role)\
                .filter(ab_perm_view_role.columns.role_id == role.id)

            existing_perms_views = set([role.permission_view_id
                                        for role in existing_perm_view_by_user])
            missing_perm_views = all_perm_views - existing_perms_views

            for perm_view_id in missing_perm_views:
                update_perm_views.append({'permission_view_id': perm_view_id,
                                          'role_id': role.id})

        self.get_session.execute(ab_perm_view_role.insert(), update_perm_views)
        self.get_session.commit()

    def update_admin_perm_view(self):
        """
        Admin should have all the permission-views.
        Add the missing ones to the table for admin.

        :return: None.
        """
        pvms = self.get_session.query(sqla_models.PermissionView).all()
        pvms = [p for p in pvms if p.permission and p.view_menu]

        admin = self.find_role('Admin')
        existing_perms_vms = set(admin.permissions)
        for p in pvms:
            if p not in existing_perms_vms:
                existing_perms_vms.add(p)
        admin.permissions = list(existing_perms_vms)
        self.get_session.commit()

    def sync_roles(self):
        """
        1. Init the default role(Admin, Viewer, User, Op, public)
           with related permissions.
        2. Init the custom role(dag-user) with related permissions.

        :return: None.
        """
        logging.info('Start syncing user roles.')

        # Create default user role.
        for config in ROLE_CONFIGS:
            role = config['role']
            vms = config['vms']
            perms = config['perms']
            self.init_role(role, vms, perms)
        self.create_custom_dag_permission_view()

        # init existing roles, the rest role could be created through UI.
        self.update_admin_perm_view()
        self.clean_perms()

    def sync_perm_for_dag(self, dag_id):
        """
        Sync permissions for given dag id. The dag id surely exists in our dag bag
        as only /refresh button will call this function

        :param dag_id:
        :return:
        """
        for dag_perm in dag_perms:
            perm_on_dag = self.find_permission_view_menu(dag_perm, dag_id)
            if perm_on_dag is None:
                self.add_permission_view_menu(dag_perm, dag_id)


text:
package com.github.trevershick.test.ldap.annotations;

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

@Retention(RetentionPolicy.RUNTIME)
public @interface Ldif {
	String value();
}


text:
package com.asciibunny.bcs.interpreter;

import com.asciibunny.bcs.apiai.ApiAiConnecter;
import com.asciibunny.bcs.apiai.data.Query;
import com.asciibunny.bcs.apiai.data.Response;

public class Interpreter {

	private static Interpreter interpreter;

	private ApiAiConnecter api;

	private Interpreter() {
		api = new ApiAiConnecter();
	}

	public static Interpreter getInterpreter() {
		if (interpreter == null) interpreter = new Interpreter();
		return interpreter;
	}

	public String command(String query, String session) {
		try {
			Response res = api.jsonToResult(api.runquery(new Query(query, session)));
			System.out.println("{" + res.result.action + ":" + res.result.parameters + "}");
			return interprete(res);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "error ocurred";
	}

	private String interprete(Response res) {
		String answer = "unrecognized command";
		switch (res.result.action) {
		case "smalltalk.greetings":
			answer = "Hey There!";
			break;
		case "smalltalk.user":
			if (res.result.parameters.get("simplified").equals("i am testing you")) {
				answer = "As far as I know, I'm still working!";
			} else {
				answer = "unrecognized 'smalltalk.user', please try again";
			}
			break;
		case "manage.app_close":
			System.out.println("Stopping now");
			System.exit(0);
			break;
		}
		return answer;
	}

}


text:
package com.google.jenkins.plugins.util;

/** This exception is used to wrap and propagate 404 (Not Found) HTTP exceptions up the stack. */
public class NotFoundException extends ExecutorException {
  public NotFoundException(Throwable throwable) {
    super(throwable);
  }

  public NotFoundException() {}
}


text:
package org.apache.metron.common.field.validation.network;

import org.apache.commons.validator.routines.InetAddressValidator;
import org.apache.metron.common.field.validation.FieldValidation;

import java.util.List;
import java.util.Map;
import java.util.function.Predicate;

public class IPValidation implements FieldValidation, Predicate<List<Object>> {

  private enum IPType {
     IPV4(ip -> InetAddressValidator.getInstance().isValidInet4Address(ip))
    ,IPV6(ip -> InetAddressValidator.getInstance().isValidInet6Address(ip))
    , DEFAULT(ip -> InetAddressValidator.getInstance().isValid(ip));
    Predicate<String> validationPredicate;
    IPType(Predicate<String> validationPredicate) {
      this.validationPredicate = validationPredicate;
    }
    public boolean isValid(String ip) {
      return validationPredicate.test(ip);
    }
    public static IPType get(String type) {
      if(type == null) {
        return DEFAULT;
      }
      else {
        try {
          return IPType.valueOf(type);
        }
        catch(Exception e) {
          return DEFAULT;
        }
      }
    }
  }
  private enum Config {
    TYPE("type")
    ;
    String key;
    Config(String key) {
      this.key = key;
    }
    public <T> T get(Map<String, Object> config, Class<T> clazz) {
      Object o = config.get(key);
      if(o == null) {
        return null;
      }
      return clazz.cast(o);
    }
  }

  /**
   * Evaluates this predicate on the given argument.
   *
   * @param strings the input argument
   * @return {@code true} if the input argument matches the predicate,
   * otherwise {@code false}
   */
  @Override
  public boolean test(List<Object> strings) {
    IPType type = IPType.DEFAULT;
    if(strings.isEmpty()) {
      return false;
    }
    Object ip =  strings.get(0);
    if(ip == null) {
      return false;
    }
    if(strings.size() >= 2) {
      Object ipType = strings.get(1);
      if(ipType != null )
      {
        try {
          type = IPType.get(ipType.toString());
        } catch (Exception e) {
          type = IPType.DEFAULT;
        }
      }
    }
    return type.isValid(ip.toString());
  }
  @Override
  public boolean isValid( Map<String, Object> input
                        , Map<String, Object> validationConfig
                        , Map<String, Object> globalConfig
                        ) {
    IPType type = IPType.get(Config.TYPE.get(validationConfig, String.class));
    for(Object o : input.values()) {
      if(o != null && !type.isValid(o.toString())) {
        return false;
      }
    }
    return true;
  }

  @Override
  public void initialize(Map<String, Object> validationConfig, Map<String, Object> globalConfig) {
  }
}


text:
/*
Package client provides a playback api client for ff command line.
Example:
	import (
	"log"
	"github.com/nofdev/fastforward/provisioning"
	"github.com/nofdev/fastforward/provisioning/api/rpc/json/openstack"
	"github.com/nofdev/fastforward/provisioning/api/rpc/json/openstack/client"
	)

	// The playback API address.
	url = "http://localhost:7001/v1"
	// Define arguments for load balancer.
	args = &openstack.Args{provisioning.ExtraVars{HostName: "localhost", RouterID: "51", State: "Master", Priority: "50"}}
	// Deploy load balancer for OpenStack HA.
	err := client.LoadBalancer(args)
	if err != nil {
		log.Fatal(err)
	}
*/
package client


text:
from iptest.assert_util import *

add_clr_assemblies("loadorder_3")

# namespace First {
#     public class Generic1<K, V> {
#         public static string Flag = typeof(Generic1<,>).FullName;
#     }
# }

import First

add_clr_assemblies("loadorder_3e")

# namespace Second {
#     public class Generic1<K, V> {
#         public static string Flag = typeof(Generic1<,>).FullName;
#     }
# }

import Second

AreEqual(First.Generic1[int, int].Flag, "First.Generic1`2")
AreEqual(Second.Generic1[int, int].Flag, "Second.Generic1`2")

from First import *

AreEqual(Generic1[int, int].Flag, "First.Generic1`2")

from Second import *

AreEqual(Generic1[int, int].Flag, "Second.Generic1`2")


text:
import boto3
import json

print('Loading function')
client = boto3.client('dynamodb')

def lambda_handler(event, context):

    # Print the input for logging
    print("Received event: " + json.dumps(event, indent=2))

    # Check for table name, table key, and queryParams
    if 'tableName' not in event or 'tableKey' not in event or 'queryParams' not in event:
        raise Exception('API Mapping Error') #501

    # Default values
    limit = 50
    lastKey = None
    # Read out query parameters
    if 'limit' in event['queryParams']:
        limit = int(event['queryParams']['limit'])
    if 'lastKey' in event['queryParams']:
        lastKey = {}
        lastKey[event['tableKey']] = {}
        lastKey[event['tableKey']]['S'] = event['queryParams']['lastKey']

    # Perform scans based on input parameters
    try:
        if lastKey is None:
            response = client.scan(TableName=event['tableName'], Limit=limit, Select='ALL_ATTRIBUTES')
        else:
            response = client.scan(TableName=event['tableName'], Limit=limit, Select='ALL_ATTRIBUTES', ExclusiveStartKey=lastKey)
    except Exception as e:
        print(e)
        raise Exception('DynamoDB Error') #500

    # Check for an empty response
    print(response)
    if 'Item' not in response and 'Items' not in response:
        raise Exception('Not Found Error') #404
    return response


text:
var Code = require('code');   // assertion library
var Lab = require('lab');
var lab = exports.lab = Lab.script();

var describe = lab.experiment;
var it = lab.test;

var server = require('../server');
var config = require('../config');

describe('tution tests ->', function(){

	lab.before({timeout: 10000}, function(done){
		server.startServer(function(){
			done();
		});
	});

	require('./web_component')(server, describe, it, Code);
	require('./user')(server, describe, it, Code);

});


text:
import parseTorrentFile = require('parse-torrent-file');
import * as fs from 'fs';

const torrent = fs.readFileSync(__filename);
try {
    const parsed = parseTorrentFile(torrent);
    console.log(parsed.name);
} catch (e) {
    // the torrent file was corrupt
    console.error(e);
}


text:
using System;

namespace Avalonia.Styling.Activators
{
    /// <summary>
    /// An <see cref="IStyleActivator"/> which listens to a property value on a control.
    /// </summary>
    internal class PropertyEqualsActivator : StyleActivatorBase, IObserver<object?>
    {
        private readonly IStyleable _control;
        private readonly AvaloniaProperty _property;
        private readonly object? _value;
        private IDisposable? _subscription;

        public PropertyEqualsActivator(
            IStyleable control,
            AvaloniaProperty property,
            object? value)
        {
            _control = control ?? throw new ArgumentNullException(nameof(control));
            _property = property ?? throw new ArgumentNullException(nameof(property));
            _value = value;
        }

        protected override bool EvaluateIsActive()
        {
            var value = _control.GetValue(_property);
            return PropertyEqualsSelector.Compare(_property.PropertyType, value, _value);
        }

        protected override void Initialize()
        {
            _subscription = _control.GetObservable(_property).Subscribe(this);
        }

        protected override void Deinitialize() => _subscription?.Dispose();

        void IObserver<object?>.OnCompleted() { }
        void IObserver<object?>.OnError(Exception error) { }
        void IObserver<object?>.OnNext(object? value) => ReevaluateIsActive();
    }
}


text:
package org.apache.maven.plugin.surefire.booterclient;

import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * A bucket from which fork numbers can be drawn. Any drawn number needs to be returned to the bucket, in order to keep
 * the range of provided values delivered as small as possible.
 *
 * @author Andreas Gudian
 */
public class ForkNumberBucket
{

    private static final ForkNumberBucket INSTANCE = new ForkNumberBucket();

    private Queue<Integer> qFree = new ConcurrentLinkedQueue<Integer>();

    private AtomicInteger highWaterMark = new AtomicInteger( 1 );

    /**
     * Non-public constructor
     */
    protected ForkNumberBucket()
    {
    }

    /**
     * @return a fork number that is not currently in use. The value must be returned to the bucket using
     *         {@link #returnNumber(int)}.
     */
    public static int drawNumber()
    {
        return getInstance()._drawNumber();
    }

    /**
     * @param number the number to return to the bucket so that it can be reused.
     */
    public static void returnNumber( int number )
    {
        getInstance()._returnNumber( number );
    }

    /**
     * @return a singleton instance
     */
    private static ForkNumberBucket getInstance()
    {
        return INSTANCE;
    }

    /**
     * @return a fork number that is not currently in use. The value must be returned to the bucket using
     *         {@link #returnNumber(int)}.
     */
    protected int _drawNumber()
    {
        Integer nextFree = qFree.poll();

        if ( null == nextFree )
        {
            return highWaterMark.getAndIncrement();
        }
        else
        {
            return nextFree.intValue();
        }
    }

    /**
     * @return the highest number that has been drawn
     */
    protected int getHighestDrawnNumber()
    {
        return highWaterMark.get() - 1;
    }

    /**
     * @param number the number to return to the bucket so that it can be reused.
     */
    protected void _returnNumber( int number )
    {
        qFree.add( Integer.valueOf( number ) );
    }
}


text:
<title>Logarithm of Exponential</title>
<link rel="stylesheet" type="text/css" href="../style.css">

The logarithm function officially inverts a complex exponential on paper but not numerically:

The graph above is the real part of

\[ -i \log[ \exp( ix ) ] \]

A straightforward inversion says this should be equal to \(x\), but since \(\exp(2 \pi i)=1\) the numerical evaluation is in practice modulus \(2 \pi i\). This is one example of differences to keep in mind between formal mathematics and numerical implementation.

This example requires the higher-level mathematics of Math.

Complete code for this example:

Examples Page


text:
import React from 'react';
import { shallow } from 'enzyme';
import { expect } from 'chai';
import R from 'ramda';
import EntityList from '../../../src/components/EntityList';
import EntityListItem from '../../../src/components/EntityListItem';

describe('EntityList', () => {
    const createComponent = (entities = []) => {
        return <EntityList entities={entities} />;
    };

    it('should render an empty list if the passed entities were empty', () => {
        const entityList = shallow(createComponent());

        expect(entityList.find('li').length).to.equal(0);
    });

    it('should render the passed in entities as list items', () => {
        const entity = { id: 'foo-1', name: 'any entity' };
        const entityList = shallow(createComponent([ entity ]));
        const listItems = entityList.find('li');

        expect(listItems.length).to.equal(1);
        expect(listItems.first().children().is(EntityListItem)).to.equal(true);
    });

    it('should render the passed in entities in the correct oder', () => {
        const entities = [ { id: '11-a', name: 'foo' }, { id: '22-b', name: 'bar' } ];
        const entityList = shallow(createComponent(entities));
        const entityListItems = entityList.find(EntityListItem);

        expect(entityListItems.length).to.equal(entities.length);
        expect(entityListItems.first().props()).to.deep.equal({ entity: R.head(entities) });
        expect(entityListItems.last().props()).to.deep.equal({ entity: R.last(entities) });
    });
});


text:
<!DOCTYPE html>

<meta charset="utf-8">
<meta name="viewport" content="user-scalable=no, width=device-width, initial-scale=1">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
<title>Transition Metals</title>
<link rel="stylesheet" href="../jqm/jquery.mobile.theme.css">
<link rel="stylesheet" href="../jqm/animate.css">

Back

Transition Metals

Hexaaquacobalt (III)

[Co(H2O)6]3+ (aq)

Pink solution. Confirmatory test for water when blue cobalt (II) chloride paper turns pink.


text:
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by CSGenerator.
// </auto-generated>
//------------------------------------------------------------------------------
using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;

using jsval = JSApi.jsval;

public class JSB_UnityEngine_ParticleSystem_CollisionEvent
{

////////////////////// CollisionEvent ///////////////////////////////////////
// constructors
public static ConstructorID constructorID0 = new ConstructorID(null, null);

static bool CollisionEvent_CollisionEvent1(JSVCall vc, int argc)
{
    int _this = JSApi.getObject((int)JSApi.GetType.Arg);
    JSApi.attachFinalizerObject(_this);
    --argc;

    int len = argc;
    if (len == 0)
    {
        JSMgr.addJSCSRel(_this, new UnityEngine.ParticleSystem.CollisionEvent());
    }

    return true;
}

// fields

// properties
static void CollisionEvent_intersection(JSVCall vc)
{
        UnityEngine.ParticleSystem.CollisionEvent _this = (UnityEngine.ParticleSystem.CollisionEvent)vc.csObj;
        var result = _this.intersection;
                JSApi.setVector3S((int)JSApi.SetType.Rval, result);
}
static void CollisionEvent_normal(JSVCall vc)
{
        UnityEngine.ParticleSystem.CollisionEvent _this = (UnityEngine.ParticleSystem.CollisionEvent)vc.csObj;
        var result = _this.normal;
                JSApi.setVector3S((int)JSApi.SetType.Rval, result);
}
static void CollisionEvent_velocity(JSVCall vc)
{
        UnityEngine.ParticleSystem.CollisionEvent _this = (UnityEngine.ParticleSystem.CollisionEvent)vc.csObj;
        var result = _this.velocity;
                JSApi.setVector3S((int)JSApi.SetType.Rval, result);
}
static void CollisionEvent_collider(JSVCall vc)
{
        UnityEngine.ParticleSystem.CollisionEvent _this = (UnityEngine.ParticleSystem.CollisionEvent)vc.csObj;
        var result = _this.collider;
                JSMgr.datax.setObject((int)JSApi.SetType.Rval, result);
}

// methods

//register

public static void __Register()
{
    JSMgr.CallbackInfo ci = new JSMgr.CallbackInfo();
    ci.type = typeof(UnityEngine.ParticleSystem.CollisionEvent);
    ci.fields = new JSMgr.CSCallbackField[]
    {

    };
    ci.properties = new JSMgr.CSCallbackProperty[]
    {
        CollisionEvent_intersection,
        CollisionEvent_normal,
        CollisionEvent_velocity,
        CollisionEvent_collider,

    };
    ci.constructors = new JSMgr.MethodCallBackInfo[]
    {
        new JSMgr.MethodCallBackInfo(CollisionEvent_CollisionEvent1, ".ctor"),

    };
    ci.methods = new JSMgr.MethodCallBackInfo[]
    {

    };
    JSMgr.allCallbackInfo.Add(ci);
}

}


text:
namespace GafferUI
{

class GAFFERUI_API PlugAdder : public ConnectionCreator
{

	public :

		GAFFER_GRAPHCOMPONENT_DECLARE_TYPE( GafferUI::PlugAdder, PlugAdderTypeId, ConnectionCreator );

		PlugAdder();
		~PlugAdder() override;

		Imath::Box3f bound() const override;

		bool canCreateConnection( const Gaffer::Plug *endpoint ) const override;
		void updateDragEndPoint( const Imath::V3f position, const Imath::V3f &tangent ) override;

		/// When emitted, shows a menu containing the specified plugs, and returns
		/// the chosen plug. Implemented as a signal so the menu can be implemented
		/// externally in Python code.
		typedef boost::signal<Gaffer::Plug *( const std::string &title, const std::vector<Gaffer::Plug *> & )> PlugMenuSignal;
		static PlugMenuSignal &plugMenuSignal();

		/// A simpler menu that just shows a list of strings.  Should the previous form be deprecated?
		typedef boost::signal<std::string ( const std::string &title, const std::vector<std::string> & )> MenuSignal;
		static MenuSignal &menuSignal();

	protected :

		void doRenderLayer( Layer layer, const Style *style ) const override;

		void applyEdgeMetadata( Gaffer::Plug *plug, bool opposite = false ) const;

	private :

		void enter( GadgetPtr gadget, const ButtonEvent &event );
		void leave( GadgetPtr gadget, const ButtonEvent &event );
		bool buttonPress( GadgetPtr gadget, const ButtonEvent &event );
		IECore::RunTimeTypedPtr dragBegin( GadgetPtr gadget, const ButtonEvent &event );
		bool dragEnter( const DragDropEvent &event );
		bool dragMove( GadgetPtr gadget, const DragDropEvent &event );
		bool dragLeave( const DragDropEvent &event );
		bool drop( const DragDropEvent &event );
		bool dragEnd( const DragDropEvent &event );

		bool m_dragging;
		Imath::V3f m_dragPosition;
		Imath::V3f m_dragTangent;

};

IE_CORE_DECLAREPTR( PlugAdder )

typedef Gaffer::FilteredChildIterator<Gaffer::TypePredicate<PlugAdder> > PlugAdderIterator;
typedef Gaffer::FilteredRecursiveChildIterator<Gaffer::TypePredicate<PlugAdder> > RecursivePlugAdderIterator;

} // namespace GafferUI

#endif // GAFFERUI_PLUGADDER_H


text:
namespace k {

typedef void (*InterruptHandler)(void);

struct InterruptTable {
  #define ETL_STM32F4XX_IRQ(name) InterruptHandler name ## _handler;
  #include "etl/stm32f4xx/interrupts.def"
  #undef ETL_STM32F4XX_IRQ
};

ETL_SECTION(".stm32f4xx_interrupt_redirect")
ETL_USED
InterruptTable const stm32f4xx_interrupt_redirect {
  #define ETL_STM32F4XX_IRQ(name) irq_redirector,
  #include "etl/stm32f4xx/interrupts.def"
  #undef ETL_STM32F4XX_IRQ
};

}  // namespace k


text:
/*
* ExecFileCommandInterpreter.java
*
* User: Greg Schueler greg@dtosolutions.com
* Created: 3/21/11 4:26 PM
*
*/
package com.dtolabs.rundeck.core.execution.workflow.steps.node.impl;

import com.dtolabs.rundeck.core.common.Framework;
import com.dtolabs.rundeck.core.common.INodeEntry;
import com.dtolabs.rundeck.core.execution.workflow.StepExecutionContext;
import com.dtolabs.rundeck.core.execution.workflow.steps.node.NodeStepException;
import com.dtolabs.rundeck.core.execution.workflow.steps.node.NodeStepExecutionItem;
import com.dtolabs.rundeck.core.execution.workflow.steps.node.NodeStepExecutor;
import com.dtolabs.rundeck.core.execution.workflow.steps.node.NodeStepResult;

/**
 * ExecFileCommandInterpreter uses ExecutionService to execute a script on a node.
 *
 * @author Greg Schueler greg@dtosolutions.com
 */
public class ScriptFileNodeStepExecutor implements NodeStepExecutor {
    public static final String SERVICE_IMPLEMENTATION_NAME = "script";
    private Framework framework;
    private ScriptFileNodeStepUtils scriptUtils = new DefaultScriptFileNodeStepUtils();

    public ScriptFileNodeStepExecutor(Framework framework) {
        this.framework = framework;
    }

    public NodeStepResult executeNodeStep(
            StepExecutionContext context,
            NodeStepExecutionItem item,
            INodeEntry node
    )
    throws NodeStepException
    {
        ScriptFileCommand command = (ScriptFileCommand) item;
        return scriptUtils.executeScriptFile(
                context,
                node,
                command.getScript(),
                command.getServerScriptFilePath(),
                command.getScriptAsStream(),
                command.getFileExtension(),
                command.getArgs(),
                command.getScriptInterpreter(),
                command.getInterpreterArgsQuoted(),
                framework.getExecutionService()
        );
    }

    public ScriptFileNodeStepUtils getScriptUtils() {
        return scriptUtils;
    }

    public void setScriptUtils(ScriptFileNodeStepUtils scriptUtils) {
        this.scriptUtils = scriptUtils;
    }
}


text: from .sorted_set import SortedSet, NOT_FOUND


text:
'use strict';

//Enrollments service used to communicate Enrollments REST endpoints
angular.module('enrollments').factory('Enrollments', ['$resource','API',
	function($resource,API) {
		return {

			enrollment : $resource(API.enrollment.create,{}, {
				create: { method: 'POST',isArray:false,headers: {'Content-Type': 'application/x-www-form-urlencoded'}},
				update: { method: 'UPDATE',isArray:false,headers: {'Content-Type': 'application/x-www-form-urlencoded'}},
				delete: { method: 'DELETE',isArray:false,headers: {'Content-Type': 'application/x-www-form-urlencoded'}},
			}),

		}
	}
]);


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<type language="gradle" name="org.gradle.play.plugins.PlayApplicationPlugin.Rules" version="3.0" superType="org.gradle.model.RuleSource">
    <method name="execute" returnType="void">
        <parameter type="org.gradle.jvm.tasks.Jar" name="jar"/>
    </method>
    <method name="execute" returnType="void">
        <parameter type="org.gradle.language.java.JavaSourceSet" name="javaSources"/>
    </method>
    <method name="execute" returnType="void">
        <parameter type="org.gradle.language.jvm.JvmResourceSet" name="appResources"/>
    </method>
    <method name="execute" returnType="void">
        <parameter type="org.gradle.language.routes.RoutesSourceSet" name="routesSourceSet"/>
    </method>
    <method name="execute" returnType="void">
        <parameter type="org.gradle.language.scala.ScalaLanguageSourceSet" name="scalaSources"/>
    </method>
    <method name="execute" returnType="void">
        <parameter type="org.gradle.language.scala.tasks.PlatformScalaCompile" name="scalaCompile"/>
    </method>
    <method name="execute" returnType="void">
        <parameter type="org.gradle.language.twirl.TwirlSourceSet" name="twirlSourceSet"/>
    </method>
    <method name="execute" returnType="void">
        <parameter type="org.gradle.play.PlayApplicationBinarySpec" name="playBinary"/>
    </method>
    <method name="execute" returnType="void">
        <parameter type="org.gradle.play.internal.PlayApplicationBinarySpecInternal" name="playApplicationBinarySpec"/>
    </method>
    <method name="execute" returnType="void">
        <parameter type="org.gradle.play.tasks.PlayRun" name="playRun"/>
    </method>
    <method name="registerPlatformResolver" returnType="void">
        <parameter type="org.gradle.platform.base.internal.PlatformResolvers" name="platformResolvers"/>
    </method>
</type>


text: @import './node_modules/pikaday/css/pikaday.css';


text:
package test;

import java.util.Map;
import java.util.Stack;

/**
 * <p/>
 * User : krisjin
 * Date: 2015/10/12
 * Time: 9:57
 */

public class TestComm {

    private String name;
    private int age;
    private double money;

    public static void main(String[] args) {
        gc();
        int i = 16 / 16;
        System.out.println(i);
        Map<Integer, String> enumMap = EnumStaticMethod.getEnumMap();
        System.out.println(enumMap.size());
        Stack stack = new Stack();
        stack.add("name");
        stack.add("sex");

        Object object=stack.pop();
        System.out.println(object);

    }

    public static void gc() {
        System.gc();
    }
}


text:
La documentation de Material-UI est disponible dans les langues suivantes.

{{"demo": "pages/discover-more/languages/Languages.js", "hideHeader": true}}


text:
using System;
using ThriftSharp;

namespace PocketCampus.IsAcademia.Models
{
    [ThriftStruct( "StudyDay" )]
    public sealed class StudyDay
    {
        [ThriftField( 1, true, "day" )]
        [ThriftConverter( typeof( ThriftJavaDateConverter ) )]
        public DateTime Day { get; set; }

        [ThriftField( 2, true, "periods" )]
        public Period[] Periods { get; set; }
    }
}


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

@Component({
  selector: 'sellit-chat',
  templateUrl: './chat.component.html',
  styleUrls: ['./chat.component.scss']
})

export class ChatComponent {}