text:
package rapture.repo;

import java.net.HttpURLConnection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import org.antlr.runtime.ANTLRStringStream;
import org.antlr.runtime.CommonTokenStream;
import org.antlr.runtime.RecognitionException;
import org.apache.log4j.Logger;

import rapture.common.exception.ExceptionToString;
import rapture.common.exception.RaptureException;
import rapture.common.exception.RaptureExceptionFactory;
import rapture.dsl.ConfigDef;
import rapture.generated.RapGenLexer;
import rapture.generated.RapGenParser;
import rapture.lock.ILockingHandler;
import rapture.lock.LockFactory;
import rapture.repo.db.BackedKeyStore;
import rapture.repo.meta.CachedRepo;
import rapture.repo.meta.ReadOnlyRepo;
import rapture.repo.meta.ShadowedRepo;

/**
 * Generate iRepo instances from config strings
 *
 * @author alan
 */
public class RepoFactory {
    private static Logger log = Logger.getLogger(RepoFactory.class);
    private static final Map<Integer, String> keyStoreImplementationMap;
    private static final Map<Integer, String> sqlStoreImplementationMap;

    static {
        keyStoreImplementationMap = createKeystoreMap();

        Map<Integer, String> sqlSetupMap = new HashMap<Integer, String>();
        sqlSetupMap.put(RapGenLexer.JDBC, "rapture.repo.jdbc.JDBCSqlStore");
        sqlStoreImplementationMap = Collections.unmodifiableMap(sqlSetupMap);

        log.debug("Created implementation Map");
    }

    private static Map<Integer, String> createKeystoreMap() {
        Map<Integer, String> keyStoreSetupMap = new HashMap<Integer, String>();
        keyStoreSetupMap.put(RapGenLexer.MEMORY, "rapture.repo.mem.MemKeyStore");
        keyStoreSetupMap.put(RapGenLexer.REDIS, "rapture.repo.redis.RedisKeyStore");
        keyStoreSetupMap.put(RapGenLexer.AWS, "rapture.repo.aws.SimpleDbKeyStore");
        keyStoreSetupMap.put(RapGenLexer.MEMCACHED, "rapture.repo.memcache.MemCacheKeyStore");
        keyStoreSetupMap.put(RapGenLexer.FILE, "rapture.repo.file.FileDataStore");
        keyStoreSetupMap.put(RapGenLexer.MONGODB, "rapture.repo.mongodb.MongoDbDataStore");
        keyStoreSetupMap.put(RapGenLexer.EHCACHE, "rapture.repo.ehcache.EhCacheKeyStore");
        keyStoreSetupMap.put(RapGenLexer.CASSANDRA, "rapture.repo.cassandra.CassandraKeyStore");
        keyStoreSetupMap.put(RapGenLexer.CSV, "rapture.repo.file.CSVKeyStore");
        keyStoreSetupMap.put(RapGenLexer.POSTGRES, "rapture.repo.postgres.PostgresDataStore");
        return Collections.unmodifiableMap(keyStoreSetupMap);
    }

    private static SQLStore createSQLStore(int storeToken, String instanceName, Map<String, String> config) {
        if (sqlStoreImplementationMap.containsKey(storeToken)) {
            return getSQLStore(sqlStoreImplementationMap.get(storeToken), instanceName, config);
        } else {
            throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_INTERNAL_ERROR, "Unsupported sql store type");
        }
    }

    private static KeyStore createKeyStore(int storeToken, String instanceName, Map<String, String> config, boolean noFolderHandling) {
        if (keyStoreImplementationMap.containsKey(storeToken)) {
            return getKeyStore(keyStoreImplementationMap.get(storeToken), instanceName, config, noFolderHandling);
        } else {
            throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_INTERNAL_ERROR, "Unsupported key store type");
        }
    }

    private static ILockingHandler createLocker(int storeToken) {
        switch (storeToken) {
            //case RapGenLexer.MONGODB:
            //    return LockFactory.createLock("LOCKING USING MONGODB {}");
            default:
                return LockFactory.createLock("LOCKING USING DUMMY {}");
        }
    }

    private static Repository createKeyStoreBasedRepo(ConfigDef repConfig, KeyStore store, ILockingHandler locker) {
        if (repConfig.getName().equals("VREP")) {
            store.resetFolderHandling();
            return new VersionedRepo(repConfig.getConfig(), store, store.createRelatedKeyStore("cache"), locker);
        } else if (repConfig.getName().equals("REP")) {
            return new UnversionedRepo(repConfig.getConfig(), store, createMetaStore(store), createAttributeStore(store), locker);
        } else if (repConfig.getName().equals("NREP")) {
            log.debug("Creating NVersioned repo on " + store.getClass().toString());
            return new NVersionedRepo(repConfig.getConfig(), store, createVersionStore(store), createMetaStore(store),
                    createAttributeStore(store), locker);
        }
        return null;
    }

    private static KeyStore createVersionStore(KeyStore store) {
        return store.createRelatedKeyStore("version");
    }

    private static KeyStore createAttributeStore(KeyStore store) {
        return store.createRelatedKeyStore("attribute");
    }

    private static KeyStore createMetaStore(KeyStore store) {
        return store.createRelatedKeyStore("meta");
    }

    private static KeyStore getKeyStore(String className, String instanceName, Map<String, String> config, boolean noFolderHandling) {
        try {
            Class<?> idgenClass = Class.forName(className);
            Object fStore;
            fStore = idgenClass.newInstance();
            if (fStore instanceof KeyStore) {
                KeyStore ret = (KeyStore) fStore;
                ret.setInstanceName(instanceName);
                if (noFolderHandling) {
                    ret.resetFolderHandling();
                }
                ret.setConfig(config);
                return ret;
            } else {
                String message = className + " is not a repo, cannot instantiate";
                throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_INTERNAL_ERROR, message);
            }
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
            throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_INTERNAL_ERROR, "Could not create repo store of type " + className, e);
        }
    }

    private static SQLStore getSQLStore(String className, String instanceName, Map<String, String> config) {
        try {
            Class<?> idgenClass = Class.forName(className);
            Object fStore;
            fStore = idgenClass.newInstance();
            if (fStore instanceof SQLStore) {
                SQLStore ret = (SQLStore) fStore;
                ret.setInstanceName(instanceName);
                ret.setConfig(config);
                return ret;
            } else {
                throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_INTERNAL_ERROR, className + " is not a repo, cannot instantiate");
            }
        } catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
            throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_INTERNAL_ERROR, "Error instantiating sql store of type " + className, e);
        }
    }

    public static Repository getRepo(String config) {
        try {
            log.info("Creating repo from config - " + config);
            RapGenParser parser = parseConfig(config);
            String name = parser.getProcessorConfig().getName();
            if ((name != null) && name.equals("QREP")) {
                return createQRepo(parser);
            } else if ((name != null) && name.equals("RREP")){
            	return createRRepo(parser);
            } else {
                return createKeyRepo(parser);
            }

        } catch (RecognitionException e) {
            log.error(ExceptionToString.format(e));
            log.error("Error parsing config - " + e.getMessage());
        } catch (RaptureException e) {
            log.error(ExceptionToString.format(e));
            log.error("Error when initializing repo - " + e.getMessage());
        }
        return null;
    }

    private static Repository createQRepo(RapGenParser parser) {
        // Create a repo that uses a store that is inherently SQL based
        SQLStore baseSQLStore = createSQLStore(parser.getStoreType(), parser.getInstance(), parser.getImplementionConfig());
        return new QRepo(baseSQLStore, parser.getProcessorConfig().getConfig());
    }

    private static Repository createRRepo(RapGenParser parser) {
    	// Create a repo that uses a set of scripts to back the repo
    	return new RRepo(parser.getProcessorConfig().getConfig());
    }

    private static Repository createKeyRepo(RapGenParser parser) {
        // parser should have everything we want now

        int storeType = parser.getStoreType();
        ILockingHandler locker = createLocker(storeType);
        KeyStore baseKeyStore = createKeyStore(storeType, parser.getInstance(), parser.getImplementionConfig(),
                parser.getProcessorConfig().getName().equals("VREP"));
        if (parser.getCacheConfig() != null) {
            log.debug("Creating backed key store");
            KeyStore cacheStore = createKeyStore(parser.getCache().getType(), parser.getInstance(), parser.getCacheConfig().getConfig(), false);
            baseKeyStore = new BackedKeyStore(baseKeyStore, cacheStore);
        } else if (parser.getShadowConfig() != null) {
            log.debug("Creating shadowed key store");
            KeyStore shadowStore = createKeyStore(parser.getShadow().getType(), parser.getInstance(), parser.getShadowConfig().getConfig(), false);
            Repository shadowRepo = null;
            if (parser.getShadowType().getType() == RapGenLexer.SHADOW) {
                shadowRepo = new UnversionedRepo(null, shadowStore, createMetaStore(shadowStore), createAttributeStore(shadowStore), createLocker(
                        parser.getShadow().getType()));
            } else if (parser.getShadowType().getType() == RapGenLexer.VSHADOW) {
                shadowRepo = new VersionedRepo(null, shadowStore, shadowStore.createRelatedKeyStore("cache"), createLocker(parser.getShadow()
                        .getType()));
            } else {
                log.error("Really bad state when creating shadow repo");
            }
            if (parser.isGeneralCache()) {
                return new CachedRepo(createKeyStoreBasedRepo(parser.getProcessorConfig(), baseKeyStore, locker), shadowRepo);
            } else {
                return new ShadowedRepo(createKeyStoreBasedRepo(parser.getProcessorConfig(), baseKeyStore, locker), shadowRepo);
            }
        }
        if (parser.getReadOnly()) {
            return new ReadOnlyRepo(createKeyStoreBasedRepo(parser.getProcessorConfig(), baseKeyStore, locker));
        }
        return createKeyStoreBasedRepo(parser.getProcessorConfig(), baseKeyStore, locker);
    }

    private static RapGenParser parseConfig(String config) throws RecognitionException {
        RapGenLexer lexer = new RapGenLexer();
        lexer.setCharStream(new ANTLRStringStream(config));
        CommonTokenStream tokens = new CommonTokenStream(lexer);
        RapGenParser parser = new RapGenParser(tokens);
        parser.repinfo();
        return parser;
    }

    private RepoFactory() {
    }
}


text:
using System;

using Assman.Configuration;

using Spark;

namespace Assman.Spark
{
	public class SparkJavascriptAssmanPlugin : IAssmanPlugin
	{
		public void Initialize(AssmanContext context)
		{
			var finder = CreateFinder();

			context.AddFinder(finder);
		}

		private SparkResourceFinder CreateFinder()
		{
			var assemblies = AssmanConfiguration.Current.Assemblies.GetAssemblies();
			var contentFetcher = CreateContentFetcher();
			var actionFinder = CreateActionFinder();

			return new SparkResourceFinder(assemblies, contentFetcher, actionFinder);
		}

		protected virtual ISparkJavascriptActionFinder CreateActionFinder()
		{
			return new AttributeBasedActionFinder();
		}

		protected virtual ISparkResourceContentFetcher CreateContentFetcher()
		{
			var sparkSettings = GetSparkSettings();

			return new SparkResourceContentFetcher(sparkSettings);
		}

		protected virtual ISparkSettings GetSparkSettings()
		{
			return new SparkSettings();
		}
	}
}

redpajama_set_name: RedPajamaGithub


text:
namespace Microsoft.Graph
{
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Runtime.Serialization;
    using Newtonsoft.Json;

    /// <summary>
    /// The type ResponseStatus.
    /// </summary>
    [JsonObject(MemberSerialization = MemberSerialization.OptIn)]
    [JsonConverter(typeof(DerivedTypeConverter))]
    public partial class ResponseStatus
    {

        /// <summary>
        /// Gets or sets response.
        /// The response type: None = 0, Organizer = 1, TentativelyAccepted = 2, Accepted = 3, Declined = 4, NotResponded = 5. Possible values are: None, Organizer, TentativelyAccepted, Accepted, Declined, NotResponded.
        /// </summary>
        [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "response", Required = Newtonsoft.Json.Required.Default)]
        public ResponseType? Response { get; set; }

        /// <summary>
        /// Gets or sets time.
        /// The date and time that the response was returned. It uses ISO 8601 format and is always in UTC time. For example, midnight UTC on Jan 1, 2014 would look like this: '2014-01-01T00:00:00Z'
        /// </summary>
        [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "time", Required = Newtonsoft.Json.Required.Default)]
        public DateTimeOffset? Time { get; set; }

        /// <summary>
        /// Gets or sets additional data.
        /// </summary>
        [JsonExtensionData(ReadData = true)]
        public IDictionary<string, object> AdditionalData { get; set; }

    }
}


text:
(function ($) {

  Drupal.behaviors.fontyourfaceBrowse = {

    attach:function(context, settings) {

      $('#fontyourface-apply-tabs').tabs();;

      $('#fontyourface-apply-tabs .css-selector input').each(function(){

        var input = $(this);
        var selector = input.val();

        var select = $('<select><option value="">-- none --</option><option value="h1, h2, h3, h4, h5, h6">all headers (h1, h2, h3, h4, h5, h6)</option><option value="h1">h1</option><option value="h2">h2</option><option value="h3">h3</option><option value="p, div">standard text (p, div)</option><option value="body">everything (body)</option><option value="<none>">-- add selector in theme CSS --</option><option value="-- other --">other</option></select>')
          .change(fontyourfaceCssSelectChange)
          .insertBefore(input.parent());

        if (select.find('option[value="' + selector + '"]').length > 0) {

          select.find('option[value=' + selector + ']').attr('selected', true);
          input.hide();

        } // if
        else {

          select.find('option[value="-- other --"]').attr('selected', true);
          input.show();

        } // else

      });

    } // attach

  } // Drupal.behaviors.fontyourfaceAddForm

  function fontyourfaceCssSelectChange() {

    var select = $(this);
    var selector = select.val();
    var input = select.parent().find('input');
    var fontFamily = select.parent().attr('data-font-family');

    if (selector == '-- other --') {

      if (input.val() == '<none>') {
        input.val('');
      } // if

      input.show();

    } // if
    else {

      input.val(selector);
      input.hide();
      select.parent().find('.font-family').remove();

      if (selector == '<none>') {

        select.parent().append('
font-family: "' + fontFamily + '";
');

      } // if

    } // else

  } // fontyourfaceCssSelectChange

})(jQuery);


text:
Save/Get your Trello lists to/from your own server.

## Features
- Free Forever
- One-file script :)
- CAN AVOID THE Cross-Domain ISSUE!
- Configurable in few seconds
- Build-in dynamic jsonp response
- Return the json/jsonp file from the trello2file.php file
- Edit few lines to create tons of files with all the data containted in the cards
- Just call the trello2file.php file one time to generate/update all the json files
- Can be used with cronjobs (so it will auto-update everything, you can forget it exist)

### 2 Steps Installation
- drag trello2file.php into your server
- create a "jsons" folder with 777 permissions

### How to get the data
After completing the configuration setup (you can find how to do it just here below) you can get the generated json files in 2 ways:
- accessing directly to the generated json file (`http://yourserver.com/jsons/file.json`)
- (suggested) by calling the `trello2file.php` file, appending the file you want at the end of the url (`...php?file=yourFile`)

The last method can let you to make a jsonp call too! J ust add `&callback=yourFunction` after the file argument and you have your jsonp data!
```js
//JSON EXAMPLE
//example for a resturant
var url = "http://yourserver.com/trello2file.php?file=Menu";
//this will return the file 'jsons/Menu.json' (it must exists)

//JSONP EXAMPLE
var url = "http://yourserver.com/trello2file.php?file=Menu&callback=logData";

var logData = function(data){
  console.log("The JSON data are:");
  console.log(data);
}

```

### Configuration
- edit trello2file.php file
- put your api key ([take it from here](https://trello.com/app-key)) and the token key (from the app-key link click on the "Token" link a few lines below the key)
- add every lists you want to create a file for like
```js
var lists = {
  "hereTheFileName" : "hereTheIdOfTheList",
  "secondList" : "idOfSecondList"
}
```
This will create 2 files in the jsons folder, one with the name "hereTheFileName.json" containing all the cards in the first list and "secondList.json" with the cards of the second list.

Now is up to you :) I really can't make it simpler.

##TIPS and TRICKS
- To get the ID of a list open a card and edit the URL adding a ".json" at the end of it. Now search the "idList". Now you can use it in hte lists variable to get all its cards :)
- don't use spaces or special chars into the file names, so use just alphanumeric characters in the key of the lists variable or it should not work
- a good tip is to check the json files the system generate, at least the first time, to check that everything is generated correctly
- if you want to use JSONP functionality (to avoid the cross-domain limit) you must call the trello2file.php?file=FileName&callback=yourCallback ([little help here](https://github.com/portapipe/Trello2File/wiki/Cross-Domain-issue,-avoid-it-with-jsonp))


text:
OllyRTTI
=========
An OllyDbg 2.0 plugin for parsing RTTI.


text:
'use strict';

module.exports = {
  conversation: require('./services/conversation.service'),
  message: require('./services/message.service')
};


text:
describe('posts section', function() {
	beforeEach(module('Cimba.posts'));

	var PostsCtrl, $location, $root, $scope, $http, $sce, httpBackend;

	var webid, _channel;
	beforeEach(inject(function($controller, _$location_, $http, $sce, $rootScope, $httpBackend) {
		$location = _$location_;
		$root = $rootScope;
		$scope = $rootScope.$new();
		httpBackend = $httpBackend;
		PostsCtrl = $controller('PostsController', {
			$scope: $scope,
			$http: $http,
			$location: $location,
			$sce: $sce
		});

		webid = '//henchill.rww.io/profile/card#me';
		_channel = {
			uri: 'https://henchill.rww.io/storage/myfirstblog/ch1/',
			title: 'Channel1',
			owner: webid
		};

		$scope.login('https:' + webid);

	}));
/*
	it('should set the default channel', inject(function() {
		// expect($scope.defaultChannel).toBeUndefined();

		var chUri = _channel.uri;

		$scope.users = {
			webid: {
				channels: {
					chUri: _channel
				}
			}
		};
		$scope.setChannel(_channel.uri);
		expect($scope.defaultChannel).toBe(_channel);

	}));*/
});


text:
layout:     post
title:      "Freeline迁移记录"
subtitle:   "修复Gradle Plugin崩溃"
date:       2017-08-23
author:     "Retrox"
header-img: "img/home-bg.jpg"
tags:
- Android
- Freeline
- Gradle
---

# Freeline 迁移记录-1 修复Gradle Plugin崩溃

> Freeline是我认为Android Application增量最快的 在成功增量的情况下,可以保证时间在10s及以内

### 痛点

- 不支持Android Studio3.0的gradle plugin
- databinding的支持是烂的

## 分析问题

> 项目已配置好freeline

```groovy
buildscript {
    repositories {
        jcenter()
//        mavenLocal()
        google()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.0-beta2'
        classpath 'com.antfortune.freeline:gradle:0.8.7'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}
```

然后在Debug模式下运行Freeline

Boom在意料之中

追查log

```shell
> build failed with script: ./gradlew :app:assembleDebug -P freelineBuild=true --stacktrace

StackTrace:
-> Caused by: java.lang.IllegalStateException: Resolving configuration 'annotationProcessor' directly is not allowed
-> 追查Freeline源码部分
->
  at com.antfortune.freeline.FreelinePlugin.findAptConfig(FreelinePlugin.groovy:644)
	at com.antfortune.freeline.FreelinePlugin$_apply_closure4$_closure13$_closure19.doCall(FreelinePlugin.groovy:176)
	at com.antfortune.freeline.FreelinePlugin$_apply_closure4$_closure13.doCall(FreelinePlugin.groovy:156)
	at com.antfortune.freeline.FreelinePlugin$_apply_closure4.doCall(FreelinePlugin.groovy:51)
```

**追查结果 : 在findAptConfig里面出现了 不允许直接分析依赖的问题**

于是跑到Freeline源码里面

定位到这个方法里面的两行代码

```groovy
 def annotationProcessorConfig = project.configurations.findByName("annotationProcessor")
 def isAnnotationProcessor = annotationProcessorConfig != null && !annotationProcessorConfig.empty
// annotationProcessorConfig的直接访问导致抛出异常
// 因为最新的Gradle Plugin修改了Api
```

> 那怎么办呢???

于是 > 追查annotationProcessorConfig的类型及其源码

在源码分析到

```groovy
package org.gradle.api.artifacts;
public interface Configuration extends FileCollection, HasConfigurableAttributes<Configuration>
```

查看这个接口相关的方法,顺藤摸瓜

```groovy
    @Incubating
    void setCanBeResolved(boolean var1);
```

顾名思义

因此我们在Freeline源码中添加一行

```groovy
def annotationProcessorConfig = project.configurations.findByName("annotationProcessor")
@+++
        annotationProcessorConfig.setCanBeResolved(true)
@+++
        def isAnnotationProcessor = annotationProcessorConfig != null && !annotationProcessorConfig.empty
```

**问题解决 !**

于是我们开心的再次跑起了Freeline

Boom!

又来了

```groovy
Caused by: groovy.lang.MissingPropertyException: Could not get unknown property 'apkvariantData' for object of type com.android.build.gradle.internal.api.ApplicationVariantImpl.
```

查看栈回溯 Freeline相关代码

```groovy
                boolean multiDexEnabled = variant.apkvariantData.variantConfiguration.isMultiDexEnabled()

```

很显然...这个变量或者这个方法没了

从外层闭包开始看

```groovy
project.android.applicationVariants.each { variant -> ... }
```

看Foreach里面的varient类型

```groovy
public DomainObjectSet<ApplicationVariant> getApplicationVariants() {
        return this.applicationVariantList;
    }
```

然后去ApplicationVariant

```groovy
public interface ApplicationVariant extends ApkVariant, TestedVariant {
}
```

```groovy
public class ApplicationVariantImpl extends ApkVariantImpl implements ApplicationVariant {
    private final ApplicationVariantData variantData;
    private TestVariant testVariant = null;
    private UnitTestVariant unitTestVariant = null;

    public ApplicationVariantImpl(ApplicationVariantData variantData, ObjectFactory objectFactory, AndroidBuilder androidBuilder, ReadOnlyObjectProvider readOnlyObjectProvider, NamedDomainObjectContainer<BaseVariantOutput> outputs) {
        super(objectFactory, androidBuilder, readOnlyObjectProvider, outputs);
        this.variantData = variantData;
    }

  //看见没...名字改了
    public ApkVariantData getVariantData() {
        return this.variantData;
    }

   ......
}

```

于是改源码一行:

```groovy
                boolean multiDexEnabled = variant.variantData.variantConfiguration.isMultiDexEnabled()
//之前是apkvariantData
```

成功解决

当然....不可能这么容易跑通

下一个问题 在AndroidManifest的获取上

Gradle Android最新版Plugin不允许直接通过Api获取Manifest的地址(取消了那个api)

但是因为Android Manifest编译中在build目录的地址是相对固定的

原代码

```groovy
if (applicationProxy) {
                    variant.outputs.each { output ->
                        output.processManifest.outputs.upToDateWhen { false }
                        output.processManifest.doLast {
                            def manifestOutFile = output.processManifest.manifestOutputFile
                            if (manifestOutFile.exists()) {
                                println "find manifest file path: ${manifestOutFile.absolutePath}"
                                replaceApplication(manifestOutFile.absolutePath as String)
                            }
                        }
                    }
                }
```

修改后

```groovy
output.processManifest.doLast {
                            def path = "${project.buildDir}/intermediates/manifests/full/debug/AndroidManifest.xml"
                            def manifestFile = new File(path)
                            if (manifestFile.exists()){
                                println "find manifest file path: ${manifestFile.absolutePath}"
                                replaceApplication(manifestFile.absolutePath as String)
                            }
                        }
```

目前修复了Gradle Plugin的兼容性问题...

但是还没有结束


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Q42.HueApi.Models.Bridge;

namespace Q42.HueApi
{
  /// <summary>
  /// Uses the special nupnp url from meethue.com to find registered bridges based on your external IP
  /// </summary>
  public class HttpBridgeLocator : BridgeLocator
  {
    private readonly Uri NuPnPUrl = new Uri("https://discovery.meethue.com");

    /// <summary>
    /// Locate bridges
    /// </summary>
    /// <param name="cancellationToken">Token to cancel the search</param>
    /// <returns>List of bridge IPs found</returns>
    public override async Task<IEnumerable<LocatedBridge>> LocateBridgesAsync(CancellationToken cancellationToken)
    {
      using (var response = await _httpClient.GetAsync(NuPnPUrl, cancellationToken).ConfigureAwait(false))
      {
        if (response.IsSuccessStatusCode && !cancellationToken.IsCancellationRequested)
        {
          string content = await response.Content.ReadAsStringAsync();

          NuPnPResponse[]? responseModel = JsonConvert.DeserializeObject<NuPnPResponse[]>(content);
          if (responseModel != null)
          {
            var locatedBridges = responseModel.Select(x => new LocatedBridge() { BridgeId = x.Id, IpAddress = x.InternalIpAddress }).ToList();
            locatedBridges.ForEach(OnBridgeFound);
            return locatedBridges;
          }
          else
            return Enumerable.Empty<LocatedBridge>();
        }
        else
        {
          return new List<LocatedBridge>();
        }
      }
    }
  }
}


text:
@interface FLModalPresentationBehavior : NSObject<FLPresentationBehavior> {
@private
    UIViewController* _shieldViewController;
}

FLSingletonProperty(FLModalPresentationBehavior);

@end


text:
<!DOCTYPE html>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, minimum-scale=1.0, initial-scale=1.0, user-scalable=yes">
  <title>WebAssembly High-Level Goals - WebAssembly 中文网</title>
  <link rel="stylesheet" type="text/css" href="/css/custom.css">
  <meta name="keywords" content="wsam,WebAssembly中国,wsam中文">
  <meta mame="description" content="WebAssembly 中文网是一个依附于WebAssembly官网内容的开源中文社区">

      概述
      Demo
      快速开始

      文档
      社区
      路线图
      FAQ
      中文交流

      多个浏览器已经达成对初始 WebAssembly 版本的一致意见 查看更多

WebAssembly High-Level Goals

Define a portable, size- and load-time-efficient
binary format to serve as a compilation target which
can be compiled to execute at native speed by taking advantage of common
hardware capabilities available on a wide range of platforms, including
mobile and
IoT.

Specify and implement incrementally:

a Minimum Viable Product (MVP) for the standard with
roughly the same functionality as asm.js, primarily
aimed at C/C++;

additional features ,
initially focused on key features like threads,
zero cost exceptions, and SIMD,
follow by additional features
prioritized by feedback and experience, including support for languages
other than C/C++.

Design to execute within and integrate well with the existing
Web platform:

maintain the versionless, feature-tested and backwards-compatible evolution story of the Web;

execute in the same semantic universe as JavaScript;

allow synchronous calls to and from JavaScript;

enforce the same-origin and permissions security policies;

access browser functionality through the same Web APIs that are accessible
to JavaScript; and

define a human-editable text format that is convertible to and from the
binary format, supporting View Source functionality.

Design to support non-browser embeddings as well.

Make a great platform:

build a new LLVM backend for WebAssembly and an accompanying
clang port (why LLVM first?);

promote other compilers and tools targeting WebAssembly; and

enable other useful tooling.

文档

        WebAssembly High-Level Goals

        JavaScript API

        Binary Encoding

        Text Format

        Semantics

        Modules

        FAQ

        Design Rationale

        Minimum Viable Product

        Features to add after the MVP

        Portability

        Security

        Nondeterminism in WebAssembly

        Guide for C/C++ developers

        Web Embedding

        Non-Web Embeddings

        Feature Test

        Tooling support

        GC / DOM / Web API Integration

        JIT and Optimization Library

        Dynamic linking

        使用场景


text:
using System;

using FarseerPhysics.Dynamics;
using FarseerPhysics.Factories;
using FarseerPhysics.Dynamics.Joints;

using Duality.Editor;
using Duality.Resources;

namespace Duality.Components.Physics
{
	/// <summary>
	/// This joint allows the RigidBody to travel on a specific axis relative to another body. It can be limited to a certain area and driven by a motor force.
	/// </summary>
	public sealed class PrismaticJointInfo : JointInfo
	{
		private	Vector2		localAnchorA	= Vector2.Zero;
		private	Vector2		localAnchorB	= Vector2.Zero;
		private	Vector2		moveAxis		= Vector2.UnitX;
		private	bool		limitEnabled	= false;
		private	float		lowerLimit		= 0.0f;
		private	float		upperLimit		= 0.0f;
		private	bool		motorEnabled	= false;
		private float		maxMotorForce	= 0.0f;
		private float		motorSpeed		= 0.0f;
		private	float		refAngle		= 0.0f;

		/// <summary>
		/// [GET / SET] The local anchor point on the first RigidBody.
		/// </summary>
		[EditorHintIncrement(1)]
		public Vector2 LocalAnchorA
		{
			get { return this.localAnchorA; }
			set { this.localAnchorA = value; this.UpdateJoint(); }
		}
		/// <summary>
		/// [GET / SET] The local anchor point on the second RigidBody.
		/// </summary>
		[EditorHintIncrement(1)]
		public Vector2 LocalAnchorB
		{
			get { return this.localAnchorB; }
			set { this.localAnchorB = value; this.UpdateJoint(); }
		}
		/// <summary>
		/// [GET / SET] The axis on which the body may move.
		/// </summary>
		public Vector2 MovementAxis
		{
			get { return this.moveAxis; }
			set { this.moveAxis = (value == Vector2.Zero) ? Vector2.UnitX : value; this.UpdateJoint(); }
		}
		/// <summary>
		/// [GET / SET] Is the joint limited in its movement?
		/// </summary>
		public bool LimitEnabled
		{
			get { return this.limitEnabled; }
			set { this.limitEnabled = value; this.UpdateJoint(); }
		}
		/// <summary>
		/// [GET / SET] The lower joint limit.
		/// </summary>
		[EditorHintIncrement(1)]
		public float LowerLimit
		{
			get { return this.lowerLimit; }
			set { this.lowerLimit = MathF.Min(value, this.upperLimit); this.UpdateJoint(); }
		}
		/// <summary>
		/// [GET / SET] The upper joint limit.
		/// </summary>
		[EditorHintIncrement(1)]
		public float UpperLimit
		{
			get { return this.upperLimit; }
			set { this.upperLimit = MathF.Max(value, this.lowerLimit); this.UpdateJoint(); }
		}
		/// <summary>
		/// [GET / SET] Is the joint motor enabled?
		/// </summary>
		public bool MotorEnabled
		{
			get { return this.motorEnabled; }
			set { this.motorEnabled = value; this.UpdateJoint(); }
		}
		/// <summary>
		/// [GET / SET] The maximum motor force.
		/// </summary>
		[EditorHintIncrement(1.0f)]
		[EditorHintDecimalPlaces(1)]
		[EditorHintRange(0, 10000, 0, 500)]
		public float MaxMotorForce
		{
			get { return this.maxMotorForce; }
			set { this.maxMotorForce = value; this.UpdateJoint(); }
		}
		/// <summary>
		/// [GET / SET] The desired motor speed.
		/// </summary>
		[EditorHintIncrement(1)]
		public float MotorSpeed
		{
			get { return this.motorSpeed; }
			set { this.motorSpeed = value; this.UpdateJoint(); }
		}
		/// <summary>
		/// [GET] The current joint speed.
		/// </summary>
		[EditorHintFlags(MemberFlags.Invisible)]
		public float JointSpeed
		{
			get { return this.joint == null ? 0.0f : (PhysicsUnit.VelocityToDuality * (this.joint as PrismaticJoint).JointSpeed); }
		}
		/// <summary>
		/// [GET] The current joint translation.
		/// </summary>
		[EditorHintFlags(MemberFlags.Invisible)]
		public float JointTranslation
		{
			get { return this.joint == null ? 0.0f : (PhysicsUnit.LengthToDuality * (this.joint as PrismaticJoint).JointTranslation); }
		}
		/// <summary>
		/// [GET] The current joint motor force.
		/// </summary>
		[EditorHintFlags(MemberFlags.Invisible)]
		public float MotorForce
		{
			get { return this.joint == null ? 0.0f : (PhysicsUnit.ForceToDuality * (this.joint as PrismaticJoint).MotorForce * Time.SecondsPerFrame); }
		}
		/// <summary>
		/// [GET / SET] The reference angle that is used to constrain the bodies angle.
		/// </summary>
		[EditorHintIncrement(MathF.RadAngle1)]
		public float ReferenceAngle
		{
			get { return this.refAngle; }
			set { this.refAngle = MathF.NormalizeAngle(value); this.UpdateJoint(); }
		}

		protected override Joint CreateJoint(World world, Body bodyA, Body bodyB)
		{
			return bodyA != null && bodyB != null ? JointFactory.CreatePrismaticJoint(world, bodyA, bodyB, Vector2.Zero, Vector2.UnitX) : null;
		}
		internal override void UpdateJoint()
		{
			base.UpdateJoint();
			if (this.joint == null) return;

			PrismaticJoint j = this.joint as PrismaticJoint;
			j.LocalAnchorA = GetFarseerPoint(this.ParentBody, this.localAnchorA);
			j.LocalAnchorB = GetFarseerPoint(this.OtherBody, this.localAnchorB);
			j.ReferenceAngle = this.refAngle;
			// Farseer gotcha: Setter is in world coordinates even though getter returns local coordinates.
			// Movement axis is relative to OtherBody, as that reflects Farseer behavior.
			j.LocalXAxis1 = this.OtherBody.GameObj.Transform.GetWorldVector(this.moveAxis).Normalized;
			j.LimitEnabled = this.limitEnabled;
			j.LowerLimit = -PhysicsUnit.LengthToPhysical * this.upperLimit;
			j.UpperLimit = -PhysicsUnit.LengthToPhysical * this.lowerLimit;
			j.MotorEnabled = this.motorEnabled;
			j.MotorSpeed = -PhysicsUnit.VelocityToPhysical * this.motorSpeed;
			j.MaxMotorForce = PhysicsUnit.ForceToPhysical * this.maxMotorForce;
		}
	}
}


text:
def extractSpiritGodShura(item):
	"""
	# Sousetsuka
	"""
	vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
	if not (chp or vol) or 'preview' in item['title'].lower():
		return None
	if item['title'].startswith('Chapter') and item['tags'] == ['Chapters']:
		if ':' in item['title'] and not postfix:
			postfix = item['title'].split(':')[-1]
		return buildReleaseMessageWithType(item, 'Spirit God Shura', vol, chp, postfix=postfix, tl_type='oel')
	return False


text:
<!--
  Copyright (C) 2008 by Frank Richter

  This library is free software; you can redistribute it and/or
  modify it under the terms of the GNU Library General Public
  License as published by the Free Software Foundation; either
  version 2 of the License, or (at your option) any later version.

  This library is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  Library General Public License for more details.

  You should have received a copy of the GNU Library General Public
  License along with this library; if not, write to the Free
  Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
-->
<snippet>
  <technique priority="100">
    <combiner name="cg" plugin="crystalspace.graphics3d.shader.combiner.glcg" />

    <block location="cg:vertexMain">
      specularColor = float3(0);
      specularColor_attr_perfragment = false;
    </block>

    <block location="cg:fragmentMain">
      specularColor = float3(0);
      specularColor_attr_perfragment = false;
    </block>

    <output name="specularColor" type="rgb">
      <attribute name="perfragment" type="bool" />
    </output>
  </technique>
</snippet>


text:
package pro.taskana.common.internal.util;

import java.util.Collection;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

public class CollectionUtil {

  private CollectionUtil() {
    throw new IllegalStateException("Utility class");
  }

  /**
   * Splits a collection with objects of type T into chunks of a certain size.
   *
   * @param <T> type of elements inside collection
   * @param inputCollection collection to be divided
   * @param size maximal number of elements inside chunk
   * @return list containing the chunks
   */
  public static <T> Collection<List<T>> partitionBasedOnSize(
      Collection<T> inputCollection, int size) {
    final AtomicInteger counter = new AtomicInteger(0);
    return inputCollection.stream()
        .collect(Collectors.groupingBy(s -> counter.getAndIncrement() / size))
        .values();
  }
}


text:
using System;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Mozlite.Data.Internal;
using Mozlite.Data.Migrations;
using Mozlite.Data.Migrations.Models;
using Mozlite.Data.Query;
using Mozlite.Data.Query.Translators;
using Mozlite.Data.SqlServer.Migrations;
using Mozlite.Data.SqlServer.Query;
using Mozlite.Data.SqlServer.Query.Translators;

namespace Mozlite.Data.SqlServer
{
    /// <summary>
    /// 数据库相关的服务器扩展。
    /// </summary>
    public static class ServiceExtensions
    {
        /// <summary>
        /// 添加SQLServer数据库服务。
        /// </summary>
        /// <param name="serviceCollection">服务集合。</param>
        /// <param name="configuration">配置实例。</param>
        /// <returns>返回服务集合实例。</returns>
        public static IServiceCollection AddSqlServer(this IServiceCollection serviceCollection, IConfiguration configuration)
        {
            var connectionString = configuration["Data:Name"];
            if (connectionString == null)
                connectionString = configuration["Data:ConnectionString"];
            else
                connectionString = $"Data Source=.;Initial Catalog={connectionString};Integrated Security=True";
            return serviceCollection.AddSqlServer(options =>
            {
                options.ConnectionString = connectionString;
                options.Prefix = configuration["Data:Prefix"];
                options.Schema = configuration["Data:Schema"];
            });
        }

        /// <summary>
        /// 添加SQLServer数据库服务。
        /// </summary>
        /// <param name="serviceCollection">服务集合。</param>
        /// <param name="options">数据源选项。</param>
        /// <returns>返回服务集合实例。</returns>
        public static IServiceCollection AddSqlServer(this IServiceCollection serviceCollection, Action<DatabaseOptions> options)
        {
            Check.NotNull(serviceCollection, nameof(serviceCollection));
            Check.NotNull(options, nameof(options));
            var source = new DatabaseOptions();
            options(source);

            return serviceCollection
                .AddSingleton<IDatabase, SqlServerDatabase>()
                .Configure<DatabaseOptions>(o =>
                {
                    o.ConnectionString = source.ConnectionString;
                    o.Prefix = source.Prefix?.Trim();
                    o.Schema = source.Schema;
                    o.Provider = "SqlServer";
                })
                .AddScoped(typeof(IRepository<>), typeof(Repository<>))
                .AddTransient<IMigrator, Migrator>()
                .AddTransient<IMigrationRepository, SqlServerMigrationRepository>()
                .AddTransient<IMigrationsSqlGenerator, MigrationsSqlServerGenerator>()
                .AddSingleton<ISqlGenerator, SqlServerGenerator>()
                .AddSingleton<ITypeMapper, SqlServerTypeMapper>()
                .AddSingleton<ISqlHelper, SqlServerHelper>()
                .AddSingleton<IMemberTranslator, SqlServerCompositeMemberTranslator>()
                .AddSingleton<IMethodCallTranslator, SqlServerCompositeMethodCallTranslator>()
                .AddSingleton<IExpressionFragmentTranslator, SqlServerCompositeExpressionFragmentTranslator>()
                .AddSingleton<IExpressionVisitorFactory, SqlServerExpressionVisitorFactory>();
        }
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Mycol. Pap. 114: 39 (1968)

#### Original name
Brachysporium harunganae Hansf.

### Remarks
null


text:
from django.db import models
from django.conf import settings

from django_extensions.db.fields import RandomCharField

# Used to generate the random URLs for profiles, posts, and other.
class RandomSlugModel(models.Model):
    slug = RandomCharField(length=8, lowercase=True, unique=True)

    class Meta:
        abstract = True

class UserProfile(RandomSlugModel):
    """
    This is an extension to the default User model, created on
    registration for each user. All relations to a User are through
    this model to maintain separation from the authentication backend.
    """
    ACCOUNT_TYPE_CHOICES = (
        ('0', "I'm a buyer"),
        ('1', "I'm a seller"),
    )

    user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='profile')

    type = models.CharField(max_length=1, choices=ACCOUNT_TYPE_CHOICES, default='0')
    name = models.CharField('name', max_length=200)
    @property
    def is_seller(self):
        return self.type == self.ACCOUNT_TYPE_CHOICES[1][0]

    def __str__(self):
        return self.name


text:
<!DOCTYPE html>

    <meta charset="utf-8">

    <title>Love Travel HTML5</title>
    <meta name="description" content="Love Travel HTML5 version">
    <meta name="author" content="nicDark">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <link rel="stylesheet" href="css/style.css">
    <link rel="stylesheet" href="css/grid.css">
    <link rel="stylesheet" href="css/responsive.css">
    <link rel="stylesheet" href="rs-plugin/css/settings.css" media="screen" />
    <link rel="stylesheet" href="showbizpro/css/settings.css" media="screen" />
    <link rel="stylesheet" href="css/animate.css">
    <link rel="stylesheet" href="css/superfish.css" media="screen">
    <link rel="stylesheet" href="css/fancybox/jquery.fancybox.css">
    <link rel="stylesheet" href="css/fancybox/jquery.fancybox-thumbs.css">
    <link rel="stylesheet" href="css/isotope.css">
    <link rel="stylesheet" href="css/flexslider.css">

    <link href='http://fonts.googleapis.com/css?family=Signika:400,300,600,700' rel='stylesheet' type='text/css'>

    <link rel="shortcut icon" href="img/favicon/favicon.ico">
    <link rel="apple-touch-icon" href="img/favicon/apple-touch-icon.png">
    <link rel="apple-touch-icon" sizes="72x72" href="img/favicon/apple-touch-icon-72x72.png">
    <link rel="apple-touch-icon" sizes="114x114" href="img/favicon/apple-touch-icon-114x114.png">

OUR BEST DESTINATIONS

NORT AMERICA

New York

Los Angeles

San Francisco

See more

SOUTH AMERICA

Rio De Janeiro

Buenos Aires

Ushuaia

See more

EUROPE

Rome

Paris

London

See more

        HOME

Slider Full Width

Slider Full Screen

Carousel Version

				One Page Version

Normal Style

Transparent Style

				Home Full Screen

With Light Menu

With Dark Menu

        PAGES

                Our Prices

                Our Tours

                Our Destinations

                About us

First Solution

Second Solution

Third Solution

                Our Team

                Single Project

                Page

With right sidebar

With left sidebar

Full Width

Centered Page

                Grid System

        GALLERY

                Gallery with same size

2 column

3 column

4 column

                Gallery With Filter

2 column

3 column

4 column

                Gallery Masonry

2 column

3 column

4 column

                Gallery Masonry With Filter

2 column

3 column

4 column

        BLOG

                Blog Standard

With right sidebar

With left sidebar

Full Width Archive

Centered Archive

                Blog Masonry Infinite Scroll

2 columns

3 columns

4 columns

                Blog Masonry With Pagination

2 columns

3 columns

4 columns

                Single Post

With right sidebar

With left sidebar

Full Width Post

Centered Post

        CONTACTS

                Dark Map

                Color Map

                With Text

        PURCHASE

    <form role="search" method="get" id="searchform" class="searchform" action="#">

            SEARCH
            <input type="text" value="" name="s" id="s" />
            <input type="submit" id="searchsubmit" value="Search" />

    </form>

ADVENTURE

Lorem ipsum dolor sit amet

RELAX

Lorem ipsum dolor sit amet

HONEYMOON

Lorem ipsum dolor sit amet

OUR AGENCY

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin cursus, elit vitae fermentum hendrerit, neque erat fringilla nibh, vel sodales sem diam nec nunc. Donec mattis blandit metus ut volutpat. Quisque orci lectus, sodales at cursus et, gravida quis nisl. Donec mattis blandit metus ut volutpat. Quisque orci lectus, sodales at cursus et, gravida quis nisl

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin cursus, elit vitae fermentum hendrerit, neque erat fringilla nibh, vel sodales sem diam nec nunc. Donec mattis blandit metus ut volutpat. Quisque orci lectus, sodales at cursus et, gravida quis nisl. Donec mattis blandit metus ut volutpat. Quisque orci lectus, sodales at cursus et, gravida quis nisl

HONEYMOON - 100%

PACKAGE TOURS - 70%

FLY AND DRIVE - 60%

TRAVEL RELAX - 90%

OUR GALLERY

SHOW ALL12

Filter 1

Filter 2

Filter 3

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

OUR TEAM

JANE MC DOE

Owner

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus ut cursus eros. Interdum et malesuada fames ac ante ipsum primis in faucibus.

NICK HOPE

Cofounder

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus ut cursus eros. Interdum et malesuada fames ac ante ipsum primis in faucibus.

JULIETTE LIGHT

Sales Agent

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus ut cursus eros. Interdum et malesuada fames ac ante ipsum primis in faucibus.

MARK SPITCH

Sales Agent

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus ut cursus eros. Interdum et malesuada fames ac ante ipsum primis in faucibus.

OUR CLIENTS

LOVE TRAVEL

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque arcu lorem, mattis quis convallis ac

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque arcu lorem, mattis quis convallis ac

CONTACTS

Address: Broadway Road 234 - 35127
Phone: +001 3072341187
Mail: info@lovetravel.com

TWEET

NEWSLETTER

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque arcu lorem, mattis quis convallis ac

                <form class="newsletterfooter">
                	<input type="text" />
                    <input type="submit" />
                </form>

© Copyright 2013 by Nicdark - All Rights Reserved


text:
        Article Average

        {{ view_objects.average_rating.starstring }}

	{{ view_objects.average_rating.rating }}

Full Stats ►


text:
def run(whatweb, pluginname):
    whatweb.recog_from_file(pluginname, "doc/page/login.asp", "Hikvision")


text:
const { graphql } = require(`graphql`)
const { createSchemaComposer } = require(`../schema-composer`)
const { buildSchema } = require(`../schema`)
const { LocalNodeModel } = require(`../node-model`)
const { store } = require(`../../redux`)
const { actions } = require(`../../redux/actions`)

jest.mock(`../../redux/actions/add-page-dependency`)
import { createPageDependency } from "../../redux/actions/add-page-dependency"

jest.mock(`gatsby-cli/lib/reporter`, () => {
  return {
    log: jest.fn(),
    info: jest.fn(),
    warn: jest.fn(),
    error: jest.fn(),
    activityTimer: () => {
      return {
        start: jest.fn(),
        setStatus: jest.fn(),
        end: jest.fn(),
      }
    },
    phantomActivity: () => {
      return {
        start: jest.fn(),
        end: jest.fn(),
      }
    },
  }
})

const makeNodes = () => [
  {
    id: `p1`,
    internal: { type: `Parent`, contentDigest: `0` },
    hair: `red`,
    children: [`c1`, `c2`, `r1`],
  },
  {
    id: `r1`,
    internal: { type: `Relative`, contentDigest: `0` },
    hair: `black`,
    children: [],
    parent: `p1`,
  },
  {
    id: `c1`,
    internal: { type: `Child`, contentDigest: `0` },
    hair: `brown`,
    children: [],
    parent: `p1`,
  },
  {
    id: `c2`,
    internal: { type: `Child`, contentDigest: `0` },
    hair: `blonde`,
    children: [],
    parent: `p1`,
  },
]

describe(`build-node-connections`, () => {
  async function runQuery(query, nodes = makeNodes()) {
    store.dispatch({ type: `DELETE_CACHE` })
    store.dispatch({ type: `START_INCREMENTAL_INFERENCE` })
    nodes.forEach(node =>
      actions.createNode(node, { name: `test` })(store.dispatch)
    )

    const schemaComposer = createSchemaComposer()
    const schema = await buildSchema({
      schemaComposer,
      types: [],
      thirdPartySchemas: [],
      inferenceMetadata: store.getState().inferenceMetadata,
    })
    store.dispatch({ type: `SET_SCHEMA`, payload: schema })

    const context = { path: `foo` }
    const { data, errors } = await graphql({
      schema,
      source: query,
      rootValue: undefined,
      contextValue: {
        ...context,
        nodeModel: new LocalNodeModel({
          schemaComposer,
          schema,
          createPageDependency,
        }),
      },
    })
    expect(errors).not.toBeDefined()
    return data
  }

  afterEach(() => {
    createPageDependency.mockClear()
  })

  it(`should result in a valid queryable schema`, async () => {
    const { allParent, allChild, allRelative } = await runQuery(
      `
      {
        allParent(filter: { id: { eq: "p1" } }) {
          edges {
            node {
              hair
            }
          }
        }
        allChild(filter: { id: { eq: "c1" } }) {
          edges {
            node {
              hair
            }
          }
        }
        allRelative(filter: { id: { eq: "r1" } }) {
          edges {
            node {
              hair
            }
          }
        }
      }
    `
    )
    expect(allParent.edges[0].node.hair).toEqual(`red`)
    expect(allChild.edges[0].node.hair).toEqual(`brown`)
    expect(allRelative.edges[0].node.hair).toEqual(`black`)
  })

  it(`should link children automatically`, async () => {
    const { allParent } = await runQuery(
      `
      {
        allParent(filter: { id: { eq: "p1" } }) {
          edges {
            node {
              children {
                id
              }
            }
          }
        }
      }
    `
    )
    expect(allParent.edges[0].node.children).toBeDefined()
    expect(allParent.edges[0].node.children.map(c => c.id)).toEqual([
      `c1`,
      `c2`,
      `r1`,
    ])
  })

  it(`should create typed children fields`, async () => {
    const { allParent } = await runQuery(
      `
      {
        allParent(filter: { id: { eq: "p1" } }) {
          edges {
            node {
              childrenChild { # lol
                id
              }
            }
          }
        }
      }
    `
    )
    expect(allParent.edges[0].node.childrenChild).toBeDefined()
    expect(allParent.edges[0].node.childrenChild.map(c => c.id)).toEqual([
      `c1`,
      `c2`,
    ])
  })

  it(`should create typed child field for singular children`, async () => {
    const { allParent } = await runQuery(
      `
      {
        allParent(filter: { id: { eq: "p1" } }) {
          edges {
            node {
              childRelative { # lol
                id
              }
              childrenRelative {
                id
              }
            }
          }
        }
      }
    `
    )

    expect(allParent.edges[0].node.childRelative).toBeDefined()
    expect(allParent.edges[0].node.childRelative.id).toEqual(`r1`)

    expect(allParent.edges[0].node.childrenRelative).toBeDefined()
    expect(allParent.edges[0].node.childrenRelative).toEqual([{ id: `r1` }])
  })

  it(`should create page dependency`, async () => {
    await runQuery(
      `
      {
        allParent(filter: { id: { eq: "p1" } }) {
          edges {
            node {
              childRelative { # lol
                id
              }
            }
          }
        }
      }
    `
    )

    expect(createPageDependency).toHaveBeenCalledWith({
      path: `foo`,
      connection: `Parent`,
    })
  })
})


text:
namespace remoting {
namespace protocol {

namespace {

// Value is chosen to balance the extra latency against the reduced
// load due to ACK traffic.
const int kTcpAckDelayMilliseconds = 10;

// Values for the TCP send and receive buffer size. This should be tuned to
// accommodate high latency network but not backlog the decoding pipeline.
const int kTcpReceiveBufferSize = 256 * 1024;
const int kTcpSendBufferSize = kTcpReceiveBufferSize + 30 * 1024;

// Try connecting ICE twice with timeout of 15 seconds for each attempt.
const int kMaxReconnectAttempts = 2;
const int kReconnectDelaySeconds = 15;

// Get fresh STUN/Relay configuration every hour.
const int kJingleInfoUpdatePeriodSeconds = 3600;

class LibjingleStreamTransport
    : public StreamTransport,
      public base::SupportsWeakPtr<LibjingleStreamTransport>,
      public sigslot::has_slots<> {
 public:
  LibjingleStreamTransport(cricket::PortAllocator* port_allocator,
                           const NetworkSettings& network_settings);
  virtual ~LibjingleStreamTransport();

  // Called by JingleTransportFactory when it has fresh Jingle info.
  void OnCanStart();

  // StreamTransport interface.
  virtual void Initialize(
      const std::string& name,
      Transport::EventHandler* event_handler,
      scoped_ptr<ChannelAuthenticator> authenticator) OVERRIDE;
  virtual void Connect(
      const StreamTransport::ConnectedCallback& callback) OVERRIDE;
  virtual void AddRemoteCandidate(const cricket::Candidate& candidate) OVERRIDE;
  virtual const std::string& name() const OVERRIDE;
  virtual bool is_connected() const OVERRIDE;

 private:
  void DoStart();

  // Signal handlers for cricket::TransportChannel.
  void OnRequestSignaling(cricket::TransportChannelImpl* channel);
  void OnCandidateReady(cricket::TransportChannelImpl* channel,
                        const cricket::Candidate& candidate);
  void OnRouteChange(cricket::TransportChannel* channel,
                     const cricket::Candidate& candidate);
  void OnWritableState(cricket::TransportChannel* channel);

  // Callback for PseudoTcpAdapter::Connect().
  void OnTcpConnected(int result);

  // Callback for Authenticator::SecureAndAuthenticate();
  void OnAuthenticationDone(net::Error error,
                            scoped_ptr<net::StreamSocket> socket);

  // Callback for jingle_glue::TransportChannelSocketAdapter to notify when the
  // socket is destroyed.
  void OnChannelDestroyed();

  // Tries to connect by restarting ICE. Called by |reconnect_timer_|.
  void TryReconnect();

  // Helper methods to call |callback_|.
  void NotifyConnected(scoped_ptr<net::StreamSocket> socket);
  void NotifyConnectFailed();

  cricket::PortAllocator* port_allocator_;
  NetworkSettings network_settings_;

  std::string name_;
  EventHandler* event_handler_;
  StreamTransport::ConnectedCallback callback_;
  scoped_ptr<ChannelAuthenticator> authenticator_;
  std::string ice_username_fragment_;
  std::string ice_password_;

  bool can_start_;

  std::list<cricket::Candidate> pending_candidates_;
  scoped_ptr<cricket::P2PTransportChannel> channel_;
  bool channel_was_writable_;
  int connect_attempts_left_;
  base::RepeatingTimer<LibjingleStreamTransport> reconnect_timer_;

  // We own |socket_| until it is connected.
  scoped_ptr<jingle_glue::PseudoTcpAdapter> socket_;

  DISALLOW_COPY_AND_ASSIGN(LibjingleStreamTransport);
};

LibjingleStreamTransport::LibjingleStreamTransport(
    cricket::PortAllocator* port_allocator,
    const NetworkSettings& network_settings)
    : port_allocator_(port_allocator),
      network_settings_(network_settings),
      event_handler_(NULL),
      ice_username_fragment_(
          rtc::CreateRandomString(cricket::ICE_UFRAG_LENGTH)),
      ice_password_(rtc::CreateRandomString(cricket::ICE_PWD_LENGTH)),
      can_start_(false),
      channel_was_writable_(false),
      connect_attempts_left_(kMaxReconnectAttempts) {
  DCHECK(!ice_username_fragment_.empty());
  DCHECK(!ice_password_.empty());
}

LibjingleStreamTransport::~LibjingleStreamTransport() {
  DCHECK(event_handler_);
  event_handler_->OnTransportDeleted(this);
  // Channel should be already destroyed if we were connected.
  DCHECK(!is_connected() || socket_.get() == NULL);

  if (channel_.get()) {
    base::ThreadTaskRunnerHandle::Get()->DeleteSoon(
        FROM_HERE, channel_.release());
  }
}

void LibjingleStreamTransport::OnCanStart() {
  DCHECK(CalledOnValidThread());

  DCHECK(!can_start_);
  can_start_ = true;

  // If Connect() has been called then start connection.
  if (!callback_.is_null())
    DoStart();

  while (!pending_candidates_.empty()) {
    channel_->OnCandidate(pending_candidates_.front());
    pending_candidates_.pop_front();
  }
}

void LibjingleStreamTransport::Initialize(
    const std::string& name,
    Transport::EventHandler* event_handler,
    scoped_ptr<ChannelAuthenticator> authenticator) {
  DCHECK(CalledOnValidThread());

  DCHECK(!name.empty());
  DCHECK(event_handler);

  // Can be initialized only once.
  DCHECK(name_.empty());

  name_ = name;
  event_handler_ = event_handler;
  authenticator_ = authenticator.Pass();
}

void LibjingleStreamTransport::Connect(
    const StreamTransport::ConnectedCallback& callback) {
  DCHECK(CalledOnValidThread());
  callback_ = callback;

  if (can_start_)
    DoStart();
}

void LibjingleStreamTransport::DoStart() {
  DCHECK(!channel_.get());

  // Create P2PTransportChannel, attach signal handlers and connect it.
  // TODO(sergeyu): Specify correct component ID for the channel.
  channel_.reset(new cricket::P2PTransportChannel(
      std::string(), 0, NULL, port_allocator_));
  channel_->SetIceProtocolType(cricket::ICEPROTO_GOOGLE);
  channel_->SetIceCredentials(ice_username_fragment_, ice_password_);
  channel_->SignalRequestSignaling.connect(
      this, &LibjingleStreamTransport::OnRequestSignaling);
  channel_->SignalCandidateReady.connect(
      this, &LibjingleStreamTransport::OnCandidateReady);
  channel_->SignalRouteChange.connect(
      this, &LibjingleStreamTransport::OnRouteChange);
  channel_->SignalWritableState.connect(
      this, &LibjingleStreamTransport::OnWritableState);
  channel_->set_incoming_only(
      !(network_settings_.flags & NetworkSettings::NAT_TRAVERSAL_OUTGOING));

  channel_->Connect();

  --connect_attempts_left_;

  // Start reconnection timer.
  reconnect_timer_.Start(
      FROM_HERE, base::TimeDelta::FromSeconds(kReconnectDelaySeconds),
      this, &LibjingleStreamTransport::TryReconnect);

  // Create net::Socket adapter for the P2PTransportChannel.
  scoped_ptr<jingle_glue::TransportChannelSocketAdapter> channel_adapter(
      new jingle_glue::TransportChannelSocketAdapter(channel_.get()));

  channel_adapter->SetOnDestroyedCallback(base::Bind(
      &LibjingleStreamTransport::OnChannelDestroyed, base::Unretained(this)));

  // Configure and connect PseudoTCP adapter.
  socket_.reset(
      new jingle_glue::PseudoTcpAdapter(channel_adapter.release()));
  socket_->SetSendBufferSize(kTcpSendBufferSize);
  socket_->SetReceiveBufferSize(kTcpReceiveBufferSize);
  socket_->SetNoDelay(true);
  socket_->SetAckDelay(kTcpAckDelayMilliseconds);

  // TODO(sergeyu): This is a hack to improve latency of the video
  // channel. Consider removing it once we have better flow control
  // implemented.
  if (name_ == kVideoChannelName)
    socket_->SetWriteWaitsForSend(true);

  int result = socket_->Connect(
      base::Bind(&LibjingleStreamTransport::OnTcpConnected,
                 base::Unretained(this)));
  if (result != net::ERR_IO_PENDING)
    OnTcpConnected(result);
}

void LibjingleStreamTransport::AddRemoteCandidate(
    const cricket::Candidate& candidate) {
  DCHECK(CalledOnValidThread());

  // To enforce the no-relay setting, it's not enough to not produce relay
  // candidates. It's also necessary to discard remote relay candidates.
  bool relay_allowed = (network_settings_.flags &
                        NetworkSettings::NAT_TRAVERSAL_RELAY) != 0;
  if (!relay_allowed && candidate.type() == cricket::RELAY_PORT_TYPE)
    return;

  if (channel_) {
    channel_->OnCandidate(candidate);
  } else {
    pending_candidates_.push_back(candidate);
  }
}

const std::string& LibjingleStreamTransport::name() const {
  DCHECK(CalledOnValidThread());
  return name_;
}

bool LibjingleStreamTransport::is_connected() const {
  DCHECK(CalledOnValidThread());
  return callback_.is_null();
}

void LibjingleStreamTransport::OnRequestSignaling(
    cricket::TransportChannelImpl* channel) {
  DCHECK(CalledOnValidThread());
  channel_->OnSignalingReady();
}

void LibjingleStreamTransport::OnCandidateReady(
    cricket::TransportChannelImpl* channel,
    const cricket::Candidate& candidate) {
  DCHECK(CalledOnValidThread());
  event_handler_->OnTransportCandidate(this, candidate);
}

void LibjingleStreamTransport::OnRouteChange(
    cricket::TransportChannel* channel,
    const cricket::Candidate& candidate) {
  TransportRoute route;

  if (candidate.type() == "local") {
    route.type = TransportRoute::DIRECT;
  } else if (candidate.type() == "stun") {
    route.type = TransportRoute::STUN;
  } else if (candidate.type() == "relay") {
    route.type = TransportRoute::RELAY;
  } else {
    LOG(FATAL) << "Unknown candidate type: " << candidate.type();
  }

  if (!jingle_glue::SocketAddressToIPEndPoint(
          candidate.address(), &route.remote_address)) {
    LOG(FATAL) << "Failed to convert peer IP address.";
  }

  DCHECK(channel_->best_connection());
  const cricket::Candidate& local_candidate =
      channel_->best_connection()->local_candidate();
  if (!jingle_glue::SocketAddressToIPEndPoint(
          local_candidate.address(), &route.local_address)) {
    LOG(FATAL) << "Failed to convert local IP address.";
  }

  event_handler_->OnTransportRouteChange(this, route);
}

void LibjingleStreamTransport::OnWritableState(
    cricket::TransportChannel* channel) {
  DCHECK_EQ(channel, channel_.get());

  if (channel->writable()) {
    channel_was_writable_ = true;
    connect_attempts_left_ = kMaxReconnectAttempts;
    reconnect_timer_.Stop();
  } else if (!channel->writable() && channel_was_writable_) {
    reconnect_timer_.Reset();
    TryReconnect();
  }
}

void LibjingleStreamTransport::OnTcpConnected(int result) {
  DCHECK(CalledOnValidThread());

  if (result != net::OK) {
    NotifyConnectFailed();
    return;
  }

  authenticator_->SecureAndAuthenticate(
      socket_.PassAs<net::StreamSocket>(),
      base::Bind(&LibjingleStreamTransport::OnAuthenticationDone,
                 base::Unretained(this)));
}

void LibjingleStreamTransport::OnAuthenticationDone(
    net::Error error,
    scoped_ptr<net::StreamSocket> socket) {
  if (error != net::OK) {
    NotifyConnectFailed();
    return;
  }

  NotifyConnected(socket.Pass());
}

void LibjingleStreamTransport::OnChannelDestroyed() {
  if (is_connected()) {
    // The connection socket is being deleted, so delete the transport too.
    delete this;
  }
}

void LibjingleStreamTransport::TryReconnect() {
  DCHECK(!channel_->writable());

  if (connect_attempts_left_ <= 0) {
    reconnect_timer_.Stop();

    // Notify the caller that ICE connection has failed - normally that will
    // terminate Jingle connection (i.e. the transport will be destroyed).
    event_handler_->OnTransportFailed(this);
    return;
  }
  --connect_attempts_left_;

  // Restart ICE by resetting ICE password.
  ice_password_ = rtc::CreateRandomString(cricket::ICE_PWD_LENGTH);
  channel_->SetIceCredentials(ice_username_fragment_, ice_password_);
}

void LibjingleStreamTransport::NotifyConnected(
    scoped_ptr<net::StreamSocket> socket) {
  DCHECK(!is_connected());
  StreamTransport::ConnectedCallback callback = callback_;
  callback_.Reset();
  callback.Run(socket.Pass());
}

void LibjingleStreamTransport::NotifyConnectFailed() {
  DCHECK(!is_connected());

  socket_.reset();

  // This method may be called in response to a libjingle signal, so
  // libjingle objects must be deleted asynchronously.
  if (channel_.get()) {
    base::ThreadTaskRunnerHandle::Get()->DeleteSoon(
        FROM_HERE, channel_.release());
  }

  authenticator_.reset();

  NotifyConnected(scoped_ptr<net::StreamSocket>());
}

}  // namespace

LibjingleTransportFactory::LibjingleTransportFactory(
    SignalStrategy* signal_strategy,
    scoped_ptr<cricket::HttpPortAllocatorBase> port_allocator,
    const NetworkSettings& network_settings)
    : signal_strategy_(signal_strategy),
      port_allocator_(port_allocator.Pass()),
      network_settings_(network_settings) {
}

LibjingleTransportFactory::~LibjingleTransportFactory() {
  // This method may be called in response to a libjingle signal, so
  // libjingle objects must be deleted asynchronously.
  scoped_refptr<base::SingleThreadTaskRunner> task_runner =
      base::ThreadTaskRunnerHandle::Get();
  task_runner->DeleteSoon(FROM_HERE, port_allocator_.release());
}

void LibjingleTransportFactory::PrepareTokens() {
  EnsureFreshJingleInfo();
}

scoped_ptr<StreamTransport> LibjingleTransportFactory::CreateStreamTransport() {
  scoped_ptr<LibjingleStreamTransport> result(
      new LibjingleStreamTransport(port_allocator_.get(), network_settings_));

  EnsureFreshJingleInfo();

  // If there is a pending |jingle_info_request_| delay starting the new
  // transport until the request is finished.
  if (jingle_info_request_) {
    on_jingle_info_callbacks_.push_back(
        base::Bind(&LibjingleStreamTransport::OnCanStart,
                   result->AsWeakPtr()));
  } else {
    result->OnCanStart();
  }

  return result.PassAs<StreamTransport>();
}

scoped_ptr<DatagramTransport>
LibjingleTransportFactory::CreateDatagramTransport() {
  NOTIMPLEMENTED();
  return scoped_ptr<DatagramTransport>();
}

void LibjingleTransportFactory::EnsureFreshJingleInfo() {
  uint32 stun_or_relay_flags = NetworkSettings::NAT_TRAVERSAL_STUN |
      NetworkSettings::NAT_TRAVERSAL_RELAY;
  if (!(network_settings_.flags & stun_or_relay_flags) ||
      jingle_info_request_) {
    return;
  }

  if (base::TimeTicks::Now() - last_jingle_info_update_time_ >
      base::TimeDelta::FromSeconds(kJingleInfoUpdatePeriodSeconds)) {
    jingle_info_request_.reset(new JingleInfoRequest(signal_strategy_));
    jingle_info_request_->Send(base::Bind(
        &LibjingleTransportFactory::OnJingleInfo, base::Unretained(this)));
  }
}

void LibjingleTransportFactory::OnJingleInfo(
    const std::string& relay_token,
    const std::vector<std::string>& relay_hosts,
    const std::vector<rtc::SocketAddress>& stun_hosts) {
  if (!relay_token.empty() && !relay_hosts.empty()) {
    port_allocator_->SetRelayHosts(relay_hosts);
    port_allocator_->SetRelayToken(relay_token);
  }
  if (!stun_hosts.empty()) {
    port_allocator_->SetStunHosts(stun_hosts);
  }

  jingle_info_request_.reset();
  if ((!relay_token.empty() && !relay_hosts.empty()) || !stun_hosts.empty())
    last_jingle_info_update_time_ = base::TimeTicks::Now();

  while (!on_jingle_info_callbacks_.empty()) {
    on_jingle_info_callbacks_.begin()->Run();
    on_jingle_info_callbacks_.pop_front();
  }
}

}  // namespace protocol
}  // namespace remoting


text:
'use strict';

var http = require('https');
var Promise = require('bluebird');
var Url = require('url');

var Pinger = (function () {

  var options = { protocol: 'https:', host: 'api.syncano.io', method: 'HEAD' };
  var timeout = 5000;
  var interval = null;
  var onConnectCb = null;
  var onDisconnectCb = null;
  var connected = null;

  function ping() {
    var time = Date.now();
    var req = http.request(options, function (res) {
      connected = true;
      if (onConnectCb) onConnectCb();
    });

    req.on('error', function () {
      connected = false;
      if (onDisconnectCb) onDisconnectCb();
    });

    req.end();
  }

  function startPinging() {
    interval = setInterval(function () {
      ping();
    }, timeout);
  }

  function stopPinging() {
    if (interval) clearInterval(interval);
  }

  function setConnectCallback(cb) {
    onConnectCb = cb;
  }

  function setDisconnectCallback(cb) {
    onDisconnectCb = cb;
  }

  function getConnected() {
    return connected;
  }

  function setBaseUrl(url) {
    options.url = Url.parse(url).host;
  }

  return {
    start: startPinging,
    onConnect: setConnectCallback,
    onDisconnect: setDisconnectCallback,
    isConnected: getConnected,
    setUrl: setBaseUrl
  };
})();

module.exports = Pinger;


text:
NS_ASSUME_NONNULL_BEGIN

@class STPObscuredCardView;

@protocol STPObscuredCardViewDelegate <NSObject>

- (void)obscuredCardViewDidClear:(STPObscuredCardView *)cardView;

@end

@interface STPObscuredCardView : UIView

@property(nonatomic)STPTheme *theme;
@property(nonatomic, weak)id<STPObscuredCardViewDelegate>delegate;
@property(nonatomic, weak)UIView *inputAccessoryView;
- (void)configureWithCard:(STPCard *)card;
- (void)clear;
- (BOOL)isEmpty;

@end

NS_ASSUME_NONNULL_END


text:
namespace Stripe
{
    using System;
    using System.Collections.Generic;
    using Newtonsoft.Json;
    using Stripe.Infrastructure;

    public class PromotionCodeCreateOptions : BaseOptions, IHasMetadata
    {
        ///
        /// Whether the promotion code is currently active.
        ///
        [JsonProperty("active")]
        public bool? Active { get; set; }

        ///
        /// The customer-facing code. Regardless of case, this code must be unique across all active
        /// promotion codes for a specific customer. If left blank, we will generate one
        /// automatically.
        ///
        [JsonProperty("code")]
        public string Code { get; set; }

        ///
        /// The coupon for this promotion code.
        ///
        [JsonProperty("coupon")]
        public string Coupon { get; set; }

        ///
        /// The customer that this promotion code can be used by. If not set, the promotion code can
        /// be used by all customers.
        ///
        [JsonProperty("customer")]
        public string Customer { get; set; }

        ///
        /// The timestamp at which this promotion code will expire. If the coupon has specified a
        /// <c>redeems_by</c>, then this value cannot be after the coupon's <c>redeems_by</c>.
        ///
        [JsonProperty("expires_at")]
        [JsonConverter(typeof(UnixDateTimeConverter))]
        public DateTime? ExpiresAt { get; set; }

        ///
        /// A positive integer specifying the number of times the promotion code can be redeemed. If
        /// the coupon has specified a <c>max_redemptions</c>, then this value cannot be greater
        /// than the coupon's <c>max_redemptions</c>.
        ///
        [JsonProperty("max_redemptions")]
        public long? MaxRedemptions { get; set; }

        ///
        /// Set of key-value pairs that you can
        /// attach to an object. This can be useful for storing additional information about the
        /// object in a structured format. Individual keys can be unset by posting an empty value to
        /// them. All keys can be unset by posting an empty value to <c>metadata</c>.
        ///
        [JsonProperty("metadata")]
        public Dictionary<string, string> Metadata { get; set; }

        ///
        /// Settings that restrict the redemption of the promotion code.
        ///
        [JsonProperty("restrictions")]
        public PromotionCodeRestrictionsOptions Restrictions { get; set; }
    }
}


text:
package cn.binarywang.wx.miniapp.bean.shop;

import com.google.gson.annotations.SerializedName;
import java.io.Serializable;
import lombok.Data;

/**
 * @author leiin
 * created on  2021/3/23
 */
@Data
public class WxMaShopAddOrderResult implements Serializable {
  private static final long serialVersionUID = -6574489801942310752L;

  /**
   * 交易组件平台订单ID
   */
  @SerializedName("order_id")
  private Long orderId;
  /**
   * 交易组件平台订单ID
   */
  @SerializedName("out_order_id")
  private String outOrderId;
  /**
   * 拉起收银台的ticket
   */
  @SerializedName("ticket")
  private String ticket;
  /**
   * ticket有效截止时间
   */
  @SerializedName("ticket_expire_time")
  private String ticketExpireTime;
  /**
   * 订单最终价格(单位:分)
   */
  @SerializedName("final_price")
  private Integer finalPrice;

}


text:
package com.cloudinary.photoalbum;

public final class Constants {
	private Constants() {
	}
	public static final String TAG = "CloudinarySample";
	public static final String EXTRA_PHOTO = "com.cloudinary.photo";
	public static final String PARSE_MODEL = "Photo";
	public static final String PARSE_CLOUDINARY_FIELD = "cloudinaryIdentifier";
	public static final String PARSE_SIGN_CLOUD_FUNCTION = "sign_cloudinary_upload_request";
	public static final int SPLASH_SCREEN_TIMEOUT = 1000;
}


text:
hb.define('matchAllOthersSpec', ['matchAllOthers'], function(matchAllOthers) {
    describe('matchAllOthers', function () {
        it("should create a new array", function() {
            var ary = [0, 1, 2];
            matchAllOthers(ary, 3);
            expect(ary.length).toBe(3);
        });

        it("should not remove any if the items do not match", function() {
            var ary = [0, 1, 2];
            var result = matchAllOthers(ary, 3, 4);
            expect(result.length).toBe(3);
        });

        it("should remove any items that match with objects", function() {
            var ary = [{id:0}, {id:1}, {id:1}];
            var result = matchAllOthers(ary, {id:1});
            expect(result.length).toBe(1);
            expect(result[0].id).toBe(0);
        });
    })
});


text:
package com.abc.kafka.example;

import java.util.Date;
import java.util.Properties;
import java.util.Random;

import kafka.javaapi.producer.Producer;
import kafka.producer.KeyedMessage;
import kafka.producer.ProducerConfig;

public class KafkaProducer {

	public static void main(String[] args) {
		long events = 100;
		Random rnd = new Random();

		Properties props = new Properties();
		props.put("metadata.broker.list", "localhost:9091");
		props.put("producer.type", "sync");
		props.put("serializer.class", "kafka.serializer.StringEncoder");
		//props.put("partitioner.class", "com.abc.kafka.example.KafkaPartitionar");
		props.put("request.required.acks", "1");
		ProducerConfig config = new ProducerConfig(props);
		Producer<String, String> producer = new Producer<String, String>(config);
		for (long nEvents = 0; nEvents < events; nEvents++) {
			System.out.println("creating event " + nEvents);
			long runtime = new Date().getTime();
			String ip = "Abhishek_Test" + rnd.nextInt(255);
			String msg = runtime + ",www.abc.com," + ip;
			KeyedMessage<String, String> data = new KeyedMessage<String, String>("test", ip, msg);
			producer.send(data);
		}
		producer.close();
	}

}


text:
package com.laytonsmith.abstraction;

import com.laytonsmith.abstraction.enums.MCDisplaySlot;

public interface MCObjective {

	String getCriteria();

	String getDisplayName();

	MCDisplaySlot getDisplaySlot();

	String getName();

	MCScore getScore(String entry);

	MCScoreboard getScoreboard();

	boolean isModifiable();

	void setDisplayName(String displayName);

	void setDisplaySlot(MCDisplaySlot slot);

	void unregister();
}


text:
FactoryGirl.define do
  factory :comment do
    body 'I love this movie!'
    sequence(:name) { |n| "Anonymous #{n}" }
    movie
  end
end


text:
package com.amazonaws.services.transfer.model;

import javax.annotation.Generated;

/**
 *
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public enum ExecutionErrorType {

    PERMISSION_DENIED("PERMISSION_DENIED"),
    CUSTOM_STEP_FAILED("CUSTOM_STEP_FAILED"),
    THROTTLED("THROTTLED"),
    ALREADY_EXISTS("ALREADY_EXISTS"),
    NOT_FOUND("NOT_FOUND"),
    BAD_REQUEST("BAD_REQUEST"),
    TIMEOUT("TIMEOUT"),
    INTERNAL_SERVER_ERROR("INTERNAL_SERVER_ERROR");

    private String value;

    private ExecutionErrorType(String value) {
        this.value = value;
    }

    @Override
    public String toString() {
        return this.value;
    }

    /**
     * Use this in place of valueOf.
     *
     * @param value
     *        real value
     * @return ExecutionErrorType corresponding to the value
     *
     * @throws IllegalArgumentException
     *         If the specified value does not map to one of the known values in this enum.
     */
    public static ExecutionErrorType fromValue(String value) {
        if (value == null || "".equals(value)) {
            throw new IllegalArgumentException("Value cannot be null or empty!");
        }

        for (ExecutionErrorType enumEntry : ExecutionErrorType.values()) {
            if (enumEntry.toString().equals(value)) {
                return enumEntry;
            }
        }

        throw new IllegalArgumentException("Cannot create enum from " + value + " value!");
    }
}


text:
package cz.mjanys.web.login.pto;

/**
 * @author Martin Janys
 */
public class LoginPto {

    private String username_;
    private String password_;

    public String getUsername_() {
        return username_;
    }

    public void setUsername_(String username_) {
        this.username_ = username_;
    }

    public String getPassword_() {
        return password_;
    }

    public void setPassword_(String password_) {
        this.password_ = password_;
    }
}


text:
package teamoortcloud.entities;

import javafx.scene.canvas.GraphicsContext;
import javafx.scene.image.Image;

public class CustomerCharacter {

	public static final int STATE_LINE = 0;
	public static final int STATE_SITTING = 1;

	int x, y;
	float vel = 2.5f;

	Image image;
	boolean traveling = false;
	int travelX, travelY;
	int state;

	public CustomerCharacter(Image image, int x, int y) {
		this.image = image;
		this.state = STATE_LINE;
		this.x = x;
		this.y = y;
	}

	public void draw(GraphicsContext gc) {
		gc.drawImage(image, x, y, 16, 16);
	}

	public void update() {
		if(traveling) {
			//Stop if at destination
			if(x == travelX && y == travelY) traveling = false;

			//Travel to coords
			if(x != travelX) {
				if(x < travelX) x += vel;
				else x -= vel;
			}
			if(y != travelY) {
				if(y < travelY) y += vel;
				else y -= vel;
			}
		}
	}

	public void travelTo(int x, int y) {
		traveling = true;
		travelX = x;
		travelY = y;
	}

	public void stopTraveling() {
		traveling = false;
	}

	public int getState() {
		return state;
	}

	public void setState(int state) {
		this.state = state;
	}

}


text:
#ifndef ALIHFJETSCONTAINERVERTEX_H
#define ALIHFJETSCONTAINERVERTEX_H

/* mailto: svallero@to.infn.it */

/* Class defining containers for the HF b-jets analysis */

//--Root--
class TClonesArray;

//--AliRoot--
class AliAODVertex;
class AliEmcalJet;

//--AliHFJetsClass--
#include "AliHFJetsUtils.h"
#include "AliHFJetsContainer.h"
#include "AliHFJetsTaggingVertex.h"

//-------------------------------------------------------------------------------------

class AliHFJetsContainerVertex : public AliHFJetsContainer {

 public:

  static const Int_t fgkContTypes = 3;

  enum EContTYPE {

    kJetVtxSim  = 0,
    kJetVtxData = 1,
    kQaVtx
  };

  const char *fgStrContType(EContTYPE type) {

    switch(type) {

      case kJetVtxSim :
        return "kJetVtxSim";

      case kJetVtxData:
        return "kJetVtxData";

      case kQaVtx:
        return "kQaVtx";
    }

    return "invalid";
  }

  // Constructors
  AliHFJetsContainerVertex();

  AliHFJetsContainerVertex(const char *name, EContTYPE contType);

  AliHFJetsContainerVertex(const AliHFJetsContainerVertex &c);

  // Destructor
  virtual ~AliHFJetsContainerVertex();

  // Assignment operator
  AliHFJetsContainerVertex &operator=(const AliHFJetsContainerVertex &corr);

  virtual void FillStepJetVtxSim(CFSteps                step,
                                 const Int_t            nSVtx,
                                 Double_t               evtMult,          // Event multiplicity (not used yet)
                                 Double_t               jetPt_wBkgRej,    // Jet's pt after background subtraction
                                 vctr_pair_dbl_int     &arrVtxDisp,       // Vector of pair with SV_vtx and SV_sigma
                                 const TClonesArray    *arrVtxHF,
                                 const AliAODVertex    *primVtx,
                                 const AliEmcalJet     *jet,
                                 const TClonesArray    *mcPart,
                                 const Double_t        *partonnat,
                                 const Double_t        *partpt,
                                 Double_t               wght);

  virtual void FillStepJetVtxData(CFSteps               step,
                                  const Int_t           nSVtx,
                                  Double_t              evtMult,
                                  Double_t              jetPt_wBkgRej,
                                  vctr_pair_dbl_int    &arrVtxDisp,
                                  const TClonesArray   *arrVtxHF,
                                  const AliAODVertex   *primVtx,
                                  const AliEmcalJet    *jet,
                                  Double_t              wght);

  virtual void FillStepQaVtx(CFSteps                    step,
                             const Int_t                nSVtx,
                             Double_t                   evtMult,
                             const AliAODVertex        *primVtx,
                             const AliEmcalJet         *jet,
                             const TClonesArray        *arrVtxHF,
                             const TClonesArray        *mcPart,
                             vctr_pair_dbl_int         &arrVtxDisp,
                             Double_t                  *p,
                             Double_t                   wght);

protected:

  // Useful tools
  void Copy(TObject &c) const;

  void CreateContainerVertex(EContTYPE contType = kJetVtxSim);  // create containers belonging to this class

  void GetBinningVertex(TString     var,
                        Int_t      &nBins,
                        Double_t   *bins,
                        const char *&axistitle);                // returns array of bin limts for relevant vars

private:

  EContTYPE fType;                   // container type

  AliHFJetsTaggingVertex *fTagger;    // to use tagging methods

  ClassDef(AliHFJetsContainerVertex, 2)    // containers for HF b-jets analysis
};

#endif


text:
<?php

namespace Segony\Debug;

/**
 * @author    Marc Binder <marcandrebinder@gmail.com>
 * @copyright Segony
 * @license   http://opensource.org/licenses/MIT
 */
interface Debuggable
{

    public function getDebugId();
    public function getDebugInfo();

}


text:
namespace maf {

    std::shared_ptr<MafComm> MafComm::_Init() {
        int initialized;
        MPI_Initialized(&initialized);

        if (!initialized) {
            int argc = 0;
            MPI_Init(&argc, (char***)NULL);
        }

        int rank, size;
        MPI_Comm_rank(MPI_COMM_WORLD, &rank);
        MPI_Comm_size(MPI_COMM_WORLD, &size);
        return std::shared_ptr<MafComm>(new MafComm(MPI_COMM_WORLD, rank, size, true));
    }

    std::shared_ptr<MafComm> MafComm::_World = MafComm::_Init();

    std::shared_ptr<MafComm> MafComm::World = MafComm::_World;

    MPI_Comm MafComm::WorldComm = MafComm::_World->communicator;

    MafComm::MafComm(MPI_Comm communicator, int rank, int size, bool is_root)
        : communicator(communicator), rank(rank), size(size), is_root(is_root) {

    }

    MafComm::~MafComm() {
        if (this->is_root) {
            MafComm::Finalize();
        }
    }

    void MafComm::Finalize() {
        int finalized;
        MPI_Finalized(&finalized);
        if (!finalized) {
            MPI_Finalize();
        }
    }

    std::shared_ptr<MafComm> MafComm::split(int color) {
        return this->shared_from_this();
    }

    void MafComm::take_over_the_world() {
        MafComm::World = this->shared_from_this();
        MafComm::WorldComm = this->communicator;
    }

    void MafComm::prepare_for_tomorrow_night() {
        MafComm::World->take_over_the_world();
    }

    void MafComm::abort(int exit_code) {
        MPI_Abort(MafComm::_World->communicator, exit_code);
    }

    void MafComm::barrier() {
        MPI_Barrier(this->communicator);
    }

    template<>
    std::string MafComm::bcast<std::string>(std::string msg, int root) {
        int size = msg.size();
        MPI_Bcast((void*)&size, sizeof(size), MPI_INT, root, this->communicator);

        if (this->rank == root) {
            MPI_Bcast((void*)msg.data(), size, MPI_CHAR, root, this->communicator);
            return msg;
        }
        else {
            std::string buffer = std::string(size, ' ');
            MPI_Bcast((void*)buffer.data(), size, MPI_CHAR, root, this->communicator);
            return buffer;
        }
    }

}


text:
<?xml version="1.0" encoding="ISO-8859-1"?>
<?xml-stylesheet href="latest_ob.xsl" type="text/xsl"?>
<current_observation version="1.0"
	 xmlns:xsd="http://www.w3.org/2001/XMLSchema"
	 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	 xsi:noNamespaceSchemaLocation="http://www.weather.gov/view/current_observation.xsd">
	<credit>NOAA's National Weather Service</credit>
	<credit_URL>http://weather.gov/</credit_URL>
	<image>
		<url>http://weather.gov/images/xml_logo.gif</url>
		<title>NOAA's National Weather Service</title>
		<link>http://weather.gov</link>
	</image>
	<suggested_pickup>15 minutes after the hour</suggested_pickup>
	<suggested_pickup_period>60</suggested_pickup_period>
	<location>Unknown Station</location>
	<station_id>NFTF</station_id>
	<observation_time>Last Updated on Jan 4 2016, 8:00 pm EST</observation_time>
        <observation_time_rfc822>Mon, 04 Jan 2016 20:00:00 -0500</observation_time_rfc822>
	<weather>A Few Clouds</weather>
	<temperature_string>88.0 F (31.0 C)</temperature_string>
	<temp_f>88.0</temp_f>
	<temp_c>31.0</temp_c>
	<relative_humidity>75</relative_humidity>
	<wind_string>East at 8.1 MPH (7 KT)</wind_string>
	<wind_dir>East</wind_dir>
	<wind_degrees>80</wind_degrees>
	<wind_mph>8.1</wind_mph>
	<wind_kt>7</wind_kt>
	<dewpoint_string>78.8 F (26.0 C)</dewpoint_string>
	<dewpoint_f>78.8</dewpoint_f>
	<dewpoint_c>26.0</dewpoint_c>
	<heat_index_string>103 F (39 C)</heat_index_string>
      	<heat_index_f>103</heat_index_f>
      	<heat_index_c>39</heat_index_c>
 	<icon_url_base>http://forecast.weather.gov/images/wtf/small/</icon_url_base>
	<two_day_history_url>http://www.weather.gov/data/obhistory/NFTF.html</two_day_history_url>
	<icon_url_name>nfew.png</icon_url_name>
	<ob_url>http://www.weather.gov/data/METAR/NFTF.1.txt</ob_url>
	<disclaimer_url>http://weather.gov/disclaimer.html</disclaimer_url>
	<copyright_url>http://weather.gov/disclaimer.html</copyright_url>
	<privacy_policy_url>http://weather.gov/notice.html</privacy_policy_url>
</current_observation>


text:
<?php

namespace PHPixie\Filesystem\Locators\Locator;

class Mount implements \PHPixie\Filesystem\Locators\Locator
{
    protected $locatorRegistry;
    protected $configData;

    protected $locator;

    public function __construct($locatorRegistry, $configData)
    {
        $this->locatorRegistry = $locatorRegistry;
        $this->configData      = $configData;
    }

    public function locate($path, $isDirectory = false)
    {
        return $this->locator()->locate($path, $isDirectory);
    }

    protected function locator()
    {
        if($this->locator === null) {
            $name = $this->configData->getRequired('name');
            $this->locator = $this->locatorRegistry->get($name);
        }

        return $this->locator;
    }
}