text:
Reading
=======

Some of the items in the list are taken from: https://github.com/analytics/analytics/blob/master/notes/papers.md, others I have added along the way.

# Reasonning about consistency

All of these relate to consistency reasoning within the context of a given store, but the concepts map upwards hoefully...

* [Replicated Data Types: Specification, Verification, Optimality](http://software.imdea.org/~gotsman/papers/distrmm-popl14.pdf)
* [Consistency Analysis in Bloom: a CALM and Collected Approach](http://db.cs.berkeley.edu/papers/cidr11-bloom.pdf)
* [CRDTs: Consistency without concurrency control](http://pagesperso-systeme.lip6.fr/Marc.Shapiro/papers/RR-6956.pdf)
* [A comprehensive study of Convergent and Commutative Replicated Data Types](http://hal.upmc.fr/docs/00/55/55/88/PDF/techreport.pdf)
*

# Query processing

* [PIQL – Scale Independent Query Processing](http://www.eecs.berkeley.edu/~marmbrus/papers/piql.vldb12.pdf)
* Lingual research here...

# Machine Learning - Storage and computational foundations

* [Materialization Optimizations for Feature Selection Workloads](./papers/mod539-zhang.pdf)
* [LINVIEW: Incremental View Maintenance for Complex Analytical Queries](./papers/mod447-nikolic.pdf)
* [Opportunistic Physical Design for Big Data Analytics](papers/p851-lefevre.pdf)

# Hetrogeneous Data Store Integration

* [Semantic Integration of Heterogeneous Information Sources](http://www.mswi.uni-osnabrueck.de/rieger_2000_03.pdf)
* [RICES: Reasoning about Information Consistency across Enterprise Solutions](./papers/rices.doc)
* TODO: add more here

# Data cleaning, data management

* [Semantic-Integration Research in the Database Community](http://www.aaai.org/ojs/index.php/aimagazine/article/view/1801/1699), [Alternate link](./papers/1801-1797-1-PB.pdf)
* TODO: Add tope paper and related here

# Time, clocks and ordering

* [Time, clocks and odering of the events in a distributed system](http://web.stanford.edu/class/cs240/readings/lamport.pdf)

# Functional Pearls / Other programming

* [Applicative programming with effects](http://strictlypositive.org/IdiomLite.pdf)
* [Reflection without remorse](http://homepages.cwi.nl/~ploeg/papers/zseq.pdf)

# UB-Trees

* [The Universal B-Tree for multidimensional indexing: General Concepts](http://citeseerx.ist.psu.edu/showciting?cid=13384)
* [The BUB-Tree (dealing with dead space)](http://www.cse.ust.hk/vldb2002/VLDB2002-proceedings/papers/S34P16.pdf) by Robert Fenk
* [Processing Relational OLAP Queries with UB-Trees and Multidimensional Hierarchical Clustering (2000)](http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.35.5820) by Markl and Bayer
* UB-Tree Indexing for Semantic Query Optimization of Range Queries by S. Housseno, A. Simonet and M. Simonet
* [Indexing Techniques in Data Warehousing Environment The UB-Tree Algorithm](http://www.aui.ma/personal/~H.Haddouti/UB_Tree_paper.pdf)

# Space-Filling
* [Skjellum provides a nice way to make a Morton order that works even for non-integral numbers of bits](http://people.cs.vt.edu/~asandu/Public/Qual2005/Q2005_skjellum.pdf)
* [Adaptive query processing in point-transformation schemes](http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.59.6190&rep=rep1&type=pdf) by B. Yu covers a way we can incrementally refine compution of overlapping ranges in Morton order.
* [Efficient Range Query Using Multiple Hilbert Curves](http://cdn.intechopen.com/pdfs/16532/InTech-Efficient_range_query_using_multiple_hilbert_curves.pdf) shows that we can answer queries in fewer ranges if we store multiple copies of the data using different space filling curves or with rotations and shifts. This may point to a replication strategy. As with storing multiple copies for a column store using different orderings to get both fault tolerance, the same thing apply to space filling storage of the data.
* [Cache-Oblivious Dense and Sparse Matrix Multiplication Based on Peano Curves](https://para08.idi.ntnu.no/docs/submission_155.pdf)
* [Performance of Multi-Dimensional Space-Filling Curves](http://docs.lib.purdue.edu/cgi/viewcontent.cgi?article=2545&context=cstech) by Mokbel, Aref and Kamel gives a number of general invariants over all space filling curves.

# Order Preserving Codes
* The identity transformation
* [Shor's explanation of the Hu-Tucker algorithm](http://www-math.mit.edu/~shor/PAM/hu-tucker_algorithm.html)
* [Golomb coding](http://en.wikipedia.org/wiki/Golomb_coding)
* [Arithmetic coding](http://en.wikipedia.org/wiki/Arithmetic_coding)
* [Range coding](http://en.wikipedia.org/wiki/Range_encoding)
* [Order Preserving Key Compression](http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.86.3306&rep=rep1&type=pdf) describes ALM coding and references the ZIL coding. ALM coding violates the prefix property of Huffman and Hu-Tucker locally, but only needs the next symbol worth of lookahead to resolve the ambiguity.
* [Dictionary-based Order-preserving String Compression
for Main Memory Column Stores](http://www.cs.uni-paderborn.de/fileadmin/Informatik/AG-Boettcher/Lehre/WS_09_10/pro-sem-ws09/Dictionary-based_Order-preserving_String_Compression_for_Main_Memory_Column_Stores.pdf)
* [Query Optimization In Compressed Database Systems](http://userpages.umbc.edu/~zhchen/papers/sigmod01-camera.pdf)
* Sometimes we don't care about ordering. If we have categorical information, we could use Huffman directly on that dimension.
* [How to Wring a Table Dry: Entropy Compression of Relations and Querying of Compressed Relations](http://tomx.inf.elte.hu/twiki/pub/Tudas_Labor/2012Summer/how_to_wring_a_table_dry_-_vldb2006-p858-raman.pdf)
* [Binary Ordered Compression for Unicode](http://en.wikipedia.org/wiki/Binary_Ordered_Compression_for_Unicode) provides an lexicographically order preserving compression scheme for unicode text, so long as you do not use the reset code! BOCU-1 is covered by US Patent #6,737,994, but is royalty-free. It may serve as a default unicode text column format in the absence of more coding information.
* [An Alternative to Arithmetic Coding with Local Decodability](http://people.csail.mit.edu/mip/papers/trits/paper.pdf)

# Other Order-Preserving Structures:
* [Order Preserving Encryption for Numeric Data](http://rsrikant.com/papers/sigmod04.pdf) by Agrawal, Kiernan Srikant, and Xu covers how to make an order-preserving encryption scheme that permits standard database indexing, robust against inspection, but not against prior domain information about ranges of values or the ability to encrypt or decrypt known data.
* [An Ideal-Security Protocol for Order-Preserving Encoding](http://eprint.iacr.org/2013/129.pdf) by Popa, Li, and Zeldovich covers a way to improve on the previous paper to leak nothing other than order by using "mutable cipher-text". This is currently realized in their [cryptdb](http://css.csail.mit.edu/cryptdb/) project.
* [Fast string sorting using order-preserving compression](http://dl.acm.org/citation.cfm?id=1180611)

## Fat binary search and monotone minimal perfect hashing
* [Order Preserving Minimal Perfect Hash Functions and Information Retrieval](http://eprints.cs.vt.edu/archive/00000248/01/TR-91-01.pdf) by Fox, Chen, Daoud, and Heath max present a way to create still-order preserving hashing functions for categorical data with known categories.
* [Fast Prefix Search in Little Space with Application](http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.174.9262&rep=rep1&type=pdf) [(slides)](http://www.itu.dk/people/pagh/papers/prefix-slides.pdf) describes a nice trade-off that permits 'weak' rank over prefix queries provided at least one key matches the prefix in the dataset and provides a nice way to balance returning all of the records that match a given query when mixed in with the other storage tools at our disposal.
* [F. C. Botelho and N. Ziviani. External perfect hashing for very large key sets. In CIKM, pages 653–662, 2007.](http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.88.2974&rep=rep1&type=pdf) provides a suite of techniques that are used to good effect in
* [Theory and Practise of Monotone Minimal Perfect Hashing](http://www.itu.dk/people/pagh/papers/jea.pdf), which provides a good template for how to put monotone minimal perfect hashing to use.

# Formal Concept Analysis

* [The Wikipedia Article](http://en.wikipedia.org/wiki/Formal_concept_analysis) is okay, it includes a link to this
* [FCA Homepage](http://www.fcahome.org.uk/fca.html)

# Incremental Computation
* [Differential Dataflow](http://www.cidrdb.org/cidr2013/Papers/CIDR13_Paper111.pdf)
* [Project Naiad](http://research.microsoft.com/en-us/projects/naiad/)

# Weighted Datalog and Generalized Annotated Programs
* [Dyna: Extending Datalog for Modern AI](http://www.cs.jhu.edu/~nwf/datalog20-paper.pdf)
* [A Flexible Solver for Finite Arithmetic Circuits](http://cs.jhu.edu/~jason/papers/filardo+eisner.iclp12.pdf)

# Stable Models
* [Extending and Implementing the Stable Model Semantics](http://arxiv.org/pdf/cs/0005010.pdf)
* [Safe Database Queries with Arithmetic Operations](http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.48.4845&rep=rep1&type=pdf)

# Top-Down Evaluation
* [Efficient Top-Down Computation of Queries Under the Well-Founded Semantics](http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.38.6142&rep=rep1&type=pdf)

# Tabling
* [OLD Resolution with Tabulation](http://sato-www.cs.titech.ac.jp/reference/Sato-ICLP86.pdf)
* [A Thread In Time Saves Tabling Time](http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.54.9454&rep=rep1&type=pdf)
* [More Efficient Datalog Queries: Subsumptive Tabling Beats Magic Sets](http://www.logicblox.com/publications/2011/sigmod11-tekle.pdf)

# *-Semirings and C-Semirings/ω-continuous semirings
```
[21:27] nwf:	 Paper dump:
[21:27] nwf:	 http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.71.7650 is a decent overview, though a little dated
[21:28] nwf:	 http://dl.acm.org/citation.cfm?id=973230 ties a lot of this in to NLP parsing, if you're curious
[21:28] nwf:	 http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.56.704 I have just skimmed and has some nice examples
[21:30] nwf:	 http://dl.acm.org/citation.cfm?doid=322261.322272 has some more graph-based examples
```
* [Weighted Datalog and Levels of Trust](http://dl.acm.org/citation.cfm?id=1371966)

# Provenance semirings and x-fast trees
* [Provenance Semirings](http://db.cis.upenn.edu/DL/07/pods07.pdf)
* [Provenance query evaluation: what's so special about it?](http://dl.acm.org/citation.cfm?id=1646040)

# Consistency and distribution

* [Distributed Algorithms in NoSQL Databases](http://highlyscalable.wordpress.com/2012/09/18/distributed-algorithms-in-nosql-databases/)

# Latch-free architecture

* [High-Performance Concurrency Control Mechanisms for Main-Memory Databases](http://vldb.org/pvldb/vol5/p298_per-akelarson_vldb2012.pdf)

# Persistence and Versioning

* [Fully Persistent B-Trees](http://cs.au.dk/~gerth/pub/soda12.html)
* [Confluently Persistent Tries for Efficient Version Control](http://erikdemaine.org/papers/ConfluentTries_Algorithmica/paper.pdf) by Demaine, Langerman and Price is particularly interesting to me, because they provide O(log log n) movement time fully persistent hash table.
* [Stratified B-trees and Versioned Dictionaries](http://static.usenix.org/event/hotstorage11/tech/final_files/Twigg.pdf) describes a technique for versioning that is consistent with the rest of the machinery in `analytics`.

# Cache-Obliviousness
* [Cache-Oblivious Algorithms](http://supertech.csail.mit.edu/papers/Prokop99.pdf) was Prokop's M.S. thesis and more or less started this whole field.
* [Cache-Oblivious Sorting](http://cs.au.dk/~gerth/pub/encyclopedia08.html)
* [Ordered Files and Cache-Oblivious Priority Queues *video*](http://www.youtube.com/watch?v=jAh_bC4hYlc)
* [A density control algorithm for doing insertions and deletions in a sequentially ordered file in a good worst-case time](http://www.sciencedirect.com/science/article/pii/089054019290034D). This provides the O((log^2 N)/B) _worst case_ bound for ordered file maintanence. Note that to do so it uses a "calibrator tree" which corresponds directly with the total number of children under a given branch. This could be-expressed like (or as part of) a Haar sketch.
* [Cache-Oblivious Parallel Algorithms](http://multicoretheory.wordpress.com/2011/05/11/cache-oblivious-parallel-algorithms/) gives a decent overview of cache-oblivious parallel architecture and Blelloch et al.'s parallel cache complexity bounds.
* [Exponential Structures for Efficient Cache-Oblivious Algorithms](http://www.daimi.au.dk/~large/ioS05/BCR.pdf) by Bender, Cole and Raman

## Packed Memory Arrays
* [Insertion Sort is /O(n log n)/](http://www.cs.sunysb.edu/~bender/newpub/BenderFaMo06-librarysort.pdf) by Bender, Farach-Colton and Mostiero.
* [An Adaptive Packed Memory Array](http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.63.1533) by Bender and Hu provides a PMA that for many access patterns offers faster /O(log n)/ amortized inserts.
* [Partially De-amortized Packed Memory Array](http://dhruvbird.com/pdpma.pdf) [(alt)](http://www.academia.edu/1766080/A_partially_deamortized_packed_memory_array) goes half-way to the Willard bounds with a lot less implementation effort.

## Encoding functions with static support, Monotone Minimal Perfect Hashing and Bloomier Filters
* [Predecessor search with distance-sensitive query time](http://arxiv.org/pdf/1209.5441.pdf) covers Z-Fast Trees (and unlike [the original](http://link.springer.com/chapter/10.1007%2F978-3-642-16321-0_15?LI=true#page-1) isn't behind a Springer pay-wall).
* [Boldi's slides from BISS2012](http://boldi.di.unimi.it/Corsi/BISS2012/mmph.pdf) give a good motivation for the fat binary search used in z-fast tries.
* [Bloomier Filters: A second look](http://arxiv.org/abs/0807.0928)

## Cache-Oblivious Databases

* [Cache-Oblivious Databases: Limitations and Opportunities](http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.144.9113&rep=rep1&type=pdf) by He and Luo provides lots of hard numbers comparing COB+ trees with other structures, etc.
* [Cache-Oblivious Streaming B-Trees](http://supertech.csail.mit.edu/papers/sbtree.pdf)
* [Streaming B-Trees for Filesystem Grand Challenges](http://institutes.lanl.gov/hec-fsio/workshops/2007/presentations/day1/Farach-Colton_sbtree-nsf07.pdf)
* [Cache-Oblivious Query Processing](http://www-db.cs.wisc.edu/cidr/cidr2007/papers/cidr07p05.pdf) by He and Luo

## String Dictionaries

* Cache-Oblivious String Dictionaries ([slides](http://www.cs.au.dk/~gerth/slides/bertinoro06.pdf)) ([paper](http://www.cs.au.dk/~gerth/papers/soda06.pdf)) by Brodal and Fagerberg use giraffe trees for fixed dictionaries.
* [Fast Compressed Tries through Path Decompositions](http://siam.omnibooksonline.com/2012ALENEX/data/papers/018.pdf) by Grossi and Ottaviano talks about [centroid trees](http://mathworld.wolfram.com/CentroidPoint.html), which are used in many dictionary structures including
* [Cache-Oblivious String B-Trees](http://www.cs.stonybrook.edu/~bender/pub/PODS06-BFK.pdf) by Bender, Farach-Colton and Kuszmaul used centroid trees as part of their COSB-tree
* [Compressed String Dictionaries](http://arxiv.org/pdf/1101.5506v1.pdf) by Brisaboa, Cánovas, Martínez-Prieto and Navarro uses a BWT-based transformation to get an efficient compressed string dictionary.
* [Offline Dictionary-Based Compression](http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.31.5097&rep=rep1&type=pdf) by Larsson and Moffat covers RE-PAIR, which has very slow encoding, but reasonable decoding performance.
* [On Searching Compressed String Collections Cache-Obliviously](http://ita.ucsd.edu/workshop/08/files/paper/paper_283.pdf) by Ferragina, Grossi, Gupta, Shah and Vitter talks about "distribution aware" search in section 5 and uses the centroid path decomposition of a tree. They also use the exact form of rear-coding we reinvented.

# Logging and Metrics

* [The log-structured merge tree](http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.44.2782&rep=rep1&type=pdf) by O'Neil, Cheng, Gawlick and O'Neil provides
 great throughput for inserts in exchange for high read latency for write-mostly workloads.

# Compressed Search

We could store full-text-indices on some columns as a BWT transformed version of the leave chunk, then perform compressed-search techniques on top to permit efficient operations on them without paying for full decompression.

At ~4 meg leaves this actually fits pretty well with bzip2 window sizes.

* [Searching BWT compressed text with the Boyer-Moore algorithm and binary search](http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.106.9296) by Bell, Powell, Mukherjee and Adjeroh. Note: since our text fragments end with a given block, the concern about chunking BWT searches from the paper do not apply.
* [A Comparison of BWT Approaches to String Pattern Matching](http://vlsi.cs.ucf.edu/nsf/files/reportVer05driver.pdf) by Firth, Bell, Mukherjee and Adjeroh
* [The SBC-Tree: An Index for Run-Length Compressed Sequences](http://www.ittc.ku.edu/~jsv/Papers/EHS08.SBCtree.pdf)
* [Compressed Text Indexing and Range Searching](http://www.cs.purdue.edu/research/technical_reports/2006/TR%2006-021.pdf)
* [Opportunistic Data Structures with Applications](http://people.unipmn.it/manzini/papers/focs00draft.pdf) by Ferragina and Manzini describes how to work with 'compressed suffix arrays' for sublinear space overhead on compressible texts.

# Wavelet Trees and Succinct Data Structures
* [The Myriad Virtues of Wavelet Trees](http://people.unipmn.it/manzini/papers/icalp06.pdf) by Ferragina, Giancarlo, and Manzini
* [Wavelet Trees for All](http://www.dcc.uchile.cl/~gnavarro/ps/cpm12.pdf) by Navarro is an amazingly good overview of the uses of rank/select.
* [Geometric Burrows-Wheeler Transform: Linking Range Searching and Text Indexing](http://www.ittc.ku.edu/~jsv/Papers/CHS08.geometricbw.pdf) builds on wavelet trees and lets us use the algorithms from
* Space-efficient Suffix Trees by Munro, Raman and Rao (2001).
* [Kernel-based Similarity Search in Massive Graph Databases with Wavelet Trees](http://siam.omnibooksonline.com/2011datamining/data/papers/168.pdf) talks a bit about rank-select structures.
* [Broadword Implementation of Rank/Select Queries](http://sux.dsi.unimi.it/paper.pdf) by Vigna
* [Succincter](http://people.csail.mit.edu/mip/papers/succinct/succinct.pdf) by Mihai Pătraşcu
* [Dynamic Entropy Compressed Sequences and Full-Text Indices](http://www.cs.ucr.edu/~stelo/cpm/cpm06/25-makinen.pdf) by Mäkinen and Navarro
* [Succinct Dictionary Matching With No Slowdown](http://arxiv.org/pdf/1001.2860.pdf)
* [The Pizza & Chili Corpus](http://pizzachili.dcc.uchile.cl/indexes.html) provides implementations for many succinct structures.
* [X86-optimized Rank-Select Dictionaries for Bit Sequences](http://www.slideshare.net/maropu0804/a-x86optimized-rankselect-dictionary-for-bit-sequences)
* [Taiju Succint Trie c++ lib and references](http://code.google.com/p/taiju/)

# Compressed Computation

* [Computable Compressed Matrices](http://arxiv.org/pdf/1303.0270v1.pdf)

# Batched buffer management

* [The Buffer Tree: A Technique for Designing Batched External Data Structures](http://www.cs.cmu.edu/~guyb/realworld/slidesF10/buffertree.pdf)
* [MemC3: Compact and Concurrent MemCache with Dumber Caching and Smarter Hashing](http://www.cs.cmu.edu/~binfan/papers/nsdi13_memc3.pdf) uses smarter hashing to get a nice write-focused memcached variant.
* [High Performance Cache Replacement Using Re-Reference Interval Prediction (RRIP)](http://www.jaleels.org/ajaleel/publications/isca2010-rrip.pdf) by Jaleel, Theobald, Steely and Emer provides a nice replacement for LRU policies for an explicit buffer cache with low overhead.
* [Decoupled Dynamic Cache Segmentation](http://faculty.cse.tamu.edu/djimenez/pdfs/hpca2012_dist.pdf) by Khan, Wang and Jiminéz is resistant to both scanning and thrashing, but is also "decoupled" from the choice of replacement policy.

# Succinct Tree Representations
* [Fully-Functional Succinct Trees](http://www.dcc.uchile.cl/~gnavarro/ps/soda10.pdf) provide a nice leg-up from DFUDS and LOUDS in terms of additional functionality.

# Scheduling and Work-Stealing

* [The data locality of work stealing](http://citeseer.ist.psu.edu/viewdoc/summary?doi=10.1.1.129.9162) by Acar and Blelloch introduced the affinity scheduler now used by Intel's TBB.
* [Dynamic circular work-stealing deque](http://citeseerx.ist.psu.edu/showciting?cid=3884551) by Chase and Lev described a novel circular work-stealing deque. However, my attempts to get it to work in Haskell have been fraught with difficulty.
* [A Dynamic-Sized Nonblocking Work Stealing Deque](http://citeseerx.ist.psu.edu/showciting?cid=3884551) by Hendler et al.

# Data Sets (for future demo / benchmarking)
* [Flights Data Set](http://stat-computing.org/dataexpo/2009/the-data.html) might be a good benchmark

# Bloom Filters
* [Don't Thrash: How to Cache your Hash on Flash](http://static.usenix.org/event/fast11/posters_files/Bender.pdf) provides the notion of a Quotient Filter


text:
import { Component, ContentChildren, QueryList, AfterContentInit } from 'angular2/core';
import { Tab } from './tab.component';

// Author:Juri Strumpflohner.  A revised version of thoughtram's article
// http://juristr.com/blog/2016/02/learning-ng2-creating-tab-component/
// http://blog.thoughtram.io/angular/2015/04/09/developing-a-tabs-component-in-angular-2.html

@Component({
  selector: 'tabs',
  template:`

        {{tab.title}}

    <ng-content></ng-content>
  `
})
export class Tabs implements AfterContentInit {

  @ContentChildren(Tab) tabs: QueryList<Tab>;

  // contentChildren are set
  ngAfterContentInit() {
    // get all active tabs
    let activeTabs = this.tabs.filter((tab)=>tab.active);
    console.log('Tabs Conut:' + this.tabs.length);
    // if there is no active tab set, activate the first
    if(activeTabs.length === 0) {
      this.selectTab(this.tabs.first);
    }
  }

  selectTab(tab: Tab){
    // deactivate all tabs
    this.tabs.toArray().forEach(tab => tab.active = false);

    // activate the tab the user has clicked on.
    tab.active = true;
  }

}

redpajama_set_name: RedPajamaGithub


text:
from nes.processors.registers import Register

class Sq1Sweep(Register):
    pass


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Annls mycol. 9: 143 (1911)

#### Original name
Puccinia phlogacanthi Syd. & P. Syd.

### Remarks
null


text:
package logic_test

import (
	. "github.com/polaris1119/config"
	"github.com/polaris1119/logger"

	"github.com/studygolang/studygolang/logic"
	"testing"
)

func TestSendAuthMail(t *testing.T) {
	logger.Init(ROOT+"/log", ConfigFile.MustValue("global", "log_level", "DEBUG"))

	err := logic.DefaultEmail.SendAuthMail("中文test", "内容test content,收到?", []string{"xuxinhua@zhimadj.com"})
	if err != nil {
		t.Error(err)
	} else {
		t.Log("successful")
	}
}


text:
using System;
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.ComTypes;
using System.Security.Permissions;

[assembly:CLSCompliant(false)]
[assembly:System.Runtime.InteropServices.ComVisible(false)]
[assembly:SecurityPermission(SecurityAction.RequestMinimum, Unrestricted=true)]


text:
This packages are "private" and currently not! certified by Mesosphere.

## Installation

```sh
dcos package repo add universe-jstabenow https://github.com/jstabenow/dcos-packages/archive/version-2.x.zip
```

## Packages:

* Graylog-Server (in progress)
* MongoDB


text:
package org.g_node.nix.valid;

import org.bytedeco.javacpp.Loader;
import org.bytedeco.javacpp.Pointer;
import org.bytedeco.javacpp.annotation.*;
import org.g_node.nix.internal.BuildLibs;

/**
 *
Message

 * Message class with entity id and msg string
 *

 * Class with message text and id string to save a message and the
 * entity id together, used by {@link Result}.
 */

@Properties(value = {
        @Platform(include = {"<nix/valid/helper.hpp>"}),
        @Platform(value = "linux", link = BuildLibs.NIX_1, preload = BuildLibs.HDF5_7),
        @Platform(value = "windows",
                link = BuildLibs.NIX,
                preload = {BuildLibs.HDF5, BuildLibs.MSVCP120, BuildLibs.MSVCR120, BuildLibs.SZIP, BuildLibs.ZLIB})})
@Namespace("nix::valid")
public class Message extends Pointer {
    static {
        Loader.load();
    }

    /**
     * Create new message.
     *
     * @param newId  id
     * @param newMsg text
     */
    public Message(String newId, String newMsg) {
        allocate(newId, newMsg);
    }

    private native void allocate(@StdString String newId, @StdString String newMsg);

    /**
     * Get id of message.
     *
     * @return id of message.
     */
    public native
    @Name("id")
    @MemberGetter
    @StdString
    String getId();

    /**
     * Set id of message.
     *
     * @param id id of message.
     */
    public native
    @Name("id")
    @MemberSetter
    void setId(@StdString String id);

    /**
     * Get text of message.
     *
     * @return text
     */
    public native
    @Name("msg")
    @MemberGetter
    @StdString
    String getMsg();

    /**
     * Set text for message.
     *
     * @param msg text
     */
    public native
    @Name("msg")
    @MemberSetter
    void setMsg(@StdString String msg);

    //--------------------------------------------------
    // Overrides
    //--------------------------------------------------

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }

        if (!(obj instanceof Message)) {
            return false;
        }

        Message message = (Message) obj;

        return this.getId().equals(message.getId())
                && this.getMsg().equals(message.getMsg());
    }

    @Override
    public String toString() {
        return "Message: {id = " + this.getId()
                + ", msg = " + this.getMsg() + "}";
    }
}


text:
<?php

namespace Puli\Manager\Discovery\Type;

use Puli\Manager\Api\Discovery\BindingTypeDescriptor;
use Puli\Manager\Api\Module\Module;
use Puli\Manager\Transaction\AtomicOperation;

/**
 * Loads a type descriptor.
 *
 * @since  1.0
 *
 * @author Bernhard Schussek <bschussek@gmail.com>
 */
class LoadTypeDescriptor implements AtomicOperation
{
    /**
     * @var BindingTypeDescriptor
     */
    private $typeDescriptor;

    /**
     * @var Module
     */
    private $containingModule;

    /**
     * @var BindingTypeDescriptorCollection
     */
    private $typeDescriptors;

    /**
     * @var BindingTypeDescriptor
     */
    private $previousDescriptor;

    public function __construct(BindingTypeDescriptor $typeDescriptor, Module $containingModule, BindingTypeDescriptorCollection $types)
    {
        $this->typeDescriptor = $typeDescriptor;
        $this->containingModule = $containingModule;
        $this->typeDescriptors = $types;
    }

    /**
     * {@inheritdoc}
     */
    public function execute()
    {
        // sanity check
        if ($this->typeDescriptor->isLoaded()) {
            return;
        }

        // never fails with the check before
        $this->typeDescriptor->load($this->containingModule);

        $typeName = $this->typeDescriptor->getTypeName();
        $moduleName = $this->containingModule->getName();

        if ($this->typeDescriptors->contains($typeName, $moduleName)) {
            // never fails with the check before
            $this->previousDescriptor = $this->typeDescriptors->get($typeName, $moduleName);
        }

        // never fails
        $this->typeDescriptors->add($this->typeDescriptor);
    }

    /**
     * {@inheritdoc}
     */
    public function rollback()
    {
        // sanity check
        if (!$this->typeDescriptor->isLoaded()) {
            return;
        }

        $typeName = $this->typeDescriptor->getTypeName();

        // never fails with the check before
        $this->typeDescriptor->unload();

        if ($this->previousDescriptor && $this->previousDescriptor->isLoaded()) {
            // never fails
            $this->typeDescriptors->add($this->previousDescriptor);
        } else {
            // never fails
            $this->typeDescriptors->remove($typeName, $this->containingModule->getName());
        }
    }
}


text:
layout: post
title: Social Media Conference at DevCom Brussels
date: 2010-01-27 12:33:00.000000000 +01:00
type: post
published: true
status: publish
categories: []
tags:
- conferences
- devcom
- english
- socialmedia
- socialnetworks
meta:
  _original_post_id: ''
  _original_import_author: 'Ramon Suarez: Internet Entrepreneurship and Marketing'
author:
  login: ramonsuarez
  email: ramon@betacowork.com
  display_name: ramonsuarez
  first_name: Ramon
  last_name: Suarez
excerpt: EBO4 - Blogs, social networks, instant messaging, video-, geo-localisation,
  M-business... A revolution is walking! How to integrate those new e-marketing levers
  and boost efficiency of your multi-channel contact centre ? in French and English
  The ...
---

EBO4 - Blogs, social networks, instant messaging, video-, geo-localisation, M-business...
A revolution is walking! How to integrate those new e-marketing levers and boost efficiency of your multi-channel contact centre ? in French and English

The Panel

Jo CAUDRON
 Fondateur DEAR MEDIA

Jean Michel FLAMANT
 Président IDEES 3COM SAS
Après 10 ans comme directeur de projets dans le domaine du multimedia puis dans la grande distribution, Jean-Michel Flamant crée Idées-3com SAS en 2006.  Idées-3com est est reconnue comme spécialiste dans la création d'outils d'aide à la vente sur les sites de E Commerce et dans les Serious Games.

Dominique Gany
 Journalist Press

Pierre LELONG
 Manager de projets innovants, Consultant e-commerce Technofutur TIC
Expert Web
 Initiateur de programmes publics TIC
 Créateur et coordinateur du PR&D
 Organisateur de Solutions Business, des Rewics, de la Semaine Numérique
 Auditeur e-business près la Région wallonne
 Conférencier et chargé de cours universitaire

Ramon SUAREZ VASQUEZ
 New Media Business & Marketing Consultant CLEVERWOOD
Ramón Suárez is a new media business and marketing consultant passionate about internet and mobile communications. With more than 10 years of experience, he helps clients find and implement the best solution to reach their strategic business goals.

Animated by

Charles CROUCH
 Lecturer in e-Business BOSTON UNIVERSITY
Charles presents lively, interactive courses, seminars and workshops to help people better understand and use the Internet in business and in their daily lives. Whether teaching in the classroom, presenting at a congress, or working directly with companies on a project, he focuses on giving practical information which people can use to improve their own online performance.

via devcom.be

Here's the programme for tomorrow's social media conference at DevCom Brussels. You can still sign up.


text:
require 'spec_helper'

describe Seth::ceth::EnvironmentCreate do
  before(:each) do
    @ceth = Seth::ceth::EnvironmentCreate.new
    @ceth.stub(:msg).and_return true
    @ceth.stub(:output).and_return true
    @ceth.stub(:show_usage).and_return true
    @ceth.name_args = [ "production" ]

    @environment = Seth::Environment.new
    @environment.stub(:save)

    Seth::Environment.stub(:new).and_return @environment
    @ceth.stub(:edit_data).and_return @environment
  end

  describe "run" do
    it "should create a new environment" do
      Seth::Environment.should_receive(:new)
      @ceth.run
    end

    it "should set the environment name" do
      @environment.should_receive(:name).with("production")
      @ceth.run
    end

    it "should not print the environment" do
      @ceth.should_not_receive(:output)
      @ceth.run
    end

    it "should prompt you to edit the data" do
      @ceth.should_receive(:edit_data).with(@environment)
      @ceth.run
    end

    it "should save the environment" do
      @environment.should_receive(:save)
      @ceth.run
    end

    it "should show usage and exit when no environment name is provided" do
      @ceth.name_args = [ ]
      @ceth.ui.should_receive(:fatal)
      @ceth.should_receive(:show_usage)
      lambda { @ceth.run }.should raise_error(SystemExit)
    end

    describe "with --description" do
      before(:each) do
        @ceth.config[:description] = "This is production"
      end

      it "should set the description" do
        @environment.should_receive(:description).with("This is production")
        @ceth.run
      end
    end

    describe "with --print-after" do
      before(:each) do
        @ceth.config[:print_after] = true
      end

      it "should pretty print the environment, formatted for display" do
        @ceth.should_receive(:output).with(@environment)
        @ceth.run
      end
    end
  end
end


text:
import org.encog.engine.network.activation.ActivationSigmoid;
import org.encog.ml.data.basic.BasicMLDataSet;
import org.encog.neural.networks.BasicNetwork;
import org.encog.neural.networks.PersistBasicNetwork;
import org.encog.neural.networks.layers.BasicLayer;
import org.encog.neural.networks.training.Train;
import org.encog.neural.networks.training.propagation.resilient.ResilientPropagation;
import storage.*;

import org.junit.Test;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * Training procedure for Encog MLP with track data
 *
 */
public class EncogMLPTrainingTest {
    private static final int TRAIN_ITERATIONS = 10000;

    // The values that we take as input for predictions
    public static final int[] INPUTS = new int[] {
            DataRecorder.SENSOR_SPEED,
            DataRecorder.SENSORS_ANGLE_TO_TRACK_AXIS,
            DataRecorder.SENSOR_TRACK_EDGE_1,
            DataRecorder.SENSOR_TRACK_EDGE_2,
            DataRecorder.SENSOR_TRACK_EDGE_3,
            DataRecorder.SENSOR_TRACK_EDGE_4,
            DataRecorder.SENSOR_TRACK_EDGE_5,
            DataRecorder.SENSOR_TRACK_EDGE_6,
            DataRecorder.SENSOR_TRACK_EDGE_7,
            DataRecorder.SENSOR_TRACK_EDGE_8,
            DataRecorder.SENSOR_TRACK_EDGE_9,
            DataRecorder.SENSOR_TRACK_EDGE_10,
            DataRecorder.SENSOR_TRACK_EDGE_11,
            DataRecorder.SENSOR_TRACK_EDGE_12,
            DataRecorder.SENSOR_TRACK_EDGE_13,
            DataRecorder.SENSOR_TRACK_EDGE_14,
            DataRecorder.SENSOR_TRACK_EDGE_15,
            DataRecorder.SENSOR_TRACK_EDGE_16,
            DataRecorder.SENSOR_TRACK_EDGE_17,
            DataRecorder.SENSOR_TRACK_EDGE_18,
            DataRecorder.SENSOR_TRACK_EDGE_19,
    };

    // The values that we want to predict
    public static final int[] OUTPUTS = new int[] {
            DataRecorder.ACTION_ACCELERATION,
            DataRecorder.ACTION_STEERING,
            DataRecorder.ACTION_BRAKING
    };

    @Test
    public void trainAndStore() {
        BasicMLDataSet dataSet = getData();

        // Create network
        BasicNetwork network = getNetwork();

        // Train
        System.out.println("Training network...");
        Train train = new ResilientPropagation(network, dataSet);
        for (int i = 0; i < TRAIN_ITERATIONS; i++) {
            train.iteration();
        }
        System.out.println("Training finished, error: " + train.getError());

        // Save to file
        System.out.println("Saving to file...");
        saveToFile(network);
        System.out.println("Done");
    }

    private void saveToFile(BasicNetwork network) {
        PersistBasicNetwork ps = new PersistBasicNetwork();
        try {
            FileOutputStream os = new FileOutputStream(Configuration.ENCOG_TRAINED_FILE);
            ps.save(os, network);
            os.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private BasicNetwork getNetwork() {
        BasicNetwork network = new BasicNetwork();
        network.addLayer(new BasicLayer(new ActivationSigmoid(), true, INPUTS.length));
        network.addLayer(new BasicLayer(new ActivationSigmoid(), true, 25));
        network.addLayer(new BasicLayer(new ActivationSigmoid(), true, OUTPUTS.length));
        network.getStructure().finalizeStructure();
        network.reset();
        return network;
    }

    private BasicMLDataSet getData() {
        TrainingData data = TrainingData.readData(Configuration.CSV_DIRECTORY, INPUTS, OUTPUTS, true);
        if (data == null) {
            System.out.println("No data read!");
            return null;
        }

        /* Prepare data */
        Normalization normData = Normalization.createNormalization(data.input, data.target);
        System.out.println("Norm min target: " + normData.targetMin);
        System.out.println("Norm max target: " + normData.targetMax);
        Normalization norm = EvolvedController.createDefaultNormalization();
        norm.normalizeInput(data.input, 0, 1);
        norm.normalizeTarget(data.target, 0, 1);
        return new BasicMLDataSet(data.input.getData(), data.target.getData());
    }

}


text:
namespace net {

//
// Find*()
//

// Returns a const reference to the value associated with the given key if it
// exists. Crashes otherwise.
//
// This is intended as a replacement for operator[] as an rvalue (for reading)
// when the key is guaranteed to exist.
//
// operator[] for lookup is discouraged for several reasons:
//  * It has a side-effect of inserting missing keys
//  * It is not thread-safe (even when it is not inserting, it can still
//      choose to resize the underlying storage)
//  * It invalidates iterators (when it chooses to resize)
//  * It default constructs a value object even if it doesn't need to
//
// This version assumes the key is printable, and includes it in the fatal log
// message.
template <class Collection>
const typename Collection::value_type::second_type& FindOrDie(
    const Collection& collection,
    const typename Collection::value_type::first_type& key) {
  typename Collection::const_iterator it = collection.find(key);
  CHECK(it != collection.end()) << "Map key not found: " << key;
  return it->second;
}

// Same as above, but returns a non-const reference.
template <class Collection>
typename Collection::value_type::second_type& FindOrDie(
    Collection& collection,  // NOLINT
    const typename Collection::value_type::first_type& key) {
  typename Collection::iterator it = collection.find(key);
  CHECK(it != collection.end()) << "Map key not found: " << key;
  return it->second;
}

// Returns a pointer to the const value associated with the given key if it
// exists, or NULL otherwise.
template <class Collection>
const typename Collection::value_type::second_type* FindOrNull(
    const Collection& collection,
    const typename Collection::value_type::first_type& key) {
  typename Collection::const_iterator it = collection.find(key);
  if (it == collection.end()) {
    return 0;
  }
  return &it->second;
}

// Same as above but returns a pointer to the non-const value.
template <class Collection>
typename Collection::value_type::second_type* FindOrNull(
    Collection& collection,  // NOLINT
    const typename Collection::value_type::first_type& key) {
  typename Collection::iterator it = collection.find(key);
  if (it == collection.end()) {
    return 0;
  }
  return &it->second;
}

// Returns the list of QUIC tags represented by the comma separated
// string in |connection_options|.
NET_EXPORT quic::QuicTagVector ParseQuicConnectionOptions(
    const std::string& connection_options);

}  // namespace net

#endif  // NET_QUIC_QUIC_UTILS_CHROMIUM_H_


text:
<?php
echo '<select class=dftHidden name=boxSizesAN>';
echo '<option value=50>0</option>';
echo '<option value=-25>01.</option>';
echo '<option value=80>01.01.</option>';
echo '<option value=-25>01.02.</option>';
echo '<option value=685>01.02.01.</option>';
echo '<option value=80>01.02.02.</option>';
echo '<option value=-25>01.02.03.</option>';
echo '<option value=-25>01.03.</option>';
echo '<option value=625>01.03.01.</option>';
echo '<option value=155>01.03.02.</option>';
echo '<option value=155>01.03.03.</option>';
echo '<option value=365>01.03.04.</option>';
echo '<option value=155>01.03.05.</option>';
echo '<option value=105>01.03.06.</option>';
echo '<option value=80>01.04.</option>';
echo '<option value=-25>01.05.</option>';
echo '<option value=-25>02.</option>';
echo '<option value=180>02.01.</option>';
echo '<option value=105>02.02.</option>';
echo '<option value=130>02.03.</option>';
echo '<option value=-25>02.04.</option>';
echo '<option value=-25>02.05.</option>';
echo '<option value=-25>02.06.</option>';
echo '<option value=310>03.</option>';
echo '<option value=-25>03.01.</option>';
echo '<option value=1420>03.01.01.</option>';
echo '<option value=1365>03.01.02.</option>';
echo '<option value=445>03.01.03.</option>';
echo '<option value=730>03.01.04.</option>';
echo '<option value=-25>03.01.05.</option>';
echo '<option value=-25>03.01.06.</option>';
echo '<option value=-25>03.01.07.</option>';
echo '<option value=-25>03.02.</option>';
echo '<option value=-25>03.03.</option>';
echo '<option value=130>04.</option>';
echo '<option value=80>05.</option>';
echo '<option value=155>06.</option>';
echo '<option value=-25>07.</option>';
echo '<option value=540>07.01.</option>';
echo '<option value=-25>07.02.</option>';
echo '<option value=-25>08.</option>';
echo '<option value=-25>08.01.</option>';
echo '<option value=-25>08.02.</option>';
echo '<option value=-25>08.03.</option>';
echo '<option value=55>09.</option>';
echo '<option value=155>10.</option>';
echo '</select>';
echo '<select class=dftHidden name=boxSizesAC>';
echo '<option value=50>0</option>';
echo '<option value=-25>01.</option>';
echo '<option value=235>01.01.</option>';
echo '<option value=-25>01.02.</option>';
echo '<option value=685>01.03.</option>';
echo '<option value=55>01.04.</option>';
echo '<option value=-25>01.05.</option>';
echo '<option value=105>02.</option>';
echo '<option value=285>03.</option>';
echo '<option value=-25>03.01.</option>';
echo '<option value=105>03.01.01.</option>';
echo '<option value=105>03.01.02.</option>';
echo '<option value=105>03.01.03.</option>';
echo '<option value=105>03.01.04.</option>';
echo '<option value=105>03.01.05.</option>';
echo '<option value=-25>03.01.06.</option>';
echo '<option value=-25>03.01.07.</option>';
echo '<option value=-25>03.02.</option>';
echo '<option value=-25>03.03.</option>';
echo '<option value=280>04.</option>';
echo '<option value=470>05.</option>';
echo '</select>';
?>


text:
package org.readium.sdk.android.biblemesh;

import java.util.HashMap;
import java.util.Map;

import org.readium.sdk.android.Container;

public class ContainerHolder {

	private static final ContainerHolder INSTANCE = new ContainerHolder();

	private final Map<Long, Container> containers = new HashMap<Long, Container>();

	public static ContainerHolder getInstance() {
		return INSTANCE;
	}

	public Container get(Object arg0) {
		return containers.get(arg0);
	}

	public Container remove(Object arg0) {
		return containers.remove(arg0);
	}

	public Container put(Long key, Container value) {
		return containers.put(key, value);
	}

}


text:
package io.digdag.client.api;

import com.google.common.base.Optional;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import org.immutables.value.Value;

@Value.Immutable
@JsonSerialize(as = ImmutableNameOptionalId.class)
@JsonDeserialize(as = ImmutableNameOptionalId.class)
public interface NameOptionalId
{
    String getName();

    Optional<Long> getId();

    static NameOptionalId of(String name, Optional<Long> id)
    {
        return ImmutableNameOptionalId.builder()
            .name(name)
            .id(id)
            .build();
    }
}


text:
<?php namespace CobwebInfo\Cobra5Sdk\Tree;

use CobwebInfo\Cobra5Sdk\Cobra5;
use Illuminate\Support\Collection;
use CobwebInfo\Cobra5Sdk\Entity\Category;
use CobwebInfo\Cobra5Sdk\Entity\Datastore;

class DatastoreTree extends AbstractTree implements Tree
{

    /**
     * The Cobra5 instance
     *
     * @var CobwebInfo\Cobra5Sdk\Cobra5
     */
    protected $cobra5;

    /**
     * Create a new instance of the DatastoreTree
     *
     * @param CobwebInfo\Cobra5Sdk\Cobra5
     * @return void
     */
    public function __construct(Cobra5 $cobra5)
    {
        $this->cobra5 = $cobra5;
    }

    /**
     * Create a tree of all branches
     *
     * @param array $branches
     * @return Illuminate\Support\Collection
     */
    public function all(array $branches = [])
    {
        $datastores = $this->cobra5->getStores();

        foreach ($datastores as $datastore) {
            $datastore = $this->hydrateRoots($datastore);
        }

        if (in_array('categories', $branches)) {
            foreach ($datastores as $datastore) {
                $datastore = $this->hydrateParents($datastore);
            }

            foreach ($datastores as $datastore) {
                foreach ($datastore->categories() as $category) {
                    $category = $this->hydrateChildren($category);
                }
            }
        }

        if (in_array('documents', $branches)) {
            foreach ($datastores as $datastore) {
                foreach ($datastore->categories() as $category) {
                    $category = $this->hydrateDocuments($category);
                }
            }
        }

        return $datastores;
    }

    /**
     * Create a tree of a single branch
     *
     * @param array $branches
     * @return CobwebInfo\Cobra5Sdk\Entity\Entity
     */
    public function branch($id, array $branches = [])
    {
        $datastore = $this->cobra5->getStore($id);

        $datastore = $this->hydrateRoots($datastore);

        if (in_array('categories', $branches)) {
            $datastore = $this->hydrateParents($datastore);

            foreach ($datastore->categories() as $category) {
                $category = $this->hydrateChildren($category);
            }
        }

        if (in_array('documents', $branches)) {
            foreach ($datastore->categories() as $category) {
                $category = $this->hydrateDocuments($category);
            }
        }

        return $datastore;
    }

}


text:
namespace net {

namespace {

bool g_has_instance = false;

base::LazyInstance<TestRootCerts>::Leaky
    g_test_root_certs = LAZY_INSTANCE_INITIALIZER;

CertificateList LoadCertificates(const base::FilePath& filename) {
  std::string raw_cert;
  if (!base::ReadFileToString(filename, &raw_cert)) {
    LOG(ERROR) << "Can't load certificate " << filename.value();
    return CertificateList();
  }

  return X509Certificate::CreateCertificateListFromBytes(
      base::as_bytes(base::make_span(raw_cert)), X509Certificate::FORMAT_AUTO);
}

}  // namespace

// static
TestRootCerts* TestRootCerts::GetInstance() {
  return g_test_root_certs.Pointer();
}

bool TestRootCerts::HasInstance() {
  return g_has_instance;
}

bool TestRootCerts::Add(X509Certificate* certificate) {
  CertErrors errors;
  scoped_refptr<ParsedCertificate> parsed = ParsedCertificate::Create(
      bssl::UpRef(certificate->cert_buffer()),
      x509_util::DefaultParseCertificateOptions(), &errors);
  if (!parsed) {
    return false;
  }

  test_trust_store_.AddTrustAnchor(std::move(parsed));
  return AddImpl(certificate);
}

bool TestRootCerts::AddFromFile(const base::FilePath& file) {
  base::ThreadRestrictions::ScopedAllowIO allow_io_for_loading_test_certs;
  CertificateList root_certs = LoadCertificates(file);
  if (root_certs.empty() || root_certs.size() > 1)
    return false;

  return Add(root_certs.front().get());
}

void TestRootCerts::Clear() {
  ClearImpl();
  test_trust_store_.Clear();
}

bool TestRootCerts::IsEmpty() const {
  return test_trust_store_.IsEmpty();
}

TestRootCerts::TestRootCerts() {
  Init();
  g_has_instance = true;
}

ScopedTestRoot::ScopedTestRoot() = default;

ScopedTestRoot::ScopedTestRoot(X509Certificate* cert) {
  Reset({cert});
}

ScopedTestRoot::ScopedTestRoot(CertificateList certs) {
  Reset(std::move(certs));
}

ScopedTestRoot::~ScopedTestRoot() {
  Reset({});
}

void ScopedTestRoot::Reset(CertificateList certs) {
  if (!certs_.empty())
    TestRootCerts::GetInstance()->Clear();
  for (const auto& cert : certs)
    TestRootCerts::GetInstance()->Add(cert.get());
  certs_ = certs;
}

}  // namespace net


text:
'use strict';

var async = require('async');
var _ = require('lodash');

var db = require('./database');
var posts = require('./posts');
var utils = require('./utils');
var plugins = require('./plugins');
var meta = require('./meta');
var user = require('./user');
var categories = require('./categories');
var privileges = require('./privileges');
var social = require('./social');

var Topics = module.exports;

require('./topics/data')(Topics);
require('./topics/create')(Topics);
require('./topics/delete')(Topics);
require('./topics/unread')(Topics);
require('./topics/recent')(Topics);
require('./topics/popular')(Topics);
require('./topics/user')(Topics);
require('./topics/fork')(Topics);
require('./topics/posts')(Topics);
require('./topics/follow')(Topics);
require('./topics/tags')(Topics);
require('./topics/teaser')(Topics);
require('./topics/suggested')(Topics);
require('./topics/tools')(Topics);
require('./topics/thumb')(Topics);
require('./topics/bookmarks')(Topics);

Topics.exists = function (tid, callback) {
	db.isSortedSetMember('topics:tid', tid, callback);
};

Topics.getPageCount = function (tid, uid, callback) {
	var postCount;
	async.waterfall([
		function (next) {
			Topics.getTopicField(tid, 'postcount', next);
		},
		function (_postCount, next) {
			if (!parseInt(_postCount, 10)) {
				return callback(null, 1);
			}
			postCount = _postCount;
			user.getSettings(uid, next);
		},
		function (settings, next) {
			next(null, Math.ceil((parseInt(postCount, 10) - 1) / settings.postsPerPage));
		},
	], callback);
};

Topics.getTidPage = function (tid, uid, callback) {
	console.warn('[Topics.getTidPage] deprecated!');
	callback(null, 1);
};

Topics.getTopicsFromSet = function (set, uid, start, stop, callback) {
	async.waterfall([
		function (next) {
			db.getSortedSetRevRange(set, start, stop, next);
		},
		function (tids, next) {
			Topics.getTopics(tids, uid, next);
		},
		function (topics, next) {
			next(null, { topics: topics, nextStart: stop + 1 });
		},
	], callback);
};

Topics.getTopics = function (tids, uid, callback) {
	async.waterfall([
		function (next) {
			privileges.topics.filterTids('read', tids, uid, next);
		},
		function (tids, next) {
			Topics.getTopicsByTids(tids, uid, next);
		},
	], callback);
};

Topics.getTopicsByTids = function (tids, uid, callback) {
	if (!Array.isArray(tids) || !tids.length) {
		return callback(null, []);
	}

	var uids;
	var cids;
	var topics;

	async.waterfall([
		function (next) {
			Topics.getTopicsData(tids, next);
		},
		function (_topics, next) {
			function mapFilter(array, field) {
				return array.map(function (topic) {
					return topic && topic[field] && topic[field].toString();
				}).filter(function (value) {
					return utils.isNumber(value);
				});
			}

			topics = _topics;
			uids = _.uniq(mapFilter(topics, 'uid'));
			cids = _.uniq(mapFilter(topics, 'cid'));

			async.parallel({
				users: function (next) {
					user.getUsersFields(uids, ['uid', 'username', 'fullname', 'userslug', 'reputation', 'postcount', 'picture', 'signature', 'banned', 'status'], next);
				},
				categories: function (next) {
					categories.getCategoriesFields(cids, ['cid', 'name', 'slug', 'icon', 'image', 'bgColor', 'color', 'disabled'], next);
				},
				hasRead: function (next) {
					Topics.hasReadTopics(tids, uid, next);
				},
				isIgnored: function (next) {
					Topics.isIgnoring(tids, uid, next);
				},
				bookmarks: function (next) {
					Topics.getUserBookmarks(tids, uid, next);
				},
				teasers: function (next) {
					Topics.getTeasers(topics, uid, next);
				},
				tags: function (next) {
					Topics.getTopicsTagsObjects(tids, next);
				},
			}, next);
		},
		function (results, next) {
			if (parseInt(meta.config.hideFullname, 10) === 1) {
				results.users.forEach(function (user) {
					user.fullname = undefined;
				});
			}

			var users = _.zipObject(uids, results.users);
			var categories = _.zipObject(cids, results.categories);

			for (var i = 0; i < topics.length; i += 1) {
				if (topics[i]) {
					topics[i].category = categories[topics[i].cid];
					topics[i].user = users[topics[i].uid];
					topics[i].teaser = results.teasers[i];
					topics[i].tags = results.tags[i];

					topics[i].isOwner = parseInt(topics[i].uid, 10) === parseInt(uid, 10);
					topics[i].pinned = parseInt(topics[i].pinned, 10) === 1;
					topics[i].locked = parseInt(topics[i].locked, 10) === 1;
					topics[i].deleted = parseInt(topics[i].deleted, 10) === 1;
					topics[i].ignored = results.isIgnored[i];
					topics[i].unread = !results.hasRead[i] && !results.isIgnored[i];
					topics[i].bookmark = results.bookmarks[i];
					topics[i].unreplied = !topics[i].teaser;

					topics[i].icons = [];
				}
			}

			topics = topics.filter(function (topic) {
				return topic &&	topic.category && !topic.category.disabled;
			});

			plugins.fireHook('filter:topics.get', { topics: topics, uid: uid }, next);
		},
		function (data, next) {
			next(null, data.topics);
		},
	], callback);
};

Topics.getTopicWithPosts = function (topicData, set, uid, start, stop, reverse, callback) {
	async.waterfall([
		function (next) {
			async.parallel({
				posts: async.apply(getMainPostAndReplies, topicData, set, uid, start, stop, reverse),
				category: async.apply(categories.getCategoryData, topicData.cid),
				tagWhitelist: async.apply(categories.getTagWhitelist, [topicData.cid]),
				threadTools: async.apply(plugins.fireHook, 'filter:topic.thread_tools', { topic: topicData, uid: uid, tools: [] }),
				isFollowing: async.apply(Topics.isFollowing, [topicData.tid], uid),
				isIgnoring: async.apply(Topics.isIgnoring, [topicData.tid], uid),
				bookmark: async.apply(Topics.getUserBookmark, topicData.tid, uid),
				postSharing: async.apply(social.getActivePostSharing),
				deleter: async.apply(getDeleter, topicData),
				related: function (next) {
					async.waterfall([
						function (next) {
							Topics.getTopicTagsObjects(topicData.tid, next);
						},
						function (tags, next) {
							topicData.tags = tags;
							Topics.getRelatedTopics(topicData, uid, next);
						},
					], next);
				},
			}, next);
		},
		function (results, next) {
			topicData.posts = results.posts;
			topicData.category = results.category;
			topicData.tagWhitelist = results.tagWhitelist[0];
			topicData.thread_tools = results.threadTools.tools;
			topicData.isFollowing = results.isFollowing[0];
			topicData.isNotFollowing = !results.isFollowing[0] && !results.isIgnoring[0];
			topicData.isIgnoring = results.isIgnoring[0];
			topicData.bookmark = results.bookmark;
			topicData.postSharing = results.postSharing;
			topicData.deleter = results.deleter;
			topicData.deletedTimestampISO = utils.toISOString(topicData.deletedTimestamp);
			topicData.related = results.related || [];

			topicData.unreplied = parseInt(topicData.postcount, 10) === 1;
			topicData.deleted = parseInt(topicData.deleted, 10) === 1;
			topicData.locked = parseInt(topicData.locked, 10) === 1;
			topicData.pinned = parseInt(topicData.pinned, 10) === 1;

			topicData.icons = [];

			plugins.fireHook('filter:topic.get', { topic: topicData, uid: uid }, next);
		},
		function (data, next) {
			next(null, data.topic);
		},
	], callback);
};

function getMainPostAndReplies(topic, set, uid, start, stop, reverse, callback) {
	async.waterfall([
		function (next) {
			if (stop > 0) {
				stop -= 1;
				if (start > 0) {
					start -= 1;
				}
			}

			posts.getPidsFromSet(set, start, stop, reverse, next);
		},
		function (pids, next) {
			if (!pids.length && !topic.mainPid) {
				return callback(null, []);
			}

			if (topic.mainPid && start === 0) {
				pids.unshift(topic.mainPid);
			}
			posts.getPostsByPids(pids, uid, next);
		},
		function (posts, next) {
			if (!posts.length) {
				return next(null, []);
			}
			var replies = posts;
			if (topic.mainPid && start === 0) {
				posts[0].index = 0;
				replies = posts.slice(1);
			}

			Topics.calculatePostIndices(replies, start, stop, topic.postcount, reverse);

			Topics.addPostData(posts, uid, next);
		},
	], callback);
}

function getDeleter(topicData, callback) {
	if (!topicData.deleterUid) {
		return setImmediate(callback, null, null);
	}
	user.getUserFields(topicData.deleterUid, ['username', 'userslug', 'picture'], callback);
}

Topics.getMainPost = function (tid, uid, callback) {
	Topics.getMainPosts([tid], uid, function (err, mainPosts) {
		callback(err, Array.isArray(mainPosts) && mainPosts.length ? mainPosts[0] : null);
	});
};

Topics.getMainPids = function (tids, callback) {
	if (!Array.isArray(tids) || !tids.length) {
		return callback(null, []);
	}
	async.waterfall([
		function (next) {
			Topics.getTopicsFields(tids, ['mainPid'], next);
		},
		function (topicData, next) {
			var mainPids = topicData.map(function (topic) {
				return topic && topic.mainPid;
			});
			next(null, mainPids);
		},
	], callback);
};

Topics.getMainPosts = function (tids, uid, callback) {
	async.waterfall([
		function (next) {
			Topics.getMainPids(tids, next);
		},
		function (mainPids, next) {
			getMainPosts(mainPids, uid, next);
		},
	], callback);
};

function getMainPosts(mainPids, uid, callback) {
	async.waterfall([
		function (next) {
			posts.getPostsByPids(mainPids, uid, next);
		},
		function (postData, next) {
			postData.forEach(function (post) {
				if (post) {
					post.index = 0;
				}
			});
			Topics.addPostData(postData, uid, next);
		},
	], callback);
}

Topics.isLocked = function (tid, callback) {
	Topics.getTopicField(tid, 'locked', function (err, locked) {
		callback(err, parseInt(locked, 10) === 1);
	});
};

Topics.search = function (tid, term, callback) {
	plugins.fireHook('filter:topic.search', {
		tid: tid,
		term: term,
	}, function (err, pids) {
		callback(err, Array.isArray(pids) ? pids : []);
	});
};


text:
package com.example.maoyh.tctest.activity;

/**
 * Created by MAOYH on 2016/3/15.
 */
public class OrderDiscussDetailActivity {
}


text:
{% extends 'adminplus/base.html' %}

{% block title %}{{ organization.name_possessive }} föreskrifter per ämnesord{% endblock %}

{% block content %}

Föreskrifter och allmänna råd

Författningsdokument grupperade efter ämnesord.

    {% for key in docs_by_keywords.items %}

{{key.0.titel}}

            {% for doc in key.1 %}

{{doc.identifierare}} {{doc.titel}}

            {% endfor %}

    {% endfor %}
{% endblock %}


text:
({
    afterRender: function(component, helper) {
        helper.addEventHandler(component, "search");
        return this.superAfterRender();
    },
    rerender: function(component, helper) {
        helper.addEventHandler(component, "search");
        return this.superRerender();
    }
})


text:
package com.hannesdorfmann.mosby3.sample.mail;

import android.animation.LayoutTransition;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import com.hannesdorfmann.mosby3.sample.mail.base.view.BaseActivity;
import com.hannesdorfmann.mosby3.sample.mail.details.DetailsFragment;
import com.hannesdorfmann.mosby3.sample.mail.details.DetailsFragmentBuilder;
import com.hannesdorfmann.mosby3.sample.mail.mails.MailsFragment;
import com.hannesdorfmann.mosby3.sample.mail.mails.MailsFragmentBuilder;
import com.hannesdorfmann.mosby3.sample.mail.model.contact.Person;
import com.hannesdorfmann.mosby3.sample.mail.model.mail.Label;
import com.hannesdorfmann.mosby3.sample.mail.model.mail.Mail;
import com.hannesdorfmann.mosby3.sample.mail.model.mail.MailProvider;

import butterknife.BindView;
import butterknife.ButterKnife;
import icepick.Icepick;
import icepick.Icicle;
import javax.inject.Inject;

public class MainActivity extends BaseActivity {

  public static final String KEY_SHOW_ACTION =
      "com.hannesdorfmann.mosby.sample.mail.MainActivity.SHOW_ACTION";

  public static final String KEY_SHOW_ACTION_MAIL_DETAILS =
      "com.hannesdorfmann.mosby.sample.mail.MainActivity.SHOW_ACTION_MAIL_DETAILS";
  public static final String KEY_DATA_MAIL_DETAILS =
      "com.hannesdorfmann.mosby.sample.mail.MainActivity.MAIL";

  public static final String KEY_SHOW_ACTION_MAILS_OF_LABEL =
      "com.hannesdorfmann.mosby.sample.mail.MainActivity.SHOW_ACTION_MAILS_OF_LABEL";
  public static final String KEY_DATA_MAILS_OF_LABEL =
      "com.hannesdorfmann.mosby.sample.mail.MainActivity.LABEL";

  public static final String FRAGMENT_TAG_DETAILS = "detailsFragmentTag";
  public static final String FRAGMENT_TAG_LABEL = "labelFragmentTag";

  Fragment detailsFragment;
  MailsFragment labelFragment;

  @Icicle String toolbarTitle;

  @Inject IntentStarter intentStarter;

  @BindView(R.id.drawerLayout) DrawerLayout drawerLayout;
  @BindView(R.id.toolbar) Toolbar toolbar;
  @BindView(R.id.leftPane) ViewGroup leftPane;
  @Nullable @BindView(R.id.rightPane) ViewGroup rightPane;
  // contains leftPane + rightPane
  @Nullable @BindView(R.id.paneContainer) ViewGroup paneContainer;

  ActionBarDrawerToggle drawerToggle;
  private MainActivityComponent mainActivityComponent;

  @Override protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // Toolbar
    toolbar.inflateMenu(R.menu.search_menu);
    toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
      @Override public boolean onMenuItemClick(MenuItem menuItem) {
        if (menuItem.getItemId() == R.id.search) {
          intentStarter.showSearch(MainActivity.this);
          return true;
        }
        return false;
      }
    });
    drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.drawer_open,
        R.string.drawer_close);
    drawerLayout.setDrawerListener(drawerToggle);
    if (toolbarTitle != null) {
      toolbar.setTitle(toolbarTitle);
    }

    // Check for previous fragments
    detailsFragment = findDetailsFragment();
    labelFragment =
        (MailsFragment) getSupportFragmentManager().findFragmentByTag(FRAGMENT_TAG_LABEL);

    if (detailsFragment != null) {
      // details fragment available, so make it visible
      rightPane.setVisibility(View.VISIBLE);
    }

    if (paneContainer != null) {
      // Enable animation
      LayoutTransition transition = new LayoutTransition();
      transition.enableTransitionType(LayoutTransition.CHANGING);
      paneContainer.setLayoutTransition(transition);
    }

    if (labelFragment == null) {
      // First app start, so start with this
      showMails(MailProvider.INBOX_LABEL, true);
    }
  }

  @Override protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    Icepick.saveInstanceState(this, outState);
  }

  @Override protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);
    setIntent(intent);
    String showAction = intent.getStringExtra(KEY_SHOW_ACTION);

    if (KEY_SHOW_ACTION_MAIL_DETAILS.equals(showAction)) {
      Mail mail = intent.getParcelableExtra(KEY_DATA_MAIL_DETAILS);
      showMail(mail);
    } else if (KEY_SHOW_ACTION_MAILS_OF_LABEL.equals(showAction)) {
      Label label = intent.getParcelableExtra(KEY_DATA_MAILS_OF_LABEL);
      showMails(label, true);
    }
  }

  @Override protected void onPostCreate(Bundle savedInstanceState) {
    super.onPostCreate(savedInstanceState);
    // Sync the toggle state after onRestoreInstanceState has occurred.
    drawerToggle.syncState();
  }

  @Override public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
    drawerToggle.onConfigurationChanged(newConfig);
  }

  private void showMails(Label label, boolean removeDetailsFragment) {
    toolbarTitle = label.getName();
    toolbar.setTitle(toolbarTitle);
    if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
      drawerLayout.closeDrawer(GravityCompat.START);
    }

    getSupportFragmentManager().beginTransaction()
        .replace(R.id.leftPane, new MailsFragmentBuilder(label).build(), FRAGMENT_TAG_LABEL)
        .commit();

    if (removeDetailsFragment) {
      removeDetailsFragment();
    }
  }

  private void showMail(Mail mail) {

    rightPane.setVisibility(View.VISIBLE);
    Person sender = mail.getSender();
    DetailsFragment fragment =
        new DetailsFragmentBuilder(mail.getDate().getTime(), mail.getId(), sender.getEmail(),
            sender.getName(), sender.getImageRes(), mail.isStarred(), mail.getSubject()).build();

    getSupportFragmentManager().beginTransaction()
        .replace(R.id.rightPane, fragment, FRAGMENT_TAG_DETAILS)
        .commit();
  }

  private Fragment findDetailsFragment() {
    return getSupportFragmentManager().findFragmentByTag(FRAGMENT_TAG_DETAILS);
  }

  /**
   * @return true if a fragment has been removed, otherwise false
   */
  private boolean removeDetailsFragment() {
    Fragment detailsFragment = findDetailsFragment();
    if (detailsFragment != null) {
      rightPane.setVisibility(View.GONE);
      getSupportFragmentManager().beginTransaction().remove(detailsFragment).commit();
      return true;
    }

    return false;
  }

  @Override public void onBackPressed() {

    // TODO make this easier to read
    if (!removeDetailsFragment()) {
      super.onBackPressed();
    }
  }

  protected void injectDependencies() {
    mainActivityComponent = DaggerMainActivityComponent.create();
    mainActivityComponent.inject(this);
  }
}


text:
package web

import (
	"time"
)

type GenericBody[T any] struct {
	Data T
} // @name Body

type GenericBodyMulti[T any, X any] struct {
	Data T
	Meta X
} // @name MultiBody

type GenericResponse[T any] struct {
	Data T

	Status string
} // @name Response

type GenericResponseMulti[T any, X any] struct {
	Data T
	Meta X

	Status string
} // @name MultiResponse

// APIError
// @Description API error
// @Description with information about it
// Other some summary
type APIError struct {
	// Error an Api error
	Error string // Error this is Line comment
	// Error `number` tick comment
	ErrorNo   int64
	ErrorCtx  string    // Error `context` tick comment
	CreatedAt time.Time // Error time
}

type AliasPkgGenericResponse[T any] struct {
	Data T

	Status string
}


text:
#include "Cpp/Warnings.h"

#include "Utils/Logger.h"

#include "System/DateTime.h"
#include "System/Environment.h"
#include "System/Stopwatch.h"
#include "System/ProcessorInfo.h"
#include "System/RamInfo.h"
#include "System/Signal.h"

#include "IO/FileSystem.h"
#include "IO/FormattedWriter.h"
#include "IO/HtmlWriter.h"
#include "IO/FileWriter.h"
#include "IO/ConsoleInput.h"
#include "IO/ConsoleOutput.h"
#include "IO/FilePath.h"
#include "IO/FormattedLogger.h"

#include "Test/PerfSummary.h"
#include "Test/TestGroup.h"

#include "Container/String.h"
#include "Container/Array.h"
#include "Container/Map.h"

#include "PerfTestSerialization.h"
#include "Range/Header.h"
#include "PerfTestRandom.h"
#include "PerfTestSort.h"

INTRA_DISABLE_REDUNDANT_WARNINGS

#ifdef _MSC_VER
#pragma warning(disable: 4350)
#endif

#include <stdlib.h>

using namespace Intra;
using namespace IO;

FormattedWriter& InitOutput()
{
	static FormattedWriter logger;
#ifndef INTRA_NO_LOGGING
#ifndef INTRA_NO_FILE_LOGGING
	//Инициализация лога
	const StringView logFileName = "logs.html";
	const bool logExisted = OS.FileExists(logFileName);
	FileWriter logFile = OS.FileOpenAppend(logFileName, Error::Skip());
	logFile.Print("<meta charset='utf-8'>\n<title>Logs</title>\n");
	FormattedWriter logWriter = HtmlWriter(Cpp::Move(logFile), !logExisted);
	String datetime;
	ToString(LastAppender(datetime), System::DateTime::Now());
	StringView appName = IO::Path::ExtractName(System::Environment.CommandLine.First());

	logWriter.BeginSpoiler(appName+StringOf(System::Environment.CommandLine.Drop(), " ", " ", " ")+datetime);

	System::CrashHandler = [](int signum)
	{
		logger.PushFont({1, 0, 0}, 5, true);
		logger.Print(System::CrashSignalDesc(signum));
		logger.PopFont();
		logger = null;
	};

	logWriter << "Command line arguments:";
	logWriter.PrintCode(StringOf(System::Environment.CommandLine, "\n", "", ""));
	logWriter.BeginSpoiler("System info");
	auto memInfo = System::RamInfo::Get();
	auto procInfo = System::ProcessorInfo::Get();
	logWriter.PrintCode(*String::Format(
		"CPU:\r\n<^>\r\n"
		"Cores: <^>\r\n"
		"Logical cores: <^>\r\n"
		"Frequency: <^> MHz\r\n\r\n"
		"Free physical memory: <^> GiB of <^> GiB\r\n")
		(procInfo.BrandString)
		(procInfo.CoreNumber)
		(procInfo.LogicalProcessorNumber)
		(double(procInfo.Frequency)/1000000.0, 1)
		(double(memInfo.FreePhysicalMemory)/double(1 << 30), 2)
		(double(memInfo.TotalPhysicalMemory)/double(1 << 30), 2)
	);
	logWriter.EndSpoiler();
	logger.Attach(Cpp::Move(logWriter));
#endif
	logger.Attach(ConsoleOutput());
#endif
	return logger;
}

int main()
{
	System::InitSignals();
	auto& output = InitOutput();

	if(System::Environment.CommandLine.Get(1, null) == "-a")
		TestGroup::YesForNestingLevel=0;

	TestGroup(null, output, "Random number generation", RunRandomPerfTests);
	if(TestGroup gr{null, output, "Ranges"})
	{
		TestGroup("Polymorphic range performance", RunPolymorphicRangePerfTests);
	}
	TestGroup(null, output, "std::string vs String", RunStringPerfTests);
	TestGroup(null, output, "std::vector и std::deque vs Array", RunContainerPerfTests);
	TestGroup(null, output, "Associative containers", RunMapPerfTests);
	TestGroup(null, output, "Serialization and deserialization", RunSerializationPerfTests);
	TestGroup(null, output, "Sort algorithms", RunSortPerfTests);

	if(System::Environment.CommandLine.Get(1, null) != "-a")
	{
		ConsoleOut.PrintLine("Press any key to exit...");
		ConsoleIn.GetChar();
	}

	return 0;
}


text:
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE DeriveDataTypeable #-}

-- | Versions for packages.

module Stack.Types.Version
  (Version
  ,Cabal.VersionRange -- TODO in the future should have a newtype wrapper
  ,VersionCheck(..)
  ,versionParser
  ,parseVersion
  ,parseVersionFromString
  ,versionString
  ,versionText
  ,toCabalVersion
  ,fromCabalVersion
  ,mkVersion
  ,versionRangeText
  ,withinRange
  ,Stack.Types.Version.intersectVersionRanges
  ,toMajorVersion
  ,latestApplicableVersion
  ,checkVersion
  ,nextMajorVersion)
  where

import           Control.Applicative
import           Control.DeepSeq
import           Control.Monad.Catch
import           Data.Aeson.Extended
import           Data.Attoparsec.Text
import           Data.Binary.VersionTagged (Binary, HasStructuralInfo)
import           Data.Data
import           Data.Hashable
import           Data.List
import           Data.Map (Map)
import qualified Data.Map as Map
import           Data.Maybe (listToMaybe)
import           Data.Set (Set)
import qualified Data.Set as Set
import           Data.Text (Text)
import qualified Data.Text as T
import           Data.Text.Binary ()
import           Data.Vector.Binary ()
import           Data.Vector.Unboxed (Vector)
import qualified Data.Vector.Unboxed as V
import           Data.Word
import           Distribution.Text (disp)
import qualified Distribution.Version as Cabal
import           GHC.Generics
import           Language.Haskell.TH
import           Language.Haskell.TH.Syntax
import           Prelude -- Fix warning: Word in Prelude from base-4.8.
import           Text.PrettyPrint (render)

-- | A parse fail.
data VersionParseFail =
  VersionParseFail Text
  deriving (Typeable)
instance Exception VersionParseFail
instance Show VersionParseFail where
    show (VersionParseFail bs) = "Invalid version: " ++ show bs

-- | A package version.
newtype Version =
  Version {unVersion :: Vector Word}
  deriving (Eq,Ord,Typeable,Data,Generic,Binary,NFData)
instance HasStructuralInfo Version

instance Hashable Version where
  hashWithSalt i = hashWithSalt i . V.toList . unVersion

instance Lift Version where
  lift (Version n) =
    appE (conE 'Version)
         (appE (varE 'V.fromList)
               (listE (map (litE . IntegerL . fromIntegral)
                           (V.toList n))))

instance Show Version where
  show (Version v) =
    intercalate "."
                (map show (V.toList v))

instance ToJSON Version where
  toJSON = toJSON . versionText
instance FromJSON Version where
  parseJSON j =
    do s <- parseJSON j
       case parseVersionFromString s of
         Nothing ->
           fail ("Couldn't parse package version: " ++ s)
         Just ver -> return ver
instance FromJSON a => FromJSON (Map Version a) where
    parseJSON val = do
        m <- parseJSON val
        fmap Map.fromList $ mapM go $ Map.toList m
      where
        go (k, v) = do
            k' <- either (fail . show) return $ parseVersionFromString k
            return (k', v)

-- | Attoparsec parser for a package version.
versionParser :: Parser Version
versionParser =
  do ls <- ((:) <$> num <*> many num')
     let !v = V.fromList ls
     return (Version v)
  where num = decimal
        num' = point *> num
        point = satisfy (== '.')

-- | Convenient way to parse a package version from a 'Text'.
parseVersion :: MonadThrow m => Text -> m Version
parseVersion x = go x
  where go =
          either (const (throwM (VersionParseFail x))) return .
          parseOnly (versionParser <* endOfInput)

-- | Migration function.
parseVersionFromString :: MonadThrow m => String -> m Version
parseVersionFromString =
  parseVersion . T.pack

-- | Get a string representation of a package version.
versionString :: Version -> String
versionString (Version v) =
  intercalate "."
              (map show (V.toList v))

-- | Get a string representation of a package version.
versionText :: Version -> Text
versionText (Version v) =
  T.intercalate
    "."
    (map (T.pack . show)
         (V.toList v))

-- | Convert to a Cabal version.
toCabalVersion :: Version -> Cabal.Version
toCabalVersion (Version v) =
  Cabal.Version (map fromIntegral (V.toList v)) []

-- | Convert from a Cabal version.
fromCabalVersion :: Cabal.Version -> Version
fromCabalVersion (Cabal.Version vs _) =
  let !v = V.fromList (map fromIntegral vs)
  in Version v

-- | Make a package version.
mkVersion :: String -> Q Exp
mkVersion s =
  case parseVersionFromString s of
    Nothing -> error ("Invalid package version: " ++ show s)
    Just pn -> [|pn|]

-- | Display a version range
versionRangeText :: Cabal.VersionRange -> Text
versionRangeText = T.pack . render . disp

-- | Check if a version is within a version range.
withinRange :: Version -> Cabal.VersionRange -> Bool
withinRange v r = toCabalVersion v `Cabal.withinRange` r

-- | A modified intersection which also simplifies, for better display.
intersectVersionRanges :: Cabal.VersionRange -> Cabal.VersionRange -> Cabal.VersionRange
intersectVersionRanges x y = Cabal.simplifyVersionRange $ Cabal.intersectVersionRanges x y

-- | Returns the first two components, defaulting to 0 if not present
toMajorVersion :: Version -> Version
toMajorVersion  (Version v) =
    case V.length v of
        0 -> Version (V.fromList [0,        0])
        1 -> Version (V.fromList [V.head v, 0])
        _ -> Version (V.fromList [V.head v, v V.! 1])

-- | Given a version range and a set of versions, find the latest version from
-- the set that is within the range.
latestApplicableVersion :: Cabal.VersionRange -> Set Version -> Maybe Version
latestApplicableVersion r = listToMaybe . filter (`withinRange` r) . Set.toDescList

-- | Get the next major version number for the given version
nextMajorVersion :: Version -> Version
nextMajorVersion (Version v) =
  case  V.length v of
    0 -> Version (V.fromList [0,        1])
    1 -> Version (V.fromList [V.head v, 1])
    _ -> Version (V.fromList [V.head v, (v V.! 1) + 1])

data VersionCheck
    = MatchMinor
    | MatchExact
    | NewerMinor
    deriving (Show, Eq, Ord)
instance ToJSON VersionCheck where
    toJSON MatchMinor = String "match-minor"
    toJSON MatchExact = String "match-exact"
    toJSON NewerMinor = String "newer-minor"
instance FromJSON VersionCheck where
    parseJSON = withText expected $ \t ->
        case t of
            "match-minor" -> return MatchMinor
            "match-exact" -> return MatchExact
            "newer-minor" -> return NewerMinor
            _ -> fail ("Expected " ++ expected ++ ", but got " ++ show t)
      where
        expected = "VersionCheck value (match-minor, match-exact, or newer-minor)"

checkVersion :: VersionCheck -> Version -> Version -> Bool
checkVersion check (Version wanted) (Version actual) =
    case check of
        MatchMinor -> V.and (V.take 3 matching)
        MatchExact -> V.length wanted == V.length actual && V.and matching
        NewerMinor -> V.and (V.take 2 matching) && newerMinor
  where
    matching = V.zipWith (==) wanted actual
    newerMinor =
        case (wanted V.!? 2, actual V.!? 2) of
            (Nothing, _) -> True
            (Just _, Nothing) -> False
            (Just w, Just a) -> a >= w


text:
require "spec_helper"

describe GraphQL::StaticValidation::DirectivesAreDefined do
  let(:query_string) {"
    query getCheese {
      okCheese: cheese(id: 1) {
        id @skip(if: true),
        source @nonsense(if: false)
        ... on Cheese {
          flavor @moreNonsense
        }
      }
    }
  "}

  let(:validator) { GraphQL::StaticValidation::Validator.new(schema: DummySchema, rules: [GraphQL::StaticValidation::DirectivesAreDefined]) }
  let(:query) { GraphQL::Query.new(DummySchema, query_string) }
  let(:errors) { validator.validate(query)[:errors] }

  describe "non-existent directives" do
    it "makes errors for them" do
      expected = [
        {
          "message"=>"Directive @nonsense is not defined",
          "locations"=>[{"line"=>5, "column"=>16}],
          "path"=>["query getCheese", "okCheese", "source"],
        }, {
          "message"=>"Directive @moreNonsense is not defined",
          "locations"=>[{"line"=>7, "column"=>18}],
          "path"=>["query getCheese", "okCheese", "... on Cheese", "flavor"],
        }
      ]
      assert_equal(expected, errors)
    end
  end
end


text:
from django.apps import AppConfig

class DocsConfig(AppConfig):
    name = 'docs'
    verbose_name = 'Quran Tafseer REST API Documentation'


text:
{-# LANGUAGE OverloadedStrings #-}

module Main where

import Prelude hiding (lookup)
import Control.Applicative ((<$>))
import Data.Aeson (decode')
import qualified Data.ByteString.Char8 as B8
import qualified Data.ByteString.Lazy.Char8 as L8
import Data.Maybe (fromJust)
import Data.Time.Clock (getCurrentTime)
import Data.Time.Clock.POSIX (POSIXTime)
import Database.MongoDB
  ( Query (..), Value (..)
  , (=:), findOne, insertAll_, lookup, select )
import Network.HTTP.Conduit
  ( Request (..), Response (..)
  , httpLbs, parseUrl, withManager )
import Network.HTTP.Types

import Data.Bson.Aeson ()
import Web.WheresMikeCraig.Config

getLastTime :: Config -> IO (Maybe POSIXTime)
getLastTime cfg = do
  Right mdoc <- cfgAccess cfg $ findOne
    (select [] $ cfgPointsColl cfg) { sort = ["date_ts" =: (-1 :: Int)]
                                    , project = ["date_ts" =: (1 :: Int)] }
  return $ fromIntegral <$> (mdoc >>= lookup "date_ts" :: Maybe Integer)

insertPoints :: Config -> L8.ByteString -> IO ()
insertPoints cfg bs = do
  case decode' bs of
    Just (Doc doc) -> case lookup "points" doc of
      Just docs -> do
        Right () <- cfgAccess cfg $ insertAll_ (cfgPointsColl cfg) docs
        return ()
      Nothing -> fail "Unexpected Geoloqi response"
    _ -> fail "Unexpected Geoloqi response"

geoloqiUrl :: String
geoloqiUrl = "https://api.geoloqi.com/1/location/history"

geoloqiReq :: Config -> Maybe POSIXTime -> Request IO
geoloqiReq cfg mtime =
  let opts = "?ignore_gaps=1&count=100000" ++ case mtime of
        Just time -> "&after=" ++ show (truncate time :: Int)
        Nothing -> ""
      token = "OAuth " `B8.append` cfgGeoloqiToken cfg
  in (fromJust $ parseUrl $ geoloqiUrl ++ opts)
    { requestHeaders = [headerAuthorization token] }

main :: IO ()
main = do
  getCurrentTime >>= putStrLn . ("Started recorder at " ++) . show
  cfg <- getConfig
  mtime <- getLastTime cfg
  r <- withManager $ httpLbs $ geoloqiReq cfg mtime
  insertPoints cfg $ responseBody r
  getCurrentTime >>= putStrLn . ("Finished recorder at " ++) . show


text:
#region Includes

using System.Collections.Generic;
using System.Security.Claims;
using Thinktecture.IdentityServer.Core;
using Thinktecture.IdentityServer.Core.Services.InMemory;

#endregion

namespace Daishi.IdentityServer {
    public static class Users {
        public static List<InMemoryUser> Get() {
            return new List<InMemoryUser> {
                new InMemoryUser {
                    Username = "admin",
                    Password = "password",
                    Subject = "1",
                    Claims = new List<Claim> {
                        new Claim(Constants.ClaimTypes.GivenName, "Administrator"),
                        new Claim(Constants.ClaimTypes.FamilyName, "Ryanair"),
                        new Claim(Constants.ClaimTypes.Email, "admin@ryanair.com")
                    }
                },
                new InMemoryUser {
                    Username = "novickyp@ryanair.com",
                    Password = "password",
                    Subject = "173a3d80",
                    Claims = new List<Claim> {
                        new Claim(Constants.ClaimTypes.Email, "novickyp@ryanair.com"),
                        new Claim(Constants.ClaimTypes.GivenName, "Petr"),
                        new Claim(Constants.ClaimTypes.FamilyName, "Novicky")
                    }
                },
                new InMemoryUser {
                    Username = "stors@ryanair.com",
                    Password = "password",
                    Subject = "173a3d81",
                    Claims = new List<Claim> {
                        new Claim(Constants.ClaimTypes.Email, "stors@ryanair.com"),
                        new Claim(Constants.ClaimTypes.GivenName, "Sašo"),
                        new Claim(Constants.ClaimTypes.FamilyName, "Štor")
                    }
                },
                new InMemoryUser {
                    Username = "ivancicm@ryanair.com",
                    Password = "password",
                    Subject = "173a3d82",
                    Claims = new List<Claim> {
                        new Claim(Constants.ClaimTypes.Email, "ivancicm@ryanair.com"),
                        new Claim(Constants.ClaimTypes.GivenName, "Martin"),
                        new Claim(Constants.ClaimTypes.FamilyName, "Ivancic")
                    }
                }
            };
        }
    }
}


text:
#pragma once
#include <string>
#include "Worker.h"
#include "globaldef.h"

class ShowSFeatureWorker : public Worker
{
	Q_OBJECT

private:
	FeaturePara _para;

public:
	void showSFeature()
	{
		QMetaObject::invokeMethod(this, "doWork");
	}
	void setFPara(FeaturePara para)
	{
		_para.feature_type = para.feature_type;
		_para.percent_out = para.percent_out;
	}
	FeaturePara getFPara()
	{
		return _para;
	}
	virtual bool is_para_satisfying(QString &message);
	virtual void prepare();

public slots:
	void doWork();

signals:
	void show();
};


text:
import inspect
from scrapli.driver.core import IOSXEDriver
from scrapli.transport.plugins.telnet.transport import TelnetTransport
from rich import inspect as rinspect
from rich.tree import Tree
from rich import print as rprint
import time

def rich_inheritance_tree(cls, tree=None):
    if not inspect.isclass(cls):
        cls = type(cls)
    tree = Tree(f"{cls.__name__}")
    bases = [c for c in cls.__bases__ if c is not object]
    if bases:
        for base in bases:
            tree.add(rich_inheritance_tree(base, tree))
    return tree

def rich_inheritance_tree2(cls, tree=None):
    if not inspect.isclass(cls):
        cls = type(cls)
    tree = Tree(f"{cls.__name__}")
    subclasses = cls.__subclasses__()
    for sub in subclasses:
        tree.add(f"{sub.__name__}")
    bases = [c for c in cls.__bases__ if c is not object]
    if bases:
        for base in bases:
            tree.add(rich_inheritance_tree(base, tree))
    return tree

def get_inheritance_tree_dict(cls, tree=None):
    if not inspect.isclass(cls):
        cls = type(cls)
    tree = {cls: {}}
    bases = [c for c in cls.__bases__ if c is not object]
    if bases:
        for base in bases:
            base_tree = get_inheritance_tree_dict(base, tree)
            tree[cls].update(base_tree)
    else:
        tree = {cls: None}
    return tree

if __name__ == "__main__":
    #tree = get_inheritance_tree_dict(IOSXEDriver)
    #rprint(tree)
    tree = rich_inheritance_tree(TelnetTransport)
    rprint(tree)
    # print(rinspect(tree.children[0].children, methods=True))


text:
package com.google.android.enterprise.connectedapps.processor.containers;

import static java.util.stream.Collectors.toSet;

import com.google.android.enterprise.connectedapps.annotations.CrossProfile;
import com.google.android.enterprise.connectedapps.processor.ProcessorConfiguration;
import com.google.android.enterprise.connectedapps.processor.SupportedTypes;
import com.google.android.enterprise.connectedapps.processor.TypeUtils;
import com.google.auto.value.AutoValue;
import com.google.common.collect.ImmutableCollection;
import com.google.common.collect.ImmutableSet;
import com.google.common.hash.Hashing;
import com.squareup.javapoet.ClassName;
import java.nio.charset.StandardCharsets;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.stream.IntStream;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.TypeElement;
import javax.lang.model.type.TypeMirror;

/** Wrapper of a {@link CrossProfile} type. */
@AutoValue
public abstract class CrossProfileTypeInfo {

  public abstract TypeElement crossProfileTypeElement();

  public abstract ImmutableCollection<CrossProfileMethodInfo> crossProfileMethods();

  public abstract SupportedTypes supportedTypes();

  public abstract Optional<ConnectorInfo> connectorInfo();

  /**
   * The verbatim (not prefixed) name of the interface class used to make cross-profile or
   * cross-user calls.
   */
  public abstract ClassName generatedClassName();

  public String simpleName() {
    return crossProfileTypeElement().getSimpleName().toString();
  }

  public ClassName className() {
    return ClassName.get(crossProfileTypeElement());
  }

  public boolean isStatic() {
    return crossProfileMethods().stream().allMatch(CrossProfileMethodInfo::isStatic);
  }

  /**
   * Get a numeric identifier for the cross-profile type.
   *
   * <p>This identifier is based on the type's qualified name, and will not change between runs.
   */
  public long identifier() {
    // Stored in a 64 bit long, with ~200 cross-profile types, chance of collision is 1 in 10^15
    return Hashing.murmur3_128()
        .hashString(crossProfileTypeElement().getQualifiedName().toString(), StandardCharsets.UTF_8)
        .asLong();
  }

  public static CrossProfileTypeInfo create(
      ValidatorContext context, ValidatorCrossProfileTypeInfo crossProfileType) {
    TypeElement crossProfileTypeElement = crossProfileType.crossProfileTypeElement();

    List<ExecutableElement> crossProfileMethodElements = crossProfileType.crossProfileMethods();

    Collection<CrossProfileMethodInfo> crossProfileMethods =
        IntStream.range(0, crossProfileMethodElements.size())
            .mapToObj(
                t ->
                    CrossProfileMethodInfo.create(
                        t, crossProfileType, crossProfileMethodElements.get(t), context))
            .collect(toSet());

    SupportedTypes.Builder supportedTypesBuilder = crossProfileType.supportedTypes().asBuilder();

    supportedTypesBuilder.filterUsed(context, crossProfileMethods);

    if (ProcessorConfiguration.GENERATE_TYPE_SPECIFIC_WRAPPERS) {
      supportedTypesBuilder.replaceWrapperPrefix(
          ClassName.bestGuess(
              crossProfileType.crossProfileTypeElement().getQualifiedName().toString()));
    }

    return new AutoValue_CrossProfileTypeInfo(
        crossProfileTypeElement,
        ImmutableSet.copyOf(crossProfileMethods),
        supportedTypesBuilder.build(),
        crossProfileType.connectorInfo(),
        findGeneratedClassName(context, crossProfileTypeElement));
  }

  private static ClassName findGeneratedClassName(
      ValidatorContext context, TypeElement typeElement) {
    return ClassName.get(
        context.elements().getPackageOf(typeElement).getQualifiedName().toString(),
        typeElement.getSimpleName().toString());
  }

  private static Collection<Type> convertTypeMirrorToSupportedTypes(
      SupportedTypes supportedTypes, TypeMirror typeMirror) {
    if (TypeUtils.isGeneric(typeMirror)) {
      return convertGenericTypeMirrorToSupportedTypes(supportedTypes, typeMirror);
    }
    return Collections.singleton(supportedTypes.getType(typeMirror));
  }

  private static Collection<Type> convertGenericTypeMirrorToSupportedTypes(
      SupportedTypes supportedTypes, TypeMirror typeMirror) {
    Collection<Type> types = new HashSet<>();
    TypeMirror genericType = TypeUtils.removeTypeArguments(typeMirror);
    Type supportedType = supportedTypes.getType(genericType);
    if (!supportedType.isSupportedWithAnyGenericType()) {
      for (TypeMirror typeArgument : TypeUtils.extractTypeArguments(typeMirror)) {
        types.addAll(convertTypeMirrorToSupportedTypes(supportedTypes, typeArgument));
      }
    }
    types.add(supportedTypes.getType(genericType));
    return types;
  }
}


text:
import MySQLdb

# ---------------------------------------------

online = True

result = []

db = MySQLdb.connect(host="localhost", user="root", passwd="root", db="toolkit_ruby")
cur = db.cursor()

# ---------------------------------------------

f = open("../brave-intel-server/filters/systems.lst",'w')

cur.execute("SELECT solarSystemName,regionName FROM mapSolarSystems INNER JOIN mapRegions ON mapSolarSystems.regionID=mapRegions.regionID where security != '-0.99'")
for res in cur.fetchall() :
	name = str(res[0])
	region = str(res[1])
	f.write(name + "=" + region + "\n")

f.close()

# ---------------------------------------------


text:
using System;
using System.Runtime.Serialization;

namespace BL4N.Data
{
    /// <summary> 課題の更新情報を表します </summary>
    public interface IIssueUpdate
    {
        /// <summary> 課題を取得します. </summary>
        IIssue Issue { get; }

        /// <summary> 更新日時を取得します. </summary>
        DateTime Updated { get; }
    }

    [DataContract]
    internal sealed class IssueUpdate : ExtraJsonPropertyReadableObject, IIssueUpdate
    {
        [DataMember(Name = "issue")]
        private Issue _issue;

        [IgnoreDataMember]
        public IIssue Issue
        {
            get { return _issue; }
        }

        [DataMember(Name = "updated")]
        public DateTime Updated { get; private set; }
    }
}


text:
import * as path from 'path';
import * as task from 'azure-pipelines-task-lib/task';
import * as telemetry from 'azure-pipelines-tasks-utility-common/telemetry'
import { getPlatform } from './taskutil';
import { usePythonVersion } from './usepythonversion';

(async () => {
    try {
        task.setResourcePath(path.join(__dirname, 'task.json'));
        const versionSpec = task.getInput('versionSpec', true);
        const disableDownloadFromRegistry = task.getBoolInput('disableDownloadFromRegistry');
        const allowUnstable = task.getBoolInput('allowUnstable');
        const addToPath = task.getBoolInput('addToPath', true);
        const architecture = task.getInput('architecture', true);
        const githubToken = task.getInput('githubToken', false);
        await usePythonVersion({
            versionSpec,
            allowUnstable,
            disableDownloadFromRegistry,
            addToPath,
            architecture,
            githubToken
        },
        getPlatform());
        task.setResult(task.TaskResult.Succeeded, "");
        telemetry.emitTelemetry('TaskHub', 'UsePythonVersionV0', {
            versionSpec,
            addToPath,
            architecture
        });
    } catch (error) {
        task.setResult(task.TaskResult.Failed, error.message);
    }
})();