text:
namespace OpenTissue
{
namespace aabb_tree
{

  template<typename aabb_tree_geometry>
  class RefitterPolicy
  {
  public:

    typedef typename aabb_tree_geometry::bvh_type       bvh_type;
    typedef typename bvh_type::volume_type              volume_type;
    typedef typename bvh_type::geometry_type            geometry_type;
    typedef typename bvh_type::bv_ptr                   bv_ptr;
    typedef typename bvh_type::annotated_bv_ptr         annotated_bv_ptr;
    typedef typename bvh_type::annotated_bv_type        annotated_bv_type;
    typedef typename bvh_type::bv_iterator              bv_iterator;
    typedef typename bvh_type::geometry_iterator        geometry_iterator;
    typedef typename volume_type::real_type             real_type;
    typedef typename volume_type::vector3_type          vector3_type;

  public:

    real_type m_enlargement;   ///< Additive enlargement factor. All volumes are slightly
                               ///< enlarged to avoid problems with numerical precision and
                               ///< truncation. Default value is zero, but can be changed by user.

  public:

    RefitterPolicy()
      : m_enlargement(0)
    {}

  public:

    void refit(bv_ptr bv)
    {
      assert(bv);
      vector3_type & m = bv->volume().min();
      vector3_type & M = bv->volume().max();
      m = vector3_type( math::detail::highest<real_type>() );
      M = vector3_type( math::detail::lowest<real_type>() );
      if(bv->is_leaf())
      {
        annotated_bv_ptr annotated_bv = boost::static_pointer_cast<annotated_bv_type>(bv);

        geometry_type * geometry = &(*(annotated_bv->geometry_begin()));
        vector3_type p0 = geometry->m_p0->position();
        vector3_type p1 = geometry->m_p1->position();
        vector3_type p2 = geometry->m_p2->position();

        m = min(m, p0);
        m = min(m, p1);
        m = min(m, p2);
        M = max(M, p0);
        M = max(M, p1);
        M = max(M, p2);
        if(m_enlargement>0)
        {
          m -= vector3_type(m_enlargement,m_enlargement,m_enlargement);
          M += vector3_type(m_enlargement,m_enlargement,m_enlargement);
        }
      }
      else
      {
        for ( bv_iterator child = bv->child_begin();child!=bv->child_end();++child )
        {
          m = min( m,  child->volume().min() );
          M = max( M,  child->volume().max() );
        }
      }
    }
  };

} // namespace aabb_tree

} // namespace OpenTissue

// OPENTISSUE_COLLISION_AABB_TREE_POLICIES_AABB_TREE_REFITTER_POLICY_H
#endif


text:
import { DESCRIPTORS, STRICT } from '../helpers/constants';

import create from 'core-js-pure/es/object/create';
import __defineGetter__ from 'core-js-pure/es/object/define-getter';
import __lookupGetter__ from 'core-js-pure/es/object/lookup-getter';

if (DESCRIPTORS) {
  QUnit.test('Object#__lookupGetter__', assert => {
    assert.isFunction(__lookupGetter__);
    assert.same(__lookupGetter__({}, 'key'), undefined, 'empty object');
    assert.same(__lookupGetter__({ key: 42 }, 'key'), undefined, 'data descriptor');
    const object = {};
    function getter() { /* empty */ }
    __defineGetter__(object, 'key', getter);
    assert.same(__lookupGetter__(object, 'key'), getter, 'own getter');
    assert.same(__lookupGetter__(create(object), 'key'), getter, 'proto getter');
    assert.same(__lookupGetter__(create(object), 'foo'), undefined, 'empty proto');
    if (STRICT) {
      assert.throws(() => __lookupGetter__(null, 1, () => { /* empty */ }), TypeError, 'Throws on null as `this`');
      assert.throws(() => __lookupGetter__(undefined, 1, () => { /* empty */ }), TypeError, 'Throws on undefined as `this`');
    }
  });
}

redpajama_set_name: RedPajamaGithub


text:
declare module "*.jpg" {
  const content: any;
  export default content;
}


text:
package com.support;

public class Cfg {
	/**
	 * File structure
	 * ./-
	 * 	 |-tmp
	 * 	 |-users-
	 * 			 |-userlist...
	 * 	 |-world
	 */
	String rootDir = ".";
	String dirLists[] = {"world", "tmp", "users", "developer"};

	String tmpPath = "tmp";
	String worldMdlPath = "world";
	String adminPath = "admin";
	String usersPath = "users";
	String worldMdlFile = "WorldModel.mdl";

	String userName = "admin";
	String feaSuf = ".mfcc";
	String mdlSuf = ".mdl";

	static Cfg Instance = new Cfg();
	public static Cfg getInstance() {
		return Instance;
	}
	private Cfg(){}

	public String getUsersPath() {
		return usersPath;
	}
	public void setUsersPath(String usersPath) {
		this.usersPath = usersPath;
	}
	public String getRootDir() {
		return rootDir;
	}
	public void setRootDir(String rootDir) {
		this.rootDir = rootDir;
	}
	public String[] getDirLists() {
		return dirLists;
	}
	public void setDirLists(String[] dirLists) {
		this.dirLists = dirLists;
	}
	public String getTmpPath() {
		return tmpPath;
	}
	public void setTmpPath(String tmpPath) {
		this.tmpPath = tmpPath;
	}
	public String getWorldMdlPath() {
		return worldMdlPath;
	}
	public void setWorldMdlPath(String worldMdlPath) {
		this.worldMdlPath = worldMdlPath;
	}
	public String getAdminPath() {
		return adminPath;
	}
	public void setAdminPath(String adminPath) {
		this.adminPath = adminPath;
	}
	public String getWorldMdlFile() {
		return worldMdlFile;
	}
	public void setWorldMdlFile(String worldMdlFile) {
		this.worldMdlFile = worldMdlFile;
	}
	public String getUserName() {
		return userName;
	}
	public void setUserName(String userName) {
		this.userName = userName;
	}
	public String getFeaSuf() {
		return feaSuf;
	}
	public void setFeaSuf(String feaSuf) {
		this.feaSuf = feaSuf;
	}
	public String getMdlSuf() {
		return mdlSuf;
	}
	public void setMdlSuf(String mdlSuf) {
		this.mdlSuf = mdlSuf;
	}

}


text:
export * from "./ShowBanner"
export * from "./ShowCard"


text:
opal_filter "Symbols" do
  fails "A Symbol literal is a ':' followed by any number of valid characters"
  fails "A Symbol literal is a ':' followed by a single- or double-quoted string that may contain otherwise invalid characters"
  fails "A Symbol literal is converted to a literal, unquoted representation if the symbol contains only valid characters"
  fails "A Symbol literal can be created by the %s-delimited expression"
  fails "A Symbol literal can contain null in the string"
  fails "A Symbol literal can be an empty string"

  fails "String#each_line raises a TypeError when the separator is a symbol"
  fails "String#gsub with pattern and Hash ignores non-String keys"
  fails "String#index raises a TypeError if passed a Symbol"
  fails "String#lines raises a TypeError when the separator is a symbol"
  fails "String#sub with pattern and Hash ignores non-String keys"
  fails "String#upto does not work with symbols"
end


text:
//
//  RKEntityCache.h
//  RestKit
//
//  Created by Blake Watters on 5/2/12.
//  Copyright (c) 2012 RestKit. All rights reserved.
//
//  Licensed under the Apache License, Version 2.0 (the "License");
//  you may not use this file except in compliance with the License.
//  You may obtain a copy of the License at
//
//  http://www.apache.org/licenses/LICENSE-2.0
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.
//

#import <CoreData/CoreData.h>

@class RKEntityByAttributeCache;

/**
 Instances of `RKEntityCache` provide an in-memory caching mechanism for objects in a Core Data managed object context. Managed objects can be cached by attribute for fast retrieval without repeatedly hitting the Core Data persistent store. This can provide a substantial speed advantage over issuing fetch requests in cases where repeated look-ups of the same data are performed using a small set of attributes as the query key. Internally, the cache entries are maintained as references to the `NSManagedObjectID` of corresponding cached objects.
 */
@interface RKEntityCache : NSObject

///-----------------------------
/// @name Initializing the Cache
///-----------------------------

/**
 Initializes the receiver with a managed object context containing the entity instances to be cached.

 @param context The managed object context containing objects to be cached.
 @returns The receiver, initialized with the given context.
 */
- (instancetype)initWithManagedObjectContext:(NSManagedObjectContext *)context NS_DESIGNATED_INITIALIZER;

/**
 The managed object context with which the receiver is associated.
 */
@property (nonatomic, strong, readonly) NSManagedObjectContext *managedObjectContext;

///-------------------------------------
/// @name Configuring the Callback Queue
///-------------------------------------

/**
 The queue on which to dispatch callbacks for asynchronous operations. When `nil`, the main queue is used.

 **Default**: `nil`
 */
@property (nonatomic, assign) dispatch_queue_t callbackQueue;

///------------------------------------
/// @name Caching Objects by Attributes
///------------------------------------

/**
 Caches all instances of an entity using the value for an attribute as the cache key.

 @param entity The entity to cache all instances of.
 @param attributeNames The attributes to cache the instances by.
 */
- (void)cacheObjectsForEntity:(NSEntityDescription *)entity byAttributes:(NSArray *)attributeNames completion:(void (^)(void))completion;

/**
 Returns a Boolean value indicating if all instances of an entity have been cached by a given attribute name.

 @param entity The entity to check the cache status of.
 @param attributeNames The attributes to check the cache status with.
 @return YES if the cache has been loaded with instances with the given attribute, else NO.
 */
- (BOOL)isEntity:(NSEntityDescription *)entity cachedByAttributes:(NSArray *)attributeNames;

/**
 Retrieves the first cached instance of a given entity where the specified attribute matches the given value.

 @param entity The entity to search the cache for instances of.
 @param attributeValues The attribute values return a match for.
 @param context The managed object from which to retrieve the cached results.
 @return A matching managed object instance or nil.
 @raise NSInvalidArgumentException Raised if instances of the entity and attribute have not been cached.
 */
- (NSManagedObject *)objectForEntity:(NSEntityDescription *)entity withAttributeValues:(NSDictionary *)attributeValues inContext:(NSManagedObjectContext *)context;

/**
 Retrieves all cached instances of a given entity where the specified attribute matches the given value.

 @param entity The entity to search the cache for instances of.
 @param attributeValues The attribute values return a match for.
 @param context The managed object from which to retrieve the cached results.
 @return All matching managed object instances or nil.
 @raise NSInvalidArgumentException Raised if instances of the entity and attribute have not been cached.
 */
- (NSSet *)objectsForEntity:(NSEntityDescription *)entity withAttributeValues:(NSDictionary *)attributeValues inContext:(NSManagedObjectContext *)context;

///-----------------------------------------------------------------------------
// @name Accessing Underlying Caches
///-----------------------------------------------------------------------------

/**
 Retrieves the underlying entity attribute cache for a given entity and attribute.

 @param entity The entity to retrieve the entity attribute cache object for.
 @param attributeNames  The attribute to retrieve the entity attribute cache object for.
 @return The entity attribute cache for the given entity and attribute, or nil if none was found.
 */
- (RKEntityByAttributeCache *)attributeCacheForEntity:(NSEntityDescription *)entity attributes:(NSArray *)attributeNames;

/**
 Retrieves all entity attributes caches for a given entity.

 @param entity The entity to retrieve the collection of entity attribute caches for.
 @return An array of entity attribute cache objects for the given entity or an empty array if none were found.
 */
- (NSArray *)attributeCachesForEntity:(NSEntityDescription *)entity;

///-----------------------------------------------------------------------------
// @name Managing the Cache
///-----------------------------------------------------------------------------

/**
 Flushes the entity cache by sending a flush message to each entity attribute cache contained within the receiver.

 @param completion An optional block to be executed when the flush has completed.
 @see [RKEntityByAttributeCache flush]
 */
- (void)flush:(void (^)(void))completion;

/**
 Adds the given set of objects to all entity attribute caches for the object's entity contained within the receiver.

 @param objects The set of objects to add to the appropriate entity attribute caches.
 @param completion An optional block to be executed when the object addition has completed.
 */
- (void)addObjects:(NSSet *)objects completion:(void (^)(void))completion;

/**
 Removes the given set of objects from all entity attribute caches for the object's entity contained within the receiver.

 @param objects The set of objects to remove from the appropriate entity attribute caches.
 @param completion An optional block to be executed when the object removal has completed.
 */
- (void)removeObjects:(NSSet *)objects completion:(void (^)(void))completion;

/**
 Returns a Boolean value that indicates if the receiver contains the given object in any of its attribute caches.

 @param managedObject The object to check for.
 @return `YES` if the receiver contains the given object in one or more of its caches, else `NO`.
 */
- (BOOL)containsObject:(NSManagedObject *)managedObject;

/**
 Call this before beginning a sequence of operations that require the cache not to be flushed.

 This is used by RKInMemoryManagedObjectCache to workaround https://github.com/RestKit/RestKit/issues/1613 .

 @see endAccessing
 */
- (void)beginAccessing;

/**
 Call this after completing a sequence of operations that require the cache not to be flushed.

 This is used by RKInMemoryManagedObjectCache to workaround https://github.com/RestKit/RestKit/issues/1613 .

 @see beginAccessing
 */
- (void)endAccessing;

@end

// Deprecated in v0.20.1
@interface RKEntityCache (Deprecations)
- (void)addObject:(NSManagedObject *)object DEPRECATED_ATTRIBUTE; // use `addObjects:completion:`
- (void)removeObject:(NSManagedObject *)object DEPRECATED_ATTRIBUTE; // use `removeObjects:completion:`
@end


text:
This package implements a distributed system that guarantees the generation of sequential `ID`s by using RW quorums and read-repair conflict-resolution strategies.

It is a direct, heavily documented, tested & benchmarked implementation of the `leaderless consistency` strategy described at the [root of this repository](/).

**Table of contents**

- [RRSeq](#rrseq)
  - [Installing](#installing)
  - [Quickstart](#quickstart)
  - [Performance](#performance)

## Installing

The easiest way is to `go get` all the things:

```
go get -u github.com/teh-cmc/seq/...
```
:warning: This most likely will return a `no buildable Go source files` error. You can safely ignore it.

## Quickstart

This quickstart will show you how to start your own cluster of `RRServer`s and `RRSeq`s.
You'll then be able to experiment with it at will.

Everything that follows assumes that your current working directory is [`/rr_seq`](/rr_seq).

**I. Running the tests**

First thing first, you should make sure that all the tests pass without any issue.

```
go test -cpu 1,4,8 -run=. -bench=none -cover -v
```
:warning: You should expect some innocuous `grpc` warnings when executing these commands.

**II. Starting some servers**

[`example/server/main.go`](example/server/main.go) implements a simple CLI program that starts a `RRServer` with the given parameters.

This code is pasted below for convenience:

```Go
package main

import (
	"flag"
	"fmt"
	"log"
	"os"
	"os/signal"

	"github.com/teh-cmc/seq/rr_seq"
)

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

var s *rrs.RRServer

func usage() string { return "./server addr path peer1_addr [peerN_addr...]" }

func main() {
	flag.Parse()
	if flag.NArg() < 3 {
		fmt.Println("Usage:", usage())
		os.Exit(1)
	}

	var f *os.File
	var err error

	f, err = os.Open(flag.Arg(1))
	if err != nil {
		f, err = os.Create(flag.Arg(1))
		if err != nil {
			log.Fatal(err)
		}
	}
	_ = f.Close()

	s, err := rrs.NewRRServer(flag.Arg(0), flag.Arg(1), flag.Args()[2:]...)
	if err != nil {
		log.Fatal(err)
	}

	log.Println("ready")

	c := make(chan os.Signal, 1)
	signal.Notify(c, os.Interrupt)
	<-c

	_ = s.Close()
}
```

Starting a server is done as the following:

```
./server addr path peer1_addr [peerN_addr...]
```

Let's start a cluster of 3 servers, listening on ports `19001`, `19002` and `19003`, respectively:

```
go run example/server/main.go :19001 /tmp/serv1_persist :19002 :19003
go run example/server/main.go :19002 /tmp/serv2_persist :19001 :19003
go run example/server/main.go :19003 /tmp/serv3_persist :19001 :19002
```
:warning: You should expect some innocuous `grpc` warnings when executing these commands.

That's it, you're now running a cluster composed 3 `RRServer`s.

**III. Starting some clients**

[`example/client/main.go`](example/client/main.go) implements a simple CLI program that starts a `RRSeq` with the given parameters.

This code is pasted below for convenience:

```Go
package main

import (
	"flag"
	"fmt"
	"log"
	"os"
	"os/signal"
	"strconv"
	"time"

	"github.com/teh-cmc/seq/rr_seq"
)

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

var s *rrs.RRSeq

func usage() string { return "./client seq_name buf_size ms_delay addr1 [addrN...]" }

func main() {
	flag.Parse()
	if flag.NArg() < 4 {
		fmt.Println("Usage:", usage())
		os.Exit(1)
	}

	bufSize, err := strconv.ParseInt(flag.Arg(1), 10, 64)
	if err != nil {
		log.Fatal(err)
	}
	delay, err := strconv.ParseInt(flag.Arg(2), 10, 64)
	if err != nil {
		log.Fatal(err)
	}

	s, err = rrs.NewRRSeq(flag.Arg(0), int(bufSize), flag.Args()[3:]...)
	ids := s.Stream()
	log.Println("ready")

	c := make(chan os.Signal, 1)
	signal.Notify(c, os.Interrupt)

infLoop:
	for {
		select {
		case <-c:
			break infLoop
		case <-time.After(time.Duration(delay) * time.Millisecond):
			select {
			case id := <-ids:
				log.Println("Got:", id)
			default:
			}
		}
	}

	_ = s.Close()
}
```

Starting a client is done as the following:

```
./client seq_name buf_size ms_delay addr1 [addrN...]
```

Let's start 2 clients, both using the sequence named `myseq`.
This first client will have a buffer size of `1000` and will try to fetch a new ID every `10ms`; while the second client will have a buffer size of `1250` and will try to fetch a new ID every `5ms`:

```
go run example/client/main.go myseq 1000 10 :19001 :19002 :19003
go run example/client/main.go myseq 1250 5  :19001 :19002 :19003
```
:warning: You should expect some innocuous `grpc` warnings when executing these commands.

That's it, you now have 2 `RRSeq`s fetching sequential IDs from your cluster of 3 `RRServer`s.

**IV. Experimenting**

Now that you have a running cluster with a bunch of clients connected to it, you can start experimenting however you like. Here are some ideas:

- `SIGINT`/`SIGQUIT`/`SIGKILL` some or all of the servers and see what happens
- `SIGINT`/`SIGQUIT`/`SIGKILL` some or all of the clients and see what happens
- `rm` some or all of the persistent logs and see what happens
- any combination of the above

:warning: Due to `grpc`'s exponential backoff algorithm used for reconnections, it can take quite some time for a `RRSeq` to reconnect to a `RRServer`.

TL;DR: wreak havoc.

## Performance

### Running the benchmarks

```
go test -cpu 1,8,32 -run=none -bench=. -cover -v
```
:warning: You should expect some innocuous `grpc` warnings when executing these commands.

Here are the results using a `DELL XPS 15-9530 (i7-4712HQ@2.30GHz)`:

```
BenchmarkRRSeq_BufSize0_SingleClient                       	    1000	   1026260 ns/op
BenchmarkRRSeq_BufSize0_SingleClient-8                     	    3000	    500635 ns/op
BenchmarkRRSeq_BufSize0_SingleClient-32                    	    3000	    512832 ns/op
BenchmarkRRSeq_BufSize1_SingleClient                       	    1000	   1062353 ns/op
BenchmarkRRSeq_BufSize1_SingleClient-8                     	    3000	    514863 ns/op
BenchmarkRRSeq_BufSize1_SingleClient-32                    	    3000	    518578 ns/op
BenchmarkRRSeq_BufSize2_SingleClient                       	    2000	    551448 ns/op
BenchmarkRRSeq_BufSize2_SingleClient-8                     	    5000	    260458 ns/op
BenchmarkRRSeq_BufSize2_SingleClient-32                    	    5000	    263286 ns/op
BenchmarkRRSeq_BufSize1024_SingleClient                    	 1000000	      1261 ns/op
BenchmarkRRSeq_BufSize1024_SingleClient-8                  	 2000000	       714 ns/op
BenchmarkRRSeq_BufSize1024_SingleClient-32                 	 2000000	       707 ns/op
BenchmarkRRSeq_BufSize0_ConcurrentClients_Local            	    1000	   1121957 ns/op
BenchmarkRRSeq_BufSize0_ConcurrentClients_Local-8          	    3000	    530608 ns/op
BenchmarkRRSeq_BufSize0_ConcurrentClients_Local-32         	    3000	    547488 ns/op
BenchmarkRRSeq_BufSize1_ConcurrentClients_Local            	    2000	   1146762 ns/op
BenchmarkRRSeq_BufSize1_ConcurrentClients_Local-8          	    3000	    538000 ns/op
BenchmarkRRSeq_BufSize1_ConcurrentClients_Local-32         	    3000	    543174 ns/op
BenchmarkRRSeq_BufSize2_ConcurrentClients_Local            	    2000	    572742 ns/op
BenchmarkRRSeq_BufSize2_ConcurrentClients_Local-8          	    5000	    271561 ns/op
BenchmarkRRSeq_BufSize2_ConcurrentClients_Local-32         	    5000	    273733 ns/op
BenchmarkRRSeq_BufSize1024_ConcurrentClients_Local         	 1000000	      1315 ns/op
BenchmarkRRSeq_BufSize1024_ConcurrentClients_Local-8       	 2000000	       879 ns/op
BenchmarkRRSeq_BufSize1024_ConcurrentClients_Local-32      	 1000000	      1048 ns/op
BenchmarkRRSeq_BufSize0_ConcurrentClients_Distributed      	       1	1155801513 ns/op
BenchmarkRRSeq_BufSize0_ConcurrentClients_Distributed-8    	    2000	    907526 ns/op
BenchmarkRRSeq_BufSize0_ConcurrentClients_Distributed-32   	    2000	    955798 ns/op
BenchmarkRRSeq_BufSize1_ConcurrentClients_Distributed      	       1	1543643181 ns/op
BenchmarkRRSeq_BufSize1_ConcurrentClients_Distributed-8    	    1000	   1006642 ns/op
BenchmarkRRSeq_BufSize1_ConcurrentClients_Distributed-32   	    1000	   1042091 ns/op
BenchmarkRRSeq_BufSize2_ConcurrentClients_Distributed      	       1	1622989431 ns/op
BenchmarkRRSeq_BufSize2_ConcurrentClients_Distributed-8    	    3000	    507277 ns/op
BenchmarkRRSeq_BufSize2_ConcurrentClients_Distributed-32   	    2000	    534845 ns/op
BenchmarkRRSeq_BufSize1024_ConcurrentClients_Distributed   	       1	1129368563 ns/op
BenchmarkRRSeq_BufSize1024_ConcurrentClients_Distributed-8 	 2000000	       939 ns/op
BenchmarkRRSeq_BufSize1024_ConcurrentClients_Distributed-32	 1000000	      1065 ns/op
```

And the same results for `SimpleBufSeq` (still using a `DELL XPS 15-9530 (i7-4712HQ@2.30GHz)`):

```
BenchmarkSimpleBufSeq_BufSize0_SingleClient           	 3000000	       426 ns/op
BenchmarkSimpleBufSeq_BufSize0_SingleClient-8         	 3000000	       449 ns/op
BenchmarkSimpleBufSeq_BufSize0_SingleClient-32        	 3000000	       449 ns/op
BenchmarkSimpleBufSeq_BufSize1_SingleClient           	 5000000	       347 ns/op
BenchmarkSimpleBufSeq_BufSize1_SingleClient-8         	 5000000	       374 ns/op
BenchmarkSimpleBufSeq_BufSize1_SingleClient-32        	 5000000	       376 ns/op
BenchmarkSimpleBufSeq_BufSize1024_SingleClient        	10000000	       188 ns/op
BenchmarkSimpleBufSeq_BufSize1024_SingleClient-8      	10000000	       222 ns/op
BenchmarkSimpleBufSeq_BufSize1024_SingleClient-32     	10000000	       220 ns/op
BenchmarkSimpleBufSeq_BufSize0_ConcurrentClients      	 3000000	       421 ns/op
BenchmarkSimpleBufSeq_BufSize0_ConcurrentClients-8    	 3000000	       544 ns/op
BenchmarkSimpleBufSeq_BufSize0_ConcurrentClients-32   	 2000000	       654 ns/op
BenchmarkSimpleBufSeq_BufSize1_ConcurrentClients      	 5000000	       344 ns/op
BenchmarkSimpleBufSeq_BufSize1_ConcurrentClients-8    	 3000000	       510 ns/op
BenchmarkSimpleBufSeq_BufSize1_ConcurrentClients-32   	 2000000	       635 ns/op
BenchmarkSimpleBufSeq_BufSize2_ConcurrentClients      	 5000000	       315 ns/op
BenchmarkSimpleBufSeq_BufSize2_ConcurrentClients-8    	 3000000	       490 ns/op
BenchmarkSimpleBufSeq_BufSize2_ConcurrentClients-32   	 2000000	       630 ns/op
BenchmarkSimpleBufSeq_BufSize1024_ConcurrentClients   	10000000	       189 ns/op
BenchmarkSimpleBufSeq_BufSize1024_ConcurrentClients-8 	 5000000	       370 ns/op
BenchmarkSimpleBufSeq_BufSize1024_ConcurrentClients-32	 3000000	       597 ns/op
```

### Comparing performance with `SimpleBufSeq`

In order compare the performance of `SimpleBufSeq` and `RRSeq/RRServer`; we'll need to focus of 3 situations:

- 32 concurrent clients trying to fetch IDs from a `Sequencer` with a buffering size of `0`

  `SimpleBufSeq`:
  ```
  BenchmarkSimpleBufSeq_BufSize0_ConcurrentClients-32   	    2000000	       654 ns/op
  ```
  `RRSeq`:
  ```
  BenchmarkRRSeq_BufSize0_ConcurrentClients_Distributed-32   	   2000	    955798 ns/op
  ```

- 32 concurrent clients trying to fetch IDs from a `Sequencer` with a buffering size of `2`

  `SimpleBufSeq`:
  ```
  BenchmarkSimpleBufSeq_BufSize2_ConcurrentClients-32   	    2000000	       630 ns/op
  ```
  `RRSeq`:
  ```
  BenchmarkRRSeq_BufSize2_ConcurrentClients_Distributed-32   	   2000	    534845 ns/op
  ```

- 32 concurrent clients trying to fetch IDs from a `Sequencer` with a buffering size of `1024`

  `SimpleBufSeq`:
  ```
  BenchmarkSimpleBufSeq_BufSize1024_ConcurrentClients-32	    3000000	       597 ns/op
  ```
  `RRSeq`:
  ```
  BenchmarkRRSeq_BufSize1024_ConcurrentClients_Distributed-32   1000000	      1065 ns/op
  ```

The results are pretty much self explanatory.

With a small buffer size, `RRSeq` is basically DOS-ing itself out of existence.
Once the buffer size starts to increase, the disk & network contention decreases proportionally:
- Starting with an empty buffer, `RRSeq` is 3 orders of magnitude slower than `SimpleBufSeq`, i.e. barely usable;
- Once it reaches a 1024-wide buffer, `RRSeq` becomes less than 2 times slower than a `SimpleBufSeq`


text:
<!DOCTYPE html>

	<meta charset="UTF-8">
	<title>ngTest Controller使用</title>

		{{vm.name}}
		<foo-directive name="{{vm.name}}"></foo-directive>


text:
RSpec.describe StackMaster::ParameterResolvers::LatestContainer do
  let(:config) { double(base_dir: '/base') }
  let(:stack_definition) { double(stack_name: 'mystack', region: 'us-east-1') }
  subject(:resolver) { described_class.new(config, stack_definition) }
  let(:ecr) { Aws::ECR::Client.new(stub_responses: true) }

  before do
    allow(Aws::ECR::Client).to receive(:new).and_return(ecr)
  end

  context 'when matches are found' do
    before do
      ecr.stub_responses(:describe_images, next_token: nil, image_details: [
        { registry_id: '012345678910', image_digest: 'sha256:decafc0ffee', image_pushed_at: Time.utc(2015,1,2,0,0), image_tags: ['v1'] },
        { registry_id: '012345678910', image_digest: 'sha256:deadbeef', image_pushed_at: Time.utc(2015,1,3,0,0), image_tags: ['v2'] }
      ])
    end

    it 'returns the latest one' do
      expect(resolver.resolve({'repository_name' => 'foo'})).to eq '012345678910.dkr.ecr.us-east-1.amazonaws.com/foo@sha256:deadbeef'
    end
  end

  context 'when no matches are found' do
    before do
      ecr.stub_responses(:describe_images, next_token: nil, image_details: [])
    end

    it 'returns nil' do
      expect(resolver.resolve({'repository_name' => 'foo'})).to be_nil
    end
  end

  context 'when a tag is passed in' do
    before do
      ecr.stub_responses(:describe_images, next_token: nil, image_details: [
        { registry_id: '012345678910', image_digest: 'sha256:decafc0ffee', image_pushed_at: Time.utc(2015,1,2,0,0), image_tags: ['v1', 'production'] },
        { registry_id: '012345678910', image_digest: 'sha256:deadbeef', image_pushed_at: Time.utc(2015,1,3,0,0), image_tags: ['v2'] }
      ])
    end

    context 'when image exists' do
      it 'returns the image with the production tag' do
        expect(resolver.resolve({'repository_name' => 'foo', 'tag' => 'production'})).to eq '012345678910.dkr.ecr.us-east-1.amazonaws.com/foo@sha256:decafc0ffee'
      end
    end

    context 'when no image exists for this tag' do
      it 'returns nil' do
        expect(resolver.resolve({'repository_name' => 'foo', 'tag' => 'nosuchtag'})).to be_nil
      end
    end
  end

  context 'when registry_id is passed in' do
    before do
      ecr.stub_responses(:describe_images, next_token: nil, image_details: [
        { registry_id: '012345678910', image_digest: 'sha256:decafc0ffee', image_pushed_at: Time.utc(2015,1,2,0,0), image_tags: ['v1'] },
      ])
    end

    it 'passes registry_id to describe_images' do
      expect(ecr).to receive(:describe_images).with(repository_name: "foo", registry_id: "012345678910", next_token: nil, filter: {:tag_status=>"TAGGED"})
      resolver.resolve({'repository_name' => 'foo', 'registry_id' => '012345678910'})
    end
  end

  context 'when there are multiple pages' do
    before do
      ecr.stub_responses(:describe_images, [
        { next_token: '1', image_details: [
          { registry_id: '012345678910', image_digest: 'sha256:decafc0ffee', image_pushed_at: Time.utc(2015,1,2,0,0), image_tags: ['v1'] },
          { registry_id: '012345678910', image_digest: 'sha256:deadbeef', image_pushed_at: Time.utc(2015,1,3,0,0), image_tags: ['latest', 'v2'] }
        ]},
        { next_token: nil, image_details: [
          { registry_id: '012345678910', image_digest: 'sha256:badf00d', image_pushed_at: Time.utc(2015,1,4,0,0), image_tags: ['v3'] },
          { registry_id: '012345678910', image_digest: 'sha256:d15ea5e', image_pushed_at: Time.utc(2015,1,5,0,0), image_tags: ['v4'] }
        ]}
      ])
    end

    it 'takes all pages into account' do
      expect(resolver.resolve({'repository_name' => 'foo'})).to eq '012345678910.dkr.ecr.us-east-1.amazonaws.com/foo@sha256:d15ea5e'
    end
  end
end


text:
<!DOCTYPE html>

<meta charset="utf-8" />
<title>Bootstrapy</title>
<link rel="stylesheet" media="all" href="bower_components/bootstrap/dist/css/bootstrap.css">
<link rel="stylesheet" media="all" href="css/bootstrapy.css">
<link rel="stylesheet" media="all" href="css/main.css">

<base target="_blank">

Bootstrapy <button rel='tooltip' type="button" class="btn btn-xs btn-default" data-toggle="tooltip" data-placement="top" title="close me" id="close-button">close</button>

  <form role='form'>

Global

            Toggle

          <button ng-click="selectAll()" rel='tooltip' type="button" class="btn btn-xs btn-success" data-toggle="tooltip" data-placement="top" title="highlight all">All</button>
          <button ng-click="selectNone()" rel='tooltip' type="button" class="btn btn-xs btn-success" data-toggle="tooltip" data-placement="top" title="remove all">None</button>

Main selectors

            <input ng-model="q" type="text" class="form-control input-sm" id="filter" placeholder="Filter by class: row, col, form, visible...">

            {{rule.name}}

          <button ng-repeat='color in colors' ng-click="select(rule, color)" type="button" id='gridRows' class="btn btn-default {{color}} {{rule.color == color && 'activated' || ''}}"></button>
          <button ng-click="select(rule, '')" rel='tooltip' type="button" class="btn btn-default" data-toggle="tooltip" data-placement="top" title="remove"></button>

  </form>


text:
///***********************************************************************
///Copyright 2016 叶嘉永
///
///Licensed under the Apache License, Version 2.0 (the "License");
///you may not use this file except in compliance with the License.
///You may obtain a copy of the License at
///
///    http://www.apache.org/licenses/LICENSE-2.0
///
///Unless required by applicable law or agreed to in writing, software
///distributed under the License is distributed on an "AS IS" BASIS,
///WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
///See the License for the specific language governing permissions and
///limitations under the License.
///***********************************************************************

using System;
using System.Windows.Forms;

namespace DiskOperationSystem
{
    public partial class FormInputDirName : Form
    {
        public FormInputDirName()
        {
            InitializeComponent();
        }

        private void buttonOK_Click(object sender, EventArgs e)
        {
            this.Text = textBoxInput.Text;
            this.Close();
        }

        /// <summary>
        /// 将对话框里的提示内容(即label的Text)替换成s的字符串
        /// </summary>
        /// <param name="s">指定替换内容的字符串</param>
        public void changeLabelName(string s)
        {
            this.label1.Text = s;
        }

    }
}


text:
<template name="afInputNumber">
  <input type="number" value="{{this.value}}" {{this.atts}}/>
</template>


text:
/*
 *   IRC - Internet Relay Chat, src/modules/m_part.c
 *   (C) 2005 The UnrealIRCd Team
 *
 *   See file AUTHORS in IRC package for additional names of
 *   the programmers.
 *
 *   This program is free software; you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation; either version 1, or (at your option)
 *   any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with this program; if not, write to the Free Software
 *   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 */
#include "config.h"
#include "struct.h"
#include "common.h"
#include "sys.h"
#include "numeric.h"
#include "msg.h"
#include "proto.h"
#include "channel.h"
#include <time.h>
#include <sys/stat.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifdef _WIN32
#include <io.h>
#endif
#include <fcntl.h>
#include "h.h"
#ifdef STRIPBADWORDS
#include "badwords.h"
#endif
#ifdef _WIN32
#include "version.h"
#endif

DLLFUNC CMD_FUNC(m_part);

#define MSG_PART 	"PART"
#define TOK_PART 	"D"

ModuleHeader MOD_HEADER(m_part)
  = {
	"m_part",
	"$Id$",
	"command /part",
	"3.2-b8-1",
	NULL
    };

DLLFUNC int MOD_INIT(m_part)(ModuleInfo *modinfo)
{
	CommandAdd(modinfo->handle, MSG_PART, TOK_PART, m_part, 2, M_USER);
	MARK_AS_OFFICIAL_MODULE(modinfo);
	return MOD_SUCCESS;
}

DLLFUNC int MOD_LOAD(m_part)(int module_load)
{
	return MOD_SUCCESS;
}

DLLFUNC int MOD_UNLOAD(m_part)(int module_unload)
{
	return MOD_SUCCESS;
}

/*
** m_part
**	parv[0] = sender prefix
**	parv[1] = channel
**	parv[2] = comment (added by Lefler)
*/
DLLFUNC CMD_FUNC(m_part)
{
	aChannel *chptr;
	Membership *lp;
	char *p = NULL, *name;
	char *commentx = (parc > 2 && parv[2]) ? parv[2] : NULL;
	char *comment;
	int n;

	if (parc < 2 || parv[1][0] == '\0')
	{
		sendto_one(sptr, err_str(ERR_NEEDMOREPARAMS),
		    me.name, parv[0], "PART");
		return 0;
	}

	if (MyClient(sptr))
	{
		if (IsShunned(sptr))
			commentx = NULL;
		if (STATIC_PART)
		{
			if (!strcasecmp(STATIC_PART, "yes") || !strcmp(STATIC_PART, "1"))
				commentx = NULL;
			else if (!strcasecmp(STATIC_PART, "no") || !strcmp(STATIC_PART, "0"))
				; /* keep original reason */
			else
				commentx = STATIC_PART;
		}
		if (commentx)
		{
			n = dospamfilter(sptr, commentx, SPAMF_PART, parv[1], 0, NULL);
			if (n == FLUSH_BUFFER)
				return n;
			if (n < 0)
				commentx = NULL;
		}
	}

	for (; (name = strtoken(&p, parv[1], ",")); parv[1] = NULL)
	{
		chptr = get_channel(sptr, name, 0);
		if (!chptr)
		{
			sendto_one(sptr, err_str(ERR_NOSUCHCHANNEL),
			    me.name, parv[0], name);
			continue;
		}
		if (check_channelmask(sptr, cptr, name))
			continue;

		/* 'commentx' is the general part msg, but it can be changed
		 * per-channel (eg some chans block badwords, strip colors, etc)
		 * so we copy it to 'comment' and use that in this for loop :)
		 */
		comment = commentx;

		if (!(lp = find_membership_link(sptr->user->channel, chptr)))
		{
			/* Normal to get get when our client did a kick
			   ** for a remote client (who sends back a PART),
			   ** so check for remote client or not --Run
			 */
			if (MyClient(sptr))
				sendto_one(sptr,
				    err_str(ERR_NOTONCHANNEL), me.name,
				    parv[0], name);
			continue;
		}

		if (!IsAnOper(sptr) && !is_chanownprotop(sptr, chptr)) {
#ifdef STRIPBADWORDS
			int blocked = 0;
#endif
			/* Banned? No comment allowed ;) */
			if (comment && is_banned(sptr, chptr, BANCHK_MSG))
				comment = NULL;
			/* And other things... */
			if ((chptr->mode.mode & MODE_NOCOLOR) && comment) {
				if (strchr((char *)comment, 3) || strchr((char *)comment, 27)) {
					comment = NULL;
				}
			}
			if ((chptr->mode.mode & MODE_MODERATED) && comment &&
				 !has_voice(sptr, chptr) && !is_halfop(sptr, chptr))
			{
				comment = NULL;
			}
			if ((chptr->mode.mode & MODE_STRIP) && comment) {
				comment = (char *)StripColors(comment);
			}
#ifdef STRIPBADWORDS
 #ifdef STRIPBADWORDS_CHAN_ALWAYS
			if (comment)
			{
				comment = (char *)stripbadwords_channel(comment, &blocked);
			}
 #else
			if ((chptr->mode.extmode & EXTMODE_STRIPBADWORDS) && comment) {
				comment = (char *)stripbadwords_channel(comment, &blocked);
			}
 #endif
#endif

		}
		/* +M and not logged in to services? */
		if ((chptr->mode.mode & MODE_MODREG) && !IsLoggedIn(sptr) && !IsAnOper(sptr))
			comment = NULL;

		if (MyConnect(sptr))
		{
			Hook *tmphook;
			for (tmphook = Hooks[HOOKTYPE_PRE_LOCAL_PART]; tmphook; tmphook = tmphook->next) {
				comment = (*(tmphook->func.pcharfunc))(sptr, chptr, comment);
				if (!comment)
					break;
			}
		}

		/* Send to other servers... */
		if (!comment)
			sendto_serv_butone_token(cptr, parv[0],
			    MSG_PART, TOK_PART, "%s", chptr->chname);
		else
			sendto_serv_butone_token(cptr, parv[0],
			    MSG_PART, TOK_PART, "%s :%s", chptr->chname,
			    comment);

		if (1)
		{
			if ((chptr->mode.mode & MODE_AUDITORIUM) && !is_chanownprotop(sptr, chptr))
			{
				if (!comment)
				{
					sendto_chanops_butone(NULL,
					    chptr, ":%s!%s@%s PART %s",
					    sptr->name, sptr->user->username, GetHost(sptr),
					    chptr->chname);
					if (!is_chan_op(sptr, chptr) && MyClient(sptr))
						sendto_one(sptr, ":%s!%s@%s PART %s",
						    sptr->name, sptr->user->username, GetHost(sptr), chptr->chname);
				}
				else
				{
					sendto_chanops_butone(NULL,
					    chptr,
					    ":%s!%s@%s PART %s %s",
					    sptr->name,
					    sptr->user->username,
					    GetHost(sptr),
					    chptr->chname, comment);
					if (!is_chan_op(cptr, chptr) && MyClient(sptr))
						sendto_one(sptr,
						    ":%s!%s@%s PART %s %s",
						    sptr->name, sptr->user->username, GetHost(sptr),
						    chptr->chname, comment);
				}
			}
			else
			{

				if (!comment)

					sendto_channel_butserv(chptr,
					    sptr, PARTFMT, parv[0],
					    chptr->chname);
				else
					sendto_channel_butserv(chptr,
					    sptr, PARTFMT2, parv[0],
					    chptr->chname, comment);
			}
			if (MyClient(sptr))
				RunHook4(HOOKTYPE_LOCAL_PART, cptr, sptr, chptr, comment);
			else
				RunHook4(HOOKTYPE_REMOTE_PART, cptr, sptr, chptr, comment);

			remove_user_from_channel(sptr, chptr);
		}
	}
	return 0;
}


text:
export const skins = `
<Layout cols={5} gap={0} justifyItems="center" alignItems="center">
  <Box padding={1} backgroundColor="D80">
    <IconButton>
      <Icons.More />
    </IconButton>
  </Box>
  <IconButton skin="inverted">
    <Icons.More />
  </IconButton>
  <Box padding={1} backgroundColor="D10">
    <IconButton skin="light">
      <Icons.More />
    </IconButton>
  </Box>
  <IconButton skin="transparent">
      <Icons.More />
  </IconButton>
  <Box padding={1} backgroundColor="D80">
    <IconButton skin="premium">
      <Icons.More />
    </IconButton>
  </Box>
</Layout>
`;

export const priority = `
<Layout cols={5} gap={0} justifyItems="center">
  <Box padding={1} backgroundColor="D80">
    <IconButton priority="secondary">
      <Icons.X />
    </IconButton>
    <IconButton priority="primary">
      <Icons.Check />
    </IconButton>
  </Box>
  <Box padding={1}>
    <IconButton priority="secondary" skin="inverted">
      <Icons.X />
    </IconButton>
    <IconButton priority="primary" >
      <Icons.Check />
    </IconButton>
  </Box>
  <Box padding={1} backgroundColor="D10">
    <IconButton priority="secondary" skin="light">
      <Icons.X />
    </IconButton>
    <IconButton priority="primary" skin="light">
      <Icons.Check />
    </IconButton>
  </Box>
  <Box padding={1} backgroundColor="B10">
    <IconButton priority="secondary" skin="transparent">
      <Icons.X />
    </IconButton>
    <IconButton priority="primary" skin="transparent">
      <Icons.Check />
    </IconButton>
  </Box>
    <Box padding={1} backgroundColor="D80">
    <IconButton priority="secondary" skin="premium">
      <Icons.X />
    </IconButton>
    <IconButton priority="primary" skin="premium">
      <Icons.Check />
    </IconButton>
  </Box>
</Layout>
`;

export const size = `
<Layout cols={4} gap={0} justifyItems="center">
  <IconButton size="tiny">
    <Icons.MoreSmall />
  </IconButton>
  <IconButton size="small">
    <Icons.MoreSmall />
  </IconButton>
  <IconButton>
    <Icons.More />
  </IconButton>
  <IconButton size="large">
    <Icons.More />
  </IconButton>
</Layout>
`;

export const disabled = `
<Layout cols={2} gap={0} justifyItems="center">
  <IconButton>
    <Icons.More />
  </IconButton>
  <IconButton disabled>
    <Icons.More />
  </IconButton>
</Layout>
`;

export const custom = `
<Layout cols={3} gap={0} justifyItems="center">
  <Box direction="vertical" align="center">

An <a/> tag

    <IconButton as="a" href="https://www.wix.com" target="_blank" skin="transparent"><Icons.More /></IconButton>
  </Box>
  <Box direction="vertical" align="center">

A react router <Link/> tag

    <IconButton as={Link} skin="premium" to="/home" skin="transparent"><Icons.More /></IconButton>
  </Box>
  <Box direction="vertical" align="center">

A native <button/> tag

    <IconButton as="button" onClick={() => alert('yay')} skin="transparent"><Icons.More /></IconButton>
  </Box>
</Layout>
`;


text:
{-# LANGUAGE TypeApplications #-}
module ProjectEuler.Problem37
  ( problem
  ) where

import Data.List
import Math.NumberTheory.Primes.Testing (isPrime)
import Petbox

import ProjectEuler.Types

problem :: Problem
problem = pureProblem 37 Solved result

isTruncatable :: Int -> Bool
isTruncatable x =
    all (isPrime . fromIntegral @Int) $ possibleNumLeft <> possibleNumRight
  where
    digitsX = intToDigits x
    possibleNumLeft =
      -- tails [x,y,z] = [[x,y,z],[y,z],[z],[]],
      -- therefore we want to get rid of first and last element of it.
      digitsToInt <$> init (tail (tails digitsX))
    possibleNumRight =
      -- inits [x,y,z] = [[],[x],[x,y],[x,y,z]],
      -- same story, but just need to get rid of the first element.
      digitsToInt <$> tail (inits digitsX)

result :: Int
result = sum $ take 11 $ filter isTruncatable searchSpace
  where
    searchSpace = dropWhile (<=7) primes


text:
public class Revision_user {

	private int id_revision;
	private double peso_revision;
	private int altura_revision;
	private double imc_revision;
	private String fecha_revision;

	public int getId_revision() {
		return id_revision;
	}
	public void setId_revision(int id_revision) {
		this.id_revision = id_revision;
	}
	public double getPeso_revision() {
		return peso_revision;
	}
	public void setPeso_revision(double peso_revision) {
		this.peso_revision = peso_revision;
	}
	public int getAltura_revision() {
		return altura_revision;
	}
	public void setAltura_revision(int altura_revision) {
		this.altura_revision = altura_revision;
	}
	public double getImc_revision() {
		return imc_revision;
	}
	public void setImc_revision(double imc_revision) {
		this.imc_revision = imc_revision;
	}
	public String getFecha_revision() {
		return fecha_revision;
	}
	public void setFecha_revision(String fecha_revision) {
		this.fecha_revision = fecha_revision;
	}

}


text:
package org.jboss.weld.tests.disposer.withStaticProducer;

import javax.inject.Qualifier;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

@Target({ TYPE, METHOD, PARAMETER, FIELD })
@Retention(RUNTIME)
@Documented
@Qualifier
public @interface StaticProducer {

}


text:
using System;
using PropertyChanged;
using FreshMvvm;
using Xamarin.Forms;
using System.Collections.ObjectModel;
using System.Windows.Input;
using System.Collections.Generic;

namespace FreshMVVMSample
{
	[ImplementPropertyChanged]
	public class CommentListPageModel : BasePageModel
	{
		IActivityService _activityService;

		public CommentListPageModel (IActivityService activityService)
		{
			_activityService = activityService;
			Title = "Comments";
		}

		public Activity Activity { get; set; }

		public override void Init (object initData)
		{
			if (initData != null) {
				Activity = (Activity)initData;
			}
		}

		public Command CloseCommand {
			get {
				return new Command (() => {
					//_dataService.UpdateContact (Contact);
					var user3 = new User { Id = 3, Name = "Bill Lott", Email = "bill@somewhere.com" };
					Activity.Comments.Add(new Comment {Id=101, User=user3, Body = "Just added this comment!" });

					CoreMethods.PopPageModel (Activity, true);
				}
				);
			}
		}
	}
}


text:
/*\
title: submodule/a.js
type: application/javascript
module-type: library

Relative test A

\*/

exports.foo = require('./b').foo;


text:
<?php
namespace dvizh\shop\assets;

use yii\web\AssetBundle;

class ModificationConstructAsset extends AssetBundle
{
    public $depends = [
        'yii\web\JqueryAsset',
    ];

    public $js = [
        'js/modification-construct.js',
    ];

    public $css = [

    ];

    public function init()
    {
        $this->sourcePath = __DIR__ . '/../web';
        parent::init();
    }

}


text:
<?php
/**
 * @version 0.0.0.1
 */

namespace common\models;

use librarys\models\BaseModel;
use yii\db\mssql\PDO;

/**
 * 资讯文章
 * @author gaoqing
 */
class Article extends BaseModel
{
    public static function getDb()
    {
        return \Yii::$app->db_v2;
    }

    public static function tableName()
    {
        return 'article';
    }

    //============================ 2015-12-11: 新增 【热搜】、【专题】部分 Start ==========================//
    public function List_ArticleByIds($articleids=array()){
        if(count($articleids)==0){
            return false;
        }
        $ids = implode(',', $articleids);
        $sql = "select articleid as id,title,url,description,inputtime from article where articleid in ($ids) order by articleid desc";
        $result = self::getDb()->createCommand($sql)->queryAll(PDO::FETCH_ASSOC);
        return $result;
    }

    public function List_Articles($where = '1', $order = '', $count = '', $offset = '') {
        $sql = 'SELECT a.* FROM article a Left JOIN article_detail ad on a.articleid=ad.articleid where ' . $where ;
        $sql .= ' order by ' . $order;
        if(!empty($count)){
            $sql.= " limit ".$offset.",".$count;
        }
        $db = self::getDb();
        $result = $db->createCommand($sql)->queryAll(PDO::FETCH_ASSOC);
        return $result;
    }

}


text:
NSString *const kNetworkPage = @"page";
NSString *const kNetworkPageSize = @"pageSize";

@interface HZNetworkConfig ()

@property(nonatomic, copy) NSMutableDictionary *headerFields;

@end

@implementation HZNetworkConfig
singleton_m(Config)

- (instancetype)init
{
    self = [super init];
    if (self) {
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            _headerFields = [NSMutableDictionary dictionary];
            _SSLPinningMode = HZSSLPinningModeNone;
            _allowInvalidCertificates = NO;
        });
    }
    return self;
}

- (void)setupBaseURL:(NSString *)baseURL
           userAgent:(NSString *)userAgent
{
    [self setupBaseURL:baseURL codeKeyPath:nil msgKeyPath:nil userAgent:userAgent rightCode:NSNotFound];
}

-  (void)setupBaseURL:(NSString *)baseURL
          codeKeyPath:(NSString *)codeKeyPath
           msgKeyPath:(NSString *)msgKeyPath
            userAgent:(NSString *)userAgent
            rightCode:(NSUInteger)rightCode;
{
    _baseURL = baseURL;
    _codeKeyPath = codeKeyPath;
    _msgKeyPath = msgKeyPath;
    _rightCode = rightCode;
    _userAgent = userAgent;

    if (userAgent.isNoEmpty)
        [self.headerFields setObject:userAgent forKey:@"User-Agent"];
}

- (void)addDefaultHeaderFields:(NSDictionary *)headerFields
{
    if (headerFields.isNoEmpty)
    [self.headerFields addEntriesFromDictionary:headerFields];
}

- (NSDictionary *)defaultHeaderFields
{
    return self.headerFields;
}

- (BOOL)reachable
{
    return !([AFNetworkReachabilityManager sharedManager].networkReachabilityStatus == AFNetworkReachabilityStatusNotReachable);
}

@end


text:
'use strict';
exports.name = 'foo'
exports.description = 'Example Foo Action'
exports.run = function(apx,req,res,next){
  res.set('status','alive')
  next()
  //fire the hello job
  apx.jobs.create('hello',{title: 'Needs to say hi'})
    .delay(5000)
    .priority('low')
    .save()
}


text:
var gulp = require('gulp');
// var iconfont = require('gulp-iconfont');
var iconfont = require('./gulp-fontforge');
var iconfontview = require('./gulp-iconfont-view');
var del = require('del');
var _ = require('lodash');

var fontName = 'iconfonts';
var generate_folder = "gen/";

gulp.task('default', function(){
  del.sync(generate_folder);
  // gulp.src(['svg-icons/*.svg'])
  //   .pipe(iconfont({
  //     formats: ['svg', 'ttf', 'eot', 'woff', 'woff2'],
  //     normalize: true,
  //     startUnicode: 0xF101,
  //     fontName: fontName
  //   }))
  //   .on('glyphs', function(glyphs, options) {
  //       var glyphsMap = []
  //
  //       for(var i=0;i<glyphs.length; i++){
  //         if(glyphs[i]&&glyphs[i].name&&glyphs[i].unicode[0]&&glyphs[i].unicode[0].charCodeAt(0)){
  //           var glyph = {};
  //           glyph.name = _.kebabCase(glyphs[i].name);
  //           glyph.unicode = glyphs[i].unicode[0].charCodeAt(0).toString(16).toUpperCase();
  //           glyphsMap.push(glyph);
  //         }
  //   		}
  //
  //       gulp.src(['templates/**/*'])
  //         .pipe(iconfontview({
  //           glyphsMap: glyphsMap,
  //           fontName: options.fontName
  //         }))
  //         .pipe(gulp.dest(generate_folder))/
  //     })
  //   .pipe(gulp.dest(generate_folder+"icon-font/fonts/"));

  gulp.src(['svg-icons/*.svg'])
    .pipe(iconfont({
      font: "iconfonts",
      dest: generate_folder+"icon-font/fonts/"
    }))
    .on('glyphs', function(glyphs, options) {
      var glyphsMap = [];
      for(let name in glyphs){
        if(glyphs.hasOwnProperty(name)){
          let glyph = {};
          glyph.name = name;
          glyph.unicode = glyphs[name].text;
          glyphsMap.push(glyph);
        }
      }
      gulp.src(['templates/**/*'])
        .pipe(iconfontview({
          glyphsMap: glyphsMap,
          fontName: "iconfonts"
        }))
        .pipe(gulp.dest(generate_folder))
    })
    .pipe(gulp.dest(generate_folder+"icon-font/fonts/"));
});


text:
use strict;
use warnings;

# Modules.
use Error::Pure::HTTP::AllError qw(err);

# Error.
err "This is a fatal error.", "name", "value";

# Output like this:
# Content-type: text/plain
#
# ERROR: This is a fatal error.
# name: value
# main  err  ./script.pl  12


text:
using System;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using Newtonsoft.Json.Linq;
using System.IO;

namespace Hackathon._1Script.CleanupWorker
{
    class Program
    {
        static void Main(string[] args)
        {
            RunAsync().Wait();
        }

        private static async Task RunAsync()
        {
            string certPath = Path.Combine(Path.GetDirectoryName(new Uri(typeof(Program).Assembly.CodeBase, UriKind.Absolute).LocalPath), "..", "..", "..", "1script.pfx");

            const string clientId = "fa24eac7-0684-4964-ab13-9d4ff772e3d1";
            X509Certificate2 cert = new X509Certificate2(
                certPath,
                "No password");
            ClientAssertionCertificate certCred = new ClientAssertionCertificate(clientId, cert);
            AuthenticationContext authContext = new AuthenticationContext("https://login.windows.net/b550583b-bc56-47d4-b547-6982b363a8b0/");
            AuthenticationResult authResult = await authContext.AcquireTokenAsync("https://management.azure.com/", certCred);
            string token = authResult.AccessToken;

            HttpClient client = new HttpClient();
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
            string location = "https://management.azure.com/subscriptions/c09ce800-abd2-48c5-8565-dc51435d90ec/resourceGroups/1script/providers/Microsoft.Web/sites?api-version=2016-08-01";
            HttpResponseMessage responseMessage = await client.GetAsync(location);
            string responseText = await responseMessage.Content.ReadAsStringAsync().ConfigureAwait(false);
            JObject outer = JObject.Parse(responseText);
            JArray items = (JArray)outer["value"];

            foreach (JObject site in items.OfType<JObject>())
            {
                string name = site["name"].ToString();

                if (string.Equals(name, "1script", StringComparison.OrdinalIgnoreCase))
                {
                    continue;
                }

                string modified = site["properties"]["lastModifiedTimeUtc"].ToString();
                DateTime created = DateTime.Parse(modified, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal);

                if (created < DateTime.Now.AddDays(-1))
                {
                    location = $"https://management.azure.com/subscriptions/c09ce800-abd2-48c5-8565-dc51435d90ec/resourceGroups/1script/providers/Microsoft.Web/sites/{name}?api-version=2016-08-01";
                    responseMessage = await client.DeleteAsync(location);
                }
            }
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Security.Cryptography.Asn1;

namespace System.Security.Cryptography.Pkcs.Asn1
{
    [StructLayout(LayoutKind.Sequential)]
    internal partial struct Rfc3161TimeStampReq
    {
        private static byte[] s_defaultCertReq = { 0x01, 0x01, 0x00 };

        internal int Version;
        internal System.Security.Cryptography.Pkcs.Asn1.MessageImprint MessageImprint;
        internal Oid ReqPolicy;
        internal ReadOnlyMemory<byte>? Nonce;
        internal bool CertReq;
        internal System.Security.Cryptography.Asn1.X509ExtensionAsn[] Extensions;

#if DEBUG
        static Rfc3161TimeStampReq()
        {
            Rfc3161TimeStampReq decoded = default;
            AsnReader reader;

            reader = new AsnReader(s_defaultCertReq, AsnEncodingRules.DER);
            decoded.CertReq = reader.ReadBoolean();
            reader.ThrowIfNotEmpty();
        }
#endif

        internal void Encode(AsnWriter writer)
        {
            Encode(writer, Asn1Tag.Sequence);
        }

        internal void Encode(AsnWriter writer, Asn1Tag tag)
        {
            writer.PushSequence(tag);

            writer.WriteInteger(Version);
            MessageImprint.Encode(writer);

            if (ReqPolicy != null)
            {
                writer.WriteObjectIdentifier(ReqPolicy);
            }

            if (Nonce.HasValue)
            {
                writer.WriteInteger(Nonce.Value.Span);
            }

            // DEFAULT value handler for CertReq.
            {
                using (AsnWriter tmp = new AsnWriter(AsnEncodingRules.DER))
                {
                    tmp.WriteBoolean(CertReq);
                    ReadOnlySpan<byte> encoded = tmp.EncodeAsSpan();

                    if (!encoded.SequenceEqual(s_defaultCertReq))
                    {
                        writer.WriteEncodedValue(encoded.ToArray());
                    }
                }
            }

            if (Extensions != null)
            {

                writer.PushSequence(new Asn1Tag(TagClass.ContextSpecific, 0));
                for (int i = 0; i < Extensions.Length; i++)
                {
                    Extensions[i].Encode(writer);
                }
                writer.PopSequence(new Asn1Tag(TagClass.ContextSpecific, 0));

            }

            writer.PopSequence(tag);
        }

        internal static Rfc3161TimeStampReq Decode(ReadOnlyMemory<byte> encoded, AsnEncodingRules ruleSet)
        {
            return Decode(Asn1Tag.Sequence, encoded, ruleSet);
        }

        internal static Rfc3161TimeStampReq Decode(Asn1Tag expectedTag, ReadOnlyMemory<byte> encoded, AsnEncodingRules ruleSet)
        {
            AsnReader reader = new AsnReader(encoded, ruleSet);

            Decode(reader, expectedTag, out Rfc3161TimeStampReq decoded);
            reader.ThrowIfNotEmpty();
            return decoded;
        }

        internal static void Decode(AsnReader reader, out Rfc3161TimeStampReq decoded)
        {
            if (reader == null)
                throw new ArgumentNullException(nameof(reader));

            Decode(reader, Asn1Tag.Sequence, out decoded);
        }

        internal static void Decode(AsnReader reader, Asn1Tag expectedTag, out Rfc3161TimeStampReq decoded)
        {
            if (reader == null)
                throw new ArgumentNullException(nameof(reader));

            decoded = default;
            AsnReader sequenceReader = reader.ReadSequence(expectedTag);
            AsnReader defaultReader;
            AsnReader collectionReader;

            if (!sequenceReader.TryReadInt32(out decoded.Version))
            {
                sequenceReader.ThrowIfNotEmpty();
            }

            System.Security.Cryptography.Pkcs.Asn1.MessageImprint.Decode(sequenceReader, out decoded.MessageImprint);

            if (sequenceReader.HasData && sequenceReader.PeekTag().HasSameClassAndValue(Asn1Tag.ObjectIdentifier))
            {
                decoded.ReqPolicy = sequenceReader.ReadObjectIdentifier();
            }

            if (sequenceReader.HasData && sequenceReader.PeekTag().HasSameClassAndValue(Asn1Tag.Integer))
            {
                decoded.Nonce = sequenceReader.GetIntegerBytes();
            }

            if (sequenceReader.HasData && sequenceReader.PeekTag().HasSameClassAndValue(Asn1Tag.Boolean))
            {
                decoded.CertReq = sequenceReader.ReadBoolean();
            }
            else
            {
                defaultReader = new AsnReader(s_defaultCertReq, AsnEncodingRules.DER);
                decoded.CertReq = defaultReader.ReadBoolean();
            }

            if (sequenceReader.HasData && sequenceReader.PeekTag().HasSameClassAndValue(new Asn1Tag(TagClass.ContextSpecific, 0)))
            {

                // Decode SEQUENCE OF for Extensions
                {
                    collectionReader = sequenceReader.ReadSequence(new Asn1Tag(TagClass.ContextSpecific, 0));
                    var tmpList = new List<System.Security.Cryptography.Asn1.X509ExtensionAsn>();
                    System.Security.Cryptography.Asn1.X509ExtensionAsn tmpItem;

                    while (collectionReader.HasData)
                    {
                        System.Security.Cryptography.Asn1.X509ExtensionAsn.Decode(collectionReader, out tmpItem);
                        tmpList.Add(tmpItem);
                    }

                    decoded.Extensions = tmpList.ToArray();
                }

            }

            sequenceReader.ThrowIfNotEmpty();
        }
    }
}


text:
{{ define "styles" }}
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/styles/default.min.css"/>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/styles/tomorrow.min.css"/>
{{ end }}

{{ define "scripts" }}

{{ end }}

{{ define "header" }}
    {{ partial "header-visible" . }}
{{ end }}

{{ define "main" }}

{{ .Title }}

                        Ben Collins

                    {{ dateFormat "January 2, 2006" .Date }}

                {{ .Content }}

    {{ template "_internal/disqus.html" . }}

{{ end }}


text:
package org.apache.commons.compress.archivers;

import static java.nio.charset.StandardCharsets.UTF_8;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.channels.Channels;
import java.nio.channels.SeekableByteChannel;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;

import org.apache.commons.compress.AbstractTestCase;
import org.apache.commons.compress.archivers.zip.Zip64Mode;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntryPredicate;
import org.apache.commons.compress.archivers.zip.ZipArchiveInputStream;
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
import org.apache.commons.compress.archivers.zip.ZipFile;
import org.apache.commons.compress.archivers.zip.ZipMethod;
import org.apache.commons.compress.archivers.zip.ZipSplitReadOnlySeekableByteChannel;
import org.apache.commons.compress.utils.IOUtils;
import org.apache.commons.compress.utils.InputStreamStatistics;
import org.apache.commons.compress.utils.SeekableInMemoryByteChannel;
import org.junit.Assert;
import org.junit.jupiter.api.Test;

public final class ZipTestCase extends AbstractTestCase {

    /**
     * Archives 2 files and unarchives it again. If the file length of result
     * and source is the same, it looks like the operations have worked
     * @throws Exception
     */
    @Test
    public void testZipArchiveCreation() throws Exception {
        // Archive
        final File output = new File(dir, "bla.zip");
        final File file1 = getFile("test1.xml");
        final File file2 = getFile("test2.xml");

        try (final OutputStream out = Files.newOutputStream(output.toPath())) {
            try (ArchiveOutputStream os = ArchiveStreamFactory.DEFAULT.createArchiveOutputStream("zip", out)) {
                os.putArchiveEntry(new ZipArchiveEntry("testdata/test1.xml"));
                try (final InputStream input = Files.newInputStream(file1.toPath())) {
                    IOUtils.copy(input, os);
                }
                os.closeArchiveEntry();

                os.putArchiveEntry(new ZipArchiveEntry("testdata/test2.xml"));
                try (final InputStream input = Files.newInputStream(file2.toPath())) {
                    IOUtils.copy(input, os);
                }
                os.closeArchiveEntry();
            }
        }

        // Unarchive the same
        final List<File> results = new ArrayList<>();

        try (final InputStream fileInputStream = Files.newInputStream(output.toPath())) {
            try (ArchiveInputStream archiveInputStream = ArchiveStreamFactory.DEFAULT.createArchiveInputStream("zip",
                fileInputStream)) {
                ZipArchiveEntry entry = null;
                while ((entry = (ZipArchiveEntry) archiveInputStream.getNextEntry()) != null) {
                    final File outfile = new File(resultDir.getCanonicalPath() + "/result/" + entry.getName());
                    outfile.getParentFile().mkdirs();
                    try (OutputStream o = Files.newOutputStream(outfile.toPath())) {
                        IOUtils.copy(archiveInputStream, o);
                    }
                    results.add(outfile);
                }
            }
        }

        assertEquals(results.size(), 2);
        File result = results.get(0);
        assertEquals(file1.length(), result.length());
        result = results.get(1);
        assertEquals(file2.length(), result.length());
    }

    /**
     * Archives 2 files and unarchives it again. If the file contents of result
     * and source is the same, it looks like the operations have worked
     * @throws Exception
     */
    @Test
    public void testZipArchiveCreationInMemory() throws Exception {
        final File file1 = getFile("test1.xml");
        final File file2 = getFile("test2.xml");
        final byte[] file1Contents = new byte[(int) file1.length()];
        final byte[] file2Contents = new byte[(int) file2.length()];
        IOUtils.read(file1, file1Contents);
        IOUtils.read(file2, file2Contents);
        final List<byte[]> results = new ArrayList<>();

        try (SeekableInMemoryByteChannel channel = new SeekableInMemoryByteChannel()) {
            try (ZipArchiveOutputStream os = new ZipArchiveOutputStream(channel)) {
                os.putArchiveEntry(new ZipArchiveEntry("testdata/test1.xml"));
                os.write(file1Contents);
                os.closeArchiveEntry();

                os.putArchiveEntry(new ZipArchiveEntry("testdata/test2.xml"));
                os.write(file2Contents);
                os.closeArchiveEntry();
            }

            // Unarchive the same
            try (ArchiveInputStream inputStream = ArchiveStreamFactory.DEFAULT.createArchiveInputStream("zip",
                new ByteArrayInputStream(channel.array()))) {

                ZipArchiveEntry entry;
                while ((entry = (ZipArchiveEntry) inputStream.getNextEntry()) != null) {
                    final byte[] result = new byte[(int) entry.getSize()];
                    IOUtils.readFully(inputStream, result);
                    results.add(result);
                }
            }
        }
        assertArrayEquals(results.get(0), file1Contents);
        assertArrayEquals(results.get(1), file2Contents);
    }

    /**
     * Simple unarchive test. Asserts nothing.
     * @throws Exception
     */
    @Test
    public void testZipUnarchive() throws Exception {
        final File input = getFile("bla.zip");
        try (final InputStream is = Files.newInputStream(input.toPath());
                final ArchiveInputStream in = ArchiveStreamFactory.DEFAULT.createArchiveInputStream("zip", is)) {
            final ZipArchiveEntry entry = (ZipArchiveEntry) in.getNextEntry();
            try (final OutputStream out = Files.newOutputStream(new File(dir, entry.getName()).toPath())) {
                IOUtils.copy(in, out);
            }
        }
    }

    /**
     * Test case for
     * COMPRESS-208.
     */
    @Test
    public void testSkipsPK00Prefix() throws Exception {
        final File input = getFile("COMPRESS-208.zip");
        final ArrayList<String> al = new ArrayList<>();
        al.add("test1.xml");
        al.add("test2.xml");
        try (InputStream fis = Files.newInputStream(input.toPath())) {
            checkArchiveContent(new ZipArchiveInputStream(fis), al);
        }
    }

    /**
     * Test case for
     * COMPRESS-93.
     */
    @Test
    public void testTokenizationCompressionMethod() throws IOException {
        try (final ZipFile moby = new ZipFile(getFile("moby.zip"))) {
            final ZipArchiveEntry entry = moby.getEntry("README");
            assertEquals("method", ZipMethod.TOKENIZATION.getCode(), entry.getMethod());
            assertFalse(moby.canReadEntryData(entry));
        }
    }

    /**
     * Test case for being able to skip an entry in an
     * {@link ZipArchiveInputStream} even if the compression method of that
     * entry is unsupported.
     *
     * @see COMPRESS-93
     */
    @Test
    public void testSkipEntryWithUnsupportedCompressionMethod()
            throws IOException {
        try (ZipArchiveInputStream zip = new ZipArchiveInputStream(Files.newInputStream(getFile("moby.zip").toPath()))) {
            final ZipArchiveEntry entry = zip.getNextZipEntry();
            assertEquals("method", ZipMethod.TOKENIZATION.getCode(), entry.getMethod());
            assertEquals("README", entry.getName());
            assertFalse(zip.canReadEntryData(entry));
            try {
                assertNull(zip.getNextZipEntry());
            } catch (final IOException e) {
                e.printStackTrace();
                fail("COMPRESS-93: Unable to skip an unsupported zip entry");
            }
        }
    }

    /**
     * Checks if all entries from a nested archive can be read.
     * The archive: OSX_ArchiveWithNestedArchive.zip contains:
     * NestedArchiv.zip and test.xml3.
     *
     * The nested archive:  NestedArchive.zip contains test1.xml and test2.xml
     *
     * @throws Exception
     */
    @Test
    public void testListAllFilesWithNestedArchive() throws Exception {
        final File input = getFile("OSX_ArchiveWithNestedArchive.zip");

        final List<String> results = new ArrayList<>();
        final List<ZipException> expectedExceptions = new ArrayList<>();

        try (final InputStream fis = Files.newInputStream(input.toPath());
            ArchiveInputStream in = ArchiveStreamFactory.DEFAULT.createArchiveInputStream("zip", fis)) {

            ZipArchiveEntry entry = null;
            while ((entry = (ZipArchiveEntry) in.getNextEntry()) != null) {
                results.add(entry.getName());

                final ArchiveInputStream nestedIn = ArchiveStreamFactory.DEFAULT.createArchiveInputStream("zip", in);
                try {
                    ZipArchiveEntry nestedEntry = null;
                    while ((nestedEntry = (ZipArchiveEntry) nestedIn.getNextEntry()) != null) {
                        results.add(nestedEntry.getName());
                    }
                } catch (final ZipException ex) {
                    // expected since you cannot create a final ArchiveInputStream from test3.xml
                    expectedExceptions.add(ex);
                }
                // nested stream must not be closed here
            }
        }

        assertTrue(results.contains("NestedArchiv.zip"));
        assertTrue(results.contains("test1.xml"));
        assertTrue(results.contains("test2.xml"));
        assertTrue(results.contains("test3.xml"));
        assertEquals(1, expectedExceptions.size());
    }

    @Test
    public void testDirectoryEntryFromFile() throws Exception {
        final File[] tmp = createTempDirAndFile();
        File archive = null;
        ZipArchiveOutputStream zos = null;
        ZipFile zf = null;
        try {
            archive = File.createTempFile("test.", ".zip", tmp[0]);
            archive.deleteOnExit();
            zos = new ZipArchiveOutputStream(archive);
            final long beforeArchiveWrite = tmp[0].lastModified();
            final ZipArchiveEntry in = new ZipArchiveEntry(tmp[0], "foo");
            zos.putArchiveEntry(in);
            zos.closeArchiveEntry();
            zos.close();
            zos = null;
            zf = new ZipFile(archive);
            final ZipArchiveEntry out = zf.getEntry("foo/");
            assertNotNull(out);
            assertEquals("foo/", out.getName());
            assertEquals(0, out.getSize());
            // ZIP stores time with a granularity of 2 seconds
            assertEquals(beforeArchiveWrite / 2000,
                         out.getLastModifiedDate().getTime() / 2000);
            assertTrue(out.isDirectory());
        } finally {
            ZipFile.closeQuietly(zf);
            if (zos != null) {
                zos.close();
            }
            tryHardToDelete(archive);
            tryHardToDelete(tmp[1]);
            rmdir(tmp[0]);
        }
    }

    @Test
    public void testExplicitDirectoryEntry() throws Exception {
        final File[] tmp = createTempDirAndFile();
        File archive = null;
        ZipArchiveOutputStream zos = null;
        ZipFile zf = null;
        try {
            archive = File.createTempFile("test.", ".zip", tmp[0]);
            archive.deleteOnExit();
            zos = new ZipArchiveOutputStream(archive);
            final long beforeArchiveWrite = tmp[0].lastModified();
            final ZipArchiveEntry in = new ZipArchiveEntry("foo/");
            in.setTime(beforeArchiveWrite);
            zos.putArchiveEntry(in);
            zos.closeArchiveEntry();
            zos.close();
            zos = null;
            zf = new ZipFile(archive);
            final ZipArchiveEntry out = zf.getEntry("foo/");
            assertNotNull(out);
            assertEquals("foo/", out.getName());
            assertEquals(0, out.getSize());
            assertEquals(beforeArchiveWrite / 2000,
                         out.getLastModifiedDate().getTime() / 2000);
            assertTrue(out.isDirectory());
        } finally {
            ZipFile.closeQuietly(zf);
            if (zos != null) {
                zos.close();
            }
            tryHardToDelete(archive);
            tryHardToDelete(tmp[1]);
            rmdir(tmp[0]);
        }
    }
    final String first_payload = "ABBA";
    final String second_payload = "AAAAAAAAAAAA";
    final ZipArchiveEntryPredicate allFilesPredicate = zipArchiveEntry -> true;

    @Test
    public void testCopyRawEntriesFromFile()
        throws IOException {

        final File[] tmp = createTempDirAndFile();
        final File reference = createReferenceFile(tmp[0], Zip64Mode.Never, "expected.");

        final File file1 = File.createTempFile("src1.", ".zip", tmp[0]);
        try (final ZipArchiveOutputStream zos = new ZipArchiveOutputStream(file1)) {
            zos.setUseZip64(Zip64Mode.Never);
            createFirstEntry(zos).close();
        }

        final File file2 = File.createTempFile("src2.", ".zip", tmp[0]);
        try (final ZipArchiveOutputStream zos1 = new ZipArchiveOutputStream(file2)) {
            zos1.setUseZip64(Zip64Mode.Never);
            createSecondEntry(zos1).close();
        }

        try (final ZipFile zipFile1 = new ZipFile(file1); final ZipFile zipFile2 = new ZipFile(file2)) {
            final File fileResult = File.createTempFile("file-actual.", ".zip", tmp[0]);
            try (final ZipArchiveOutputStream zos2 = new ZipArchiveOutputStream(fileResult)) {
                zipFile1.copyRawEntries(zos2, allFilesPredicate);
                zipFile2.copyRawEntries(zos2, allFilesPredicate);
            }
            // copyRawEntries does not add superfluous zip64 header like regular zip output stream
            // does when using Zip64Mode.AsNeeded so all the source material has to be Zip64Mode.Never,
            // if exact binary equality is to be achieved
            assertSameFileContents(reference, fileResult);
        }
    }

    @Test
    public void testCopyRawZip64EntryFromFile()
            throws IOException {

        final File[] tmp = createTempDirAndFile();
        final File reference = File.createTempFile("z64reference.", ".zip", tmp[0]);
        try (final ZipArchiveOutputStream zos1 = new ZipArchiveOutputStream(reference)) {
            zos1.setUseZip64(Zip64Mode.Always);
            createFirstEntry(zos1);
        }

        final File file1 = File.createTempFile("zip64src.", ".zip", tmp[0]);
        try (final ZipArchiveOutputStream zos = new ZipArchiveOutputStream(file1)) {
            zos.setUseZip64(Zip64Mode.Always);
            createFirstEntry(zos).close();
        }

        final File fileResult = File.createTempFile("file-actual.", ".zip", tmp[0]);
        try (final ZipFile zipFile1 = new ZipFile(file1)) {
            try (final ZipArchiveOutputStream zos2 = new ZipArchiveOutputStream(fileResult)) {
                zos2.setUseZip64(Zip64Mode.Always);
                zipFile1.copyRawEntries(zos2, allFilesPredicate);
            }
            assertSameFileContents(reference, fileResult);
        }
    }

    @Test
    public void testUnixModeInAddRaw() throws IOException {

        final File[] tmp = createTempDirAndFile();

        final File file1 = File.createTempFile("unixModeBits.", ".zip", tmp[0]);
        try (final ZipArchiveOutputStream zos = new ZipArchiveOutputStream(file1)) {

            final ZipArchiveEntry archiveEntry = new ZipArchiveEntry("fred");
            archiveEntry.setUnixMode(0664);
            archiveEntry.setMethod(ZipEntry.STORED);
            archiveEntry.setSize(3);
            archiveEntry.setCompressedSize(3);
            zos.addRawArchiveEntry(archiveEntry, new ByteArrayInputStream("fud".getBytes()));
        }

        try (final ZipFile zf1 = new ZipFile(file1)) {
            final ZipArchiveEntry fred = zf1.getEntry("fred");
            assertEquals(0664, fred.getUnixMode());
        }
    }

    private File createReferenceFile(final File directory, final Zip64Mode zipMode, final String prefix)
            throws IOException {
        final File reference = File.createTempFile(prefix, ".zip", directory);
        try (final ZipArchiveOutputStream zos = new ZipArchiveOutputStream(reference)) {
            zos.setUseZip64(zipMode);
            createFirstEntry(zos);
            createSecondEntry(zos);
        }
        return reference;
    }

    private ZipArchiveOutputStream createFirstEntry(final ZipArchiveOutputStream zos) throws IOException {
        createArchiveEntry(first_payload, zos, "file1.txt");
        return zos;
    }

    private ZipArchiveOutputStream createSecondEntry(final ZipArchiveOutputStream zos) throws IOException {
        createArchiveEntry(second_payload, zos, "file2.txt");
        return zos;
    }

    private void assertSameFileContents(final File expectedFile, final File actualFile) throws IOException {
        final int size = (int) Math.max(expectedFile.length(), actualFile.length());
        try (final ZipFile expected = new ZipFile(expectedFile); final ZipFile actual = new ZipFile(actualFile)) {
            final byte[] expectedBuf = new byte[size];
            final byte[] actualBuf = new byte[size];

            final Enumeration<ZipArchiveEntry> actualInOrder = actual.getEntriesInPhysicalOrder();
            final Enumeration<ZipArchiveEntry> expectedInOrder = expected.getEntriesInPhysicalOrder();

            while (actualInOrder.hasMoreElements()) {
                final ZipArchiveEntry actualElement = actualInOrder.nextElement();
                final ZipArchiveEntry expectedElement = expectedInOrder.nextElement();
                assertEquals(expectedElement.getName(), actualElement.getName());
                // Don't compare timestamps since they may vary;
                // there's no support for stubbed out clock (TimeSource) in ZipArchiveOutputStream
                assertEquals(expectedElement.getMethod(), actualElement.getMethod());
                assertEquals(expectedElement.getGeneralPurposeBit(), actualElement.getGeneralPurposeBit());
                assertEquals(expectedElement.getCrc(), actualElement.getCrc());
                assertEquals(expectedElement.getCompressedSize(), actualElement.getCompressedSize());
                assertEquals(expectedElement.getSize(), actualElement.getSize());
                assertEquals(expectedElement.getExternalAttributes(), actualElement.getExternalAttributes());
                assertEquals(expectedElement.getInternalAttributes(), actualElement.getInternalAttributes());

                try (final InputStream actualIs = actual.getInputStream(actualElement);
                    final InputStream expectedIs = expected.getInputStream(expectedElement)) {
                    IOUtils.readFully(expectedIs, expectedBuf);
                    IOUtils.readFully(actualIs, actualBuf);
                }
                Assert.assertArrayEquals(expectedBuf, actualBuf); // Buffers are larger than payload. dont care
            }

        }
    }

    private void createArchiveEntry(final String payload, final ZipArchiveOutputStream zos, final String name)
            throws IOException {
        final ZipArchiveEntry in = new ZipArchiveEntry(name);
        zos.putArchiveEntry(in);

        zos.write(payload.getBytes());
        zos.closeArchiveEntry();
    }

    @Test
    public void testFileEntryFromFile() throws Exception {
        final File[] tmp = createTempDirAndFile();
        File archive = null;
        ZipArchiveOutputStream zos = null;
        ZipFile zf = null;
        InputStream fis = null;
        final File tmpDir = tmp[0];
        final File tmpFile = tmp[1];
        try {
            archive = File.createTempFile("test.", ".zip", tmpDir);
            archive.deleteOnExit();
            zos = new ZipArchiveOutputStream(archive);
            final ZipArchiveEntry in = new ZipArchiveEntry(tmpFile, "foo");
            zos.putArchiveEntry(in);
            final byte[] b = new byte[(int) tmpFile.length()];
            fis = Files.newInputStream(tmpFile.toPath());
            while (fis.read(b) > 0) {
                zos.write(b);
            }
            fis.close();
            fis = null;
            zos.closeArchiveEntry();
            zos.close();
            zos = null;
            zf = new ZipFile(archive);
            final ZipArchiveEntry out = zf.getEntry("foo");
            assertNotNull(out);
            assertEquals("foo", out.getName());
            assertEquals(tmpFile.length(), out.getSize());
            assertEquals(tmpFile.lastModified() / 2000,
                         out.getLastModifiedDate().getTime() / 2000);
            assertFalse(out.isDirectory());
        } finally {
            ZipFile.closeQuietly(zf);
            if (zos != null) {
                zos.close();
            }
            tryHardToDelete(archive);
            if (fis != null) {
                fis.close();
            }
            tryHardToDelete(tmpFile);
            rmdir(tmpDir);
        }
    }

    @Test
    public void testZipArchiveEntryNewFromPath() throws Exception {
        final File[] tmp = createTempDirAndFile();
        File archiveFile = null;
        Path archivePath = null;
        ZipArchiveOutputStream zos = null;
        ZipFile zf = null;
        InputStream fis = null;
        final File tmpDir = tmp[0];
        final File tmpFile = tmp[1];
        final Path tmpFilePath = tmpFile.toPath();
        try {
            archiveFile = File.createTempFile("test.", ".zip", tmpDir);
            archivePath = archiveFile.toPath();
            archiveFile.deleteOnExit();
            zos = new ZipArchiveOutputStream(archivePath);
            final ZipArchiveEntry in = (ZipArchiveEntry) zos.createArchiveEntry(tmpFilePath, "foo");
            zos.putArchiveEntry(in);
            final byte[] b = new byte[(int) tmpFile.length()];
            fis = Files.newInputStream(tmpFile.toPath());
            while (fis.read(b) > 0) {
                zos.write(b);
            }
            fis.close();
            fis = null;
            zos.closeArchiveEntry();
            zos.close();
            zos = null;
            zf = new ZipFile(archiveFile);
            final ZipArchiveEntry out = zf.getEntry("foo");
            assertNotNull(out);
            assertEquals("foo", out.getName());
            assertEquals(tmpFile.length(), out.getSize());
            assertEquals(tmpFile.lastModified() / 2000,
                         out.getLastModifiedDate().getTime() / 2000);
            assertFalse(out.isDirectory());
        } finally {
            ZipFile.closeQuietly(zf);
            if (zos != null) {
                zos.close();
            }
            tryHardToDelete(archiveFile);
            if (fis != null) {
                fis.close();
            }
            tryHardToDelete(tmpFile);
            rmdir(tmpDir);
        }
    }

    @Test
    public void testExplicitFileEntry() throws Exception {
        final File[] tmp = createTempDirAndFile();
        File archive = null;
        ZipArchiveOutputStream zos = null;
        ZipFile zf = null;
        InputStream fis = null;
        try {
            archive = File.createTempFile("test.", ".zip", tmp[0]);
            archive.deleteOnExit();
            zos = new ZipArchiveOutputStream(archive);
            final ZipArchiveEntry in = new ZipArchiveEntry("foo");
            in.setTime(tmp[1].lastModified());
            in.setSize(tmp[1].length());
            zos.putArchiveEntry(in);
            final byte[] b = new byte[(int) tmp[1].length()];
            fis = Files.newInputStream(tmp[1].toPath());
            while (fis.read(b) > 0) {
                zos.write(b);
            }
            fis.close();
            fis = null;
            zos.closeArchiveEntry();
            zos.close();
            zos = null;
            zf = new ZipFile(archive);
            final ZipArchiveEntry out = zf.getEntry("foo");
            assertNotNull(out);
            assertEquals("foo", out.getName());
            assertEquals(tmp[1].length(), out.getSize());
            assertEquals(tmp[1].lastModified() / 2000,
                         out.getLastModifiedDate().getTime() / 2000);
            assertFalse(out.isDirectory());
        } finally {
            ZipFile.closeQuietly(zf);
            if (zos != null) {
                zos.close();
            }
            tryHardToDelete(archive);
            if (fis != null) {
                fis.close();
            }
            tryHardToDelete(tmp[1]);
            rmdir(tmp[0]);
        }
    }

    @Test
    public void inputStreamStatisticsOfZipBombExcel() throws IOException, ArchiveException {
        final Map<String, List<Long>> expected = new HashMap<String, List<Long>>() {{
            put("[Content_Types].xml", Arrays.asList(8390036L, 8600L));
            put("xl/worksheets/sheet1.xml", Arrays.asList(1348L, 508L));
        }};
        testInputStreamStatistics("zipbomb.xlsx", expected);
    }

    @Test
    public void inputStreamStatisticsForImplodedEntry() throws IOException, ArchiveException {
        final Map<String, List<Long>> expected = new HashMap<String, List<Long>>() {{
            put("LICENSE.TXT", Arrays.asList(11560L, 4131L));
        }};
        testInputStreamStatistics("imploding-8Kdict-3trees.zip", expected);
    }

    @Test
    public void inputStreamStatisticsForShrunkEntry() throws IOException, ArchiveException {
        final Map<String, List<Long>> expected = new HashMap<String, List<Long>>() {{
            put("TEST1.XML", Arrays.asList(76L, 66L));
            put("TEST2.XML", Arrays.asList(81L, 76L));
        }};
        testInputStreamStatistics("SHRUNK.ZIP", expected);
    }

    @Test
    public void inputStreamStatisticsForStoredEntry() throws IOException, ArchiveException {
        final Map<String, List<Long>> expected = new HashMap<String, List<Long>>() {{
            put("test.txt", Arrays.asList(5L, 5L));
        }};
        testInputStreamStatistics("COMPRESS-264.zip", expected);
    }

    @Test
    public void inputStreamStatisticsForBzip2Entry() throws IOException, ArchiveException {
        final Map<String, List<Long>> expected = new HashMap<String, List<Long>>() {{
            put("lots-of-as", Arrays.asList(42L, 39L));
        }};
        testInputStreamStatistics("bzip2-zip.zip", expected);
    }

    @Test
    public void inputStreamStatisticsForDeflate64Entry() throws IOException, ArchiveException {
        final Map<String, List<Long>> expected = new HashMap<String, List<Long>>() {{
            put("input2", Arrays.asList(3072L, 2111L));
        }};
        testInputStreamStatistics("COMPRESS-380/COMPRESS-380.zip", expected);
    }

    @Test
    public void buildSplitZipWithTooSmallSizeThrowsException() throws IOException {
        assertThrows(IllegalArgumentException.class, () -> new ZipArchiveOutputStream(File.createTempFile("temp", "zip"), 64 * 1024 - 1));
    }

    @Test
    public void buildSplitZipWithTooLargeSizeThrowsException() throws IOException {
        assertThrows(IllegalArgumentException.class, () -> new ZipArchiveOutputStream(File.createTempFile("temp", "zip"), 4294967295L + 1));
    }

    @Test
    public void buildSplitZipWithSegmentAlreadyExistThrowsException() throws IOException {
        final File directoryToZip = getFilesToZip();
        final File outputZipFile = new File(dir, "splitZip.zip");
        final long splitSize = 100 * 1024L; /* 100 KB */
        try (final ZipArchiveOutputStream zipArchiveOutputStream = new ZipArchiveOutputStream(outputZipFile,
            splitSize)) {

            // create a file that has the same name of one of the created split segments
            final File sameNameFile = new File(dir, "splitZip.z01");
            sameNameFile.createNewFile();

            assertThrows(IOException.class, () -> addFilesToZip(zipArchiveOutputStream, directoryToZip));
        } catch (Exception e) {
            // Ignore:
            // java.io.IOException: This archive contains unclosed entries.
            //   at org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream.finish(ZipArchiveOutputStream.java:563)
            //   at org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream.close(ZipArchiveOutputStream.java:1119)
            //   at org.apache.commons.compress.archivers.ZipTestCase.buildSplitZipWithSegmentAlreadyExistThrowsException(ZipTestCase.java:715)
        }
    }

    @Test
    public void buildSplitZipTest() throws IOException {
        final File directoryToZip = getFilesToZip();
        createTestSplitZipSegments();

        final File lastFile = new File(dir, "splitZip.zip");
        try (SeekableByteChannel channel = ZipSplitReadOnlySeekableByteChannel.buildFromLastSplitSegment(lastFile);
            InputStream inputStream = Channels.newInputStream(channel);
            ZipArchiveInputStream splitInputStream = new ZipArchiveInputStream(inputStream,
                UTF_8.toString(), true, false, true)) {

            ArchiveEntry entry;
            final int filesNum = countNonDirectories(directoryToZip);
            int filesCount = 0;
            while ((entry = splitInputStream.getNextEntry()) != null) {
                if (entry.isDirectory()) {
                    continue;
                }
                // compare all files one by one
                final File fileToCompare = new File(entry.getName());
                try (InputStream inputStreamToCompare = Files.newInputStream(fileToCompare.toPath())) {
                    assertArrayEquals(IOUtils.toByteArray(splitInputStream),
                        IOUtils.toByteArray(inputStreamToCompare));
                }
                filesCount++;
            }
            // and the number of files should equal
            assertEquals(filesCount, filesNum);
        }
    }

    private void testInputStreamStatistics(final String fileName, final Map<String, List<Long>> expectedStatistics)
        throws IOException, ArchiveException {
        final File input = getFile(fileName);

        final Map<String,List<List<Long>>> actualStatistics = new HashMap<>();

        // stream access
        try (final InputStream fis = Files.newInputStream(input.toPath());
            final ArchiveInputStream in = ArchiveStreamFactory.DEFAULT.createArchiveInputStream("zip", fis)) {
            for (ArchiveEntry entry; (entry = in.getNextEntry()) != null; ) {
                readStream(in, entry, actualStatistics);
            }
        }

        // file access
        try (final ZipFile zf = new ZipFile(input)) {
            final Enumeration<ZipArchiveEntry> entries = zf.getEntries();
            while (entries.hasMoreElements()) {
                final ZipArchiveEntry zae = entries.nextElement();
                try (InputStream in = zf.getInputStream(zae)) {
                    readStream(in, zae, actualStatistics);
                }
            }
        }

        // compare statistics of stream / file access
        for (final Map.Entry<String,List<List<Long>>> me : actualStatistics.entrySet()) {
            assertEquals("Mismatch of stats for: " + me.getKey(),
                         me.getValue().get(0), me.getValue().get(1));
        }

        for (final Map.Entry<String, List<Long>> me : expectedStatistics.entrySet()) {
            assertEquals("Mismatch of stats with expected value for: " + me.getKey(),
                me.getValue(), actualStatistics.get(me.getKey()).get(0));
        }
    }

    private void readStream(final InputStream in, final ArchiveEntry entry, final Map<String,List<List<Long>>> map) throws IOException {
        final byte[] buf = new byte[4096];
        final InputStreamStatistics stats = (InputStreamStatistics) in;
        while (in.read(buf) != -1) {
            // consume all.
        }

        final String name = entry.getName();
        final List<List<Long>> l;
        if (map.containsKey(name)) {
            l = map.get(name);
        } else {
            map.put(name, l = new ArrayList<>());
        }

        final long t = stats.getUncompressedCount();
        final long b = stats.getCompressedCount();
        l.add(Arrays.asList(t, b));
    }

    private File getFilesToZip() throws IOException {
        final File originalZipFile = getFile("COMPRESS-477/split_zip_created_by_zip/zip_to_compare_created_by_zip.zip");
        try (ZipFile zipFile = new ZipFile(originalZipFile)) {
            final Enumeration<ZipArchiveEntry> zipEntries = zipFile.getEntries();
            ZipArchiveEntry zipEntry;
            File outputFile;
            byte[] buffer;
            int readLen;

            while (zipEntries.hasMoreElements()) {
                zipEntry = zipEntries.nextElement();
                if (zipEntry.isDirectory()) {
                    continue;
                }

                outputFile = new File(dir, zipEntry.getName());
                if (!outputFile.getParentFile().exists()) {
                    outputFile.getParentFile().mkdirs();
                }
                outputFile = new File(dir, zipEntry.getName());

                try (InputStream inputStream = zipFile.getInputStream(zipEntry);
                    OutputStream outputStream = Files.newOutputStream(outputFile.toPath())) {
                    buffer = new byte[(int) zipEntry.getSize()];
                    while ((readLen = inputStream.read(buffer)) > 0) {
                        outputStream.write(buffer, 0, readLen);
                    }
                }
            }
        }
        return dir.listFiles()[0];
    }

    private void createTestSplitZipSegments() throws IOException {
        final File directoryToZip = getFilesToZip();
        final File outputZipFile = new File(dir, "splitZip.zip");
        final long splitSize = 100 * 1024L; /* 100 KB */
        try (final ZipArchiveOutputStream zipArchiveOutputStream = new ZipArchiveOutputStream(outputZipFile,
            splitSize)) {
            addFilesToZip(zipArchiveOutputStream, directoryToZip);
        }
    }

    private void addFilesToZip(final ZipArchiveOutputStream zipArchiveOutputStream, final File fileToAdd) throws IOException {
        if (fileToAdd.isDirectory()) {
            for (final File file : fileToAdd.listFiles()) {
                addFilesToZip(zipArchiveOutputStream, file);
            }
        } else {
            final ZipArchiveEntry zipArchiveEntry = new ZipArchiveEntry(fileToAdd.getPath());
            zipArchiveEntry.setMethod(ZipEntry.DEFLATED);

            zipArchiveOutputStream.putArchiveEntry(zipArchiveEntry);
            try (final InputStream input = Files.newInputStream(fileToAdd.toPath())) {
                IOUtils.copy(input, zipArchiveOutputStream);
            } finally {
                zipArchiveOutputStream.closeArchiveEntry();
            }
        }
    }

    private int countNonDirectories(final File file) {
        if(!file.isDirectory()) {
            return 1;
        }

        int result = 0;
        for (final File fileInDirectory : file.listFiles()) {
            result += countNonDirectories(fileInDirectory);
        }

        return result;
    }
}


text:
namespace SumoLogic.Logging.Serilog.Extensions
{
    using System;
    using System.Linq.Expressions;
    using System.Reflection;
    using SumoLogic.Logging.Serilog.Config;

    /// <summary>
    /// Extensions of <see cref="SumoLogicConnection"/>.
    /// </summary>
    internal static class SumoLogicConnectionExtensions
    {
        /// <summary>
        /// Sets time span if not empty to provided configuration.
        /// </summary>
        /// <param name="target">Target configuration.</param>
        /// <param name="member">Time span property expression.</param>
        /// <param name="value">Value to be set.</param>
        /// <returns>
        /// Target instance.
        /// </returns>
        public static SumoLogicConnection SetTimeSpanIfNotEmpty(
            this SumoLogicConnection target,
            Expression<Func<SumoLogicConnection, TimeSpan>> member,
            long? value)
        {
            if (value.HasValue
                && member.Body is MemberExpression memberExpression
                && memberExpression.Member is PropertyInfo propertyInfo)
            {
                propertyInfo.SetValue(target, TimeSpan.FromMilliseconds(value.Value), null);
            }

            return target;
        }
    }
}