text:
<!DOCTYPE HTML>

	<meta http-equiv="content-type" content="text/html; charset=utf-8" />
	<meta name="generator" content="JsDoc Toolkit" />
	<title>Built.Query - Built.IO JavaScript SDK Reference</title>

	<link media="all" rel="stylesheet" href="../css/common.css" type="text/css" />
	<link media="all" rel="stylesheet" href="../css/prettify.css" type="text/css" />
	<link media="all" rel="stylesheet" href="../css/bootstrap.min.css" type="text/css" />
	<link media="print" rel="stylesheet" href="../css/print.css" type="text/css" />

				built.io JavaScript Reference

Classes

Built

ACL

Analytics

Application

Cache

Cloud

Delta

File

Object

Promise

Query

Role

User

Util

				Built.Query

Inheritance

Query

		Constructor

		Static members

Constructor

							Query
							( String ClassUid )

							Static

									Get new instance of Built.Query.

											Parameters

ClassUid : String

Init Built.Query with class uid.

											Returns

unknown

Built.Query Object Instance.

Static members

Static MethodsDefined By

									afterUid
									( String ObjectUid )
									 : Built.Query

									Static
									Built.Query

											Returned filter results after specified Uid.

													Parameters

ObjectUid : String

.

													Returns

Built.Query

Returns the query, so you can chain this call.

									ascending
									( String Key )
									 : Built.Query

									Static
									Built.Query

											Sort Query result in ascending order by specific key field

													Parameters

Key : String

Field uid.

													Returns

Built.Query

Returns the query, so you can chain this call.

									beforeUid
									( String ObjectUid )
									 : Built.Query

									Static
									Built.Query

											Returned filter results before specified Uid.

													Parameters

ObjectUid : String

.

													Returns

Built.Query

Returns the query, so you can chain this call.

									containedIn
									( String key, Array values )
									 : Built.Query

									Static
									Built.Query

											Add a constraint to the query that requires a particular key's value to
be contained in the provided list of values.

													Parameters

key : String

The key to check.

values : Array

The values that will match.

													Returns

Built.Query

Returns the query, so you can chain this call.

									count
									( Object Object )
									 : Built.Query

									Static
									Built.Query

											Get total count of object fits in query without
notation to specify which fields in the included object are also fetch.

													Parameters

Object : Object

Containing onSuccess,onError and always method.

													Returns

Built.Query

Returns the query, so you can chain this call.

									descending
									( String Key )
									 : Built.Query

									Static
									Built.Query

											Sort Query result in descending order by specific key field

													Parameters

Key : String

Field uid.

													Returns

Built.Query

Returns the query, so you can chain this call.

									doesNotExist
									( String key )
									 : Built.Query

									Static
									Built.Query

											Add a constraint for finding objects that do not contain a given key.

													Parameters

key : String

The key that should not exist

													Returns

Built.Query

Returns the query, so you can chain this call.

									except
									( String Field_uid, Boolean Reference )
									 : Built.Query

									Static
									Built.Query

											The "except" parameter specifies an uid's of field that would NOT be included in the response

													Parameters

Field_uid : String

uid of the field to include in response.

Reference : Boolean

Whether Field is reference type or not. Default(false).

													Returns

Built.Query

Returns the query, so you can chain this call.

									exec
									( Object Options )
									 : Built.Query

									Static
									Built.Query

											Execute the Query.

													Parameters

Options : Object

Optional Hash map for options and callbacks eg:-  {onSuccess:function(data){}}.

													Returns

Built.Query

Returns the query, so you can chain this call.

									exists
									( String key )
									 : Built.Query

									Static
									Built.Query

											Add a constraint for finding objects that contain the given key.

													Parameters

key : String

The key that should exist.

													Returns

Built.Query

Returns the query, so you can chain this call.

									greaterThan
									( String key, Number value )
									 : Built.Query

									Static
									Built.Query

											Add a constraint to the query that requires a particular key's value to
be greater than the provided value.

													Parameters

key : String

The key to check.

value : Number

The value that provides an lower bound.

													Returns

Built.Query

Returns the query, so you can chain this call.

									greaterThanOrEqualTo
									( String key, Number value )
									 : Built.Query

									Static
									Built.Query

											Add a constraint to the query that requires a particular key's value to
be greater than or equal to the provided value.

													Parameters

key : String

The key to check.

value : Number

The value that provides an lower bound.

													Returns

Built.Query

Returns the query, so you can chain this call.

									include
									( String key )
									 : Built.Query

									Static
									Built.Query

											Include Referenced Built.Objects for the provided key.  You can use dot
notation to specify which fields in the included object are also fetch.

													Parameters

key : String

The name of the key to include.

													Returns

Built.Query

Returns the query, so you can chain this call.

									includeCount
									(  )
									 : Built.Query

									Static
									Built.Query

											Add Count of all objects in Query result.

													Returns

Built.Query

Returns the query, so you can chain this call.

									includeDrafts
									(  )
									 : Built.Query

									Static
									Built.Query

											Add Drafts objects in Query search context.

													Returns

Built.Query

Returns the query, so you can chain this call.

									includeFilter
									( String Key, String Value )
									 : Built.Query

									Static
									Built.Query

											Include custom query in key value string

													Parameters

Key : String

Query name to include.

Value : String

Query value to include.

													Returns

Built.Query

Returns the query, so you can chain this call.

									includeSchema
									(  )
									 : Built.Query

									Static
									Built.Query

											Add Class schema in Query result.

													Returns

Built.Query

Returns the query, so you can chain this call.

									includeUser
									(  )
									 : Built.Query

									Static
									Built.Query

											Returned objects Model will also contain a key "_owner", which will include the owner's profile in the objects' data.

													Returns

Built.Query

Returns the query, so you can chain this call.

									lessThan
									( String key, Number value )
									 : Built.Query

									Static
									Built.Query

											Add a constraint to the query that requires a particular key's value to
be less than the provided value.

													Parameters

key : String

The key to check.

value : Number

The value that provides an upper bound.

													Returns

Built.Query

Returns the query, so you can chain this call.

									lessThanOrEqualTo
									( String key, Number value )
									 : Built.Query

									Static
									Built.Query

											Add a constraint to the query that requires a particular key's value to
be less than or equal to the provided value.

													Parameters

key : String

The key to check.

value : Number

The value that provides an upper bound.

													Returns

Built.Query

Returns the query, so you can chain this call.

									limit
									( Number n )
									 : Built.Query

									Static
									Built.Query

											Sets the limit of the number of results to return.

													Parameters

n : Number

the number of results to limit to.

													Returns

Built.Query

Returns the query, so you can chain this call.

									matches
									( String key, RegExp regex )
									 : Built.Query

									Static
									Built.Query

											Add a regular expression constraint for finding string values that match
the provided regular expression.
This may be slow for large datasets.

													Parameters

key : String

The key that the string to match is stored in.

regex : RegExp

The regular expression pattern to match.

													Returns

Built.Query

Returns the query, so you can chain this call.

									notContainedIn
									( String key, Array values )
									 : Built.Query

									Static
									Built.Query

											Add a constraint to the query that requires a particular key's value to
not be contained in the provided list of values.

													Parameters

key : String

The key to check.

values : Array

The values that will not match.

													Returns

Built.Query

Returns the query, so you can chain this call.

									notEqualTo
									( String key, unknown value )
									 : Built.Query

									Static
									Built.Query

											Add a constraint to the query that requires a particular key's value to
be not equal to the provided value.

													Parameters

key : String

The key to check.

value : unknown

The value that must not be equalled.

													Returns

Built.Query

Returns the query, so you can chain this call.

									only
									( String Field_uid, Boolean Reference )
									 : Built.Query

									Static
									Built.Query

											The "only" parameter specifies an uid's that would be included in the response

													Parameters

Field_uid : String

uid of the field to include in response.

Reference : Boolean

Whether Field is reference type or not. Default(false).

													Returns

Built.Query

Returns the query, so you can chain this call.

									onlyDrafts
									(  )
									 : Built.Query

									Static
									Built.Query

											Return only Drafts objects in Query search context.

													Returns

Built.Query

Returns the query, so you can chain this call.

									referenceRegex
									( String Key, String Value )
									 : Built.Query

									Static
									Built.Query

											The "refRegex" is the same as "refWhere", but here we take a regular expression for the reference search.

For example, if "Post" has a reference to "Comments", and comments have a reference to "User"

referenceRegex("comment.user.name","^Jo");

													Parameters

Key : String

Reference Key Uid.

Value : String

Regex Value.

													Returns

Built.Query

Returns the query, so you can chain this call.

									referenceWhere
									( String Key, String Value )
									 : Built.Query

									Static
									Built.Query

											The "referenceWhere" parameter allows you to query a reference.

Using this, you can query references which are seperated by a ".".

For example, if "Post" has a reference to "Comments", and comments have a reference to "User"

referenceWhere("comment.user.name","John");

													Parameters

Key : String

Reference Key Uid.

Value : String

Value.

													Returns

Built.Query

Returns the query, so you can chain this call.

									skip
									( Number n )
									 : Built.Query

									Static
									Built.Query

											Sets the number of results to skip before returning any results.
This is useful for pagination.
Default is to skip zero results.

													Parameters

n : Number

the number of results to skip.

													Returns

Built.Query

Returns the query, so you can chain this call.

									where
									( String Key, String Value )
									 : Built.Query

									Static
									Built.Query

											The where method allows to filter object for a matching field value in your object.

Nested searches for embedded objects are possible, by using a "." seperator

													Parameters

Key : String

Field Uid.

Value : String

Value.

													Returns

Built.Query

Returns the query, so you can chain this call.

©Raw Engineering 2013

Documentation generated by JsDoc Toolkit 2.4.0


text:
Pychron and the Database
=============================

redpajama_set_name: RedPajamaGithub


text:
package org.xbill.DNS;

import java.io.EOFException;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.security.SecureRandom;
import java.time.Duration;
import java.util.Iterator;
import java.util.Queue;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentLinkedQueue;
import lombok.RequiredArgsConstructor;
import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@UtilityClass
final class NioUdpClient extends NioClient {
  private static final int EPHEMERAL_START;
  private static final int EPHEMERAL_RANGE;

  private static final SecureRandom prng;
  private static final Queue<Transaction> registrationQueue = new ConcurrentLinkedQueue<>();
  private static final Queue<Transaction> pendingTransactions = new ConcurrentLinkedQueue<>();

  static {
    // https://tools.ietf.org/html/rfc6335#section-6
    int ephemeralStartDefault = 49152;
    int ephemeralEndDefault = 65535;

    // Linux usually uses 32768-60999
    if (System.getProperty("os.name").toLowerCase().contains("linux")) {
      ephemeralStartDefault = 32768;
      ephemeralEndDefault = 60999;
    }

    EPHEMERAL_START = Integer.getInteger("dnsjava.udp.ephemeral.start", ephemeralStartDefault);
    int ephemeralEnd = Integer.getInteger("dnsjava.udp.ephemeral.end", ephemeralEndDefault);
    EPHEMERAL_RANGE = ephemeralEnd - EPHEMERAL_START;

    if (Boolean.getBoolean("dnsjava.udp.ephemeral.use_ephemeral_port")) {
      prng = null;
    } else {
      prng = new SecureRandom();
    }
    addSelectorTimeoutTask(NioUdpClient::processPendingRegistrations);
    addSelectorTimeoutTask(NioUdpClient::checkTransactionTimeouts);
    addCloseTask(NioUdpClient::closeUdp);
  }

  private static void processPendingRegistrations() {
    while (!registrationQueue.isEmpty()) {
      Transaction t = registrationQueue.remove();
      try {
        t.channel.register(selector(), SelectionKey.OP_READ, t);
        t.send();
      } catch (IOException e) {
        t.f.completeExceptionally(e);
      }
    }
  }

  private static void checkTransactionTimeouts() {
    for (Iterator<Transaction> it = pendingTransactions.iterator(); it.hasNext(); ) {
      Transaction t = it.next();
      if (t.endTime - System.nanoTime() < 0) {
        t.silentCloseChannel();
        t.f.completeExceptionally(new SocketTimeoutException("Query timed out"));
        it.remove();
      }
    }
  }

  @RequiredArgsConstructor
  private static class Transaction implements KeyProcessor {
    private final byte[] data;
    private final int max;
    private final long endTime;
    private final DatagramChannel channel;
    private final CompletableFuture<byte[]> f;

    void send() throws IOException {
      ByteBuffer buffer = ByteBuffer.wrap(data);
      verboseLog(
          "UDP write",
          channel.socket().getLocalSocketAddress(),
          channel.socket().getRemoteSocketAddress(),
          data);
      int n = channel.send(buffer, channel.socket().getRemoteSocketAddress());
      if (n <= 0) {
        throw new EOFException();
      }
    }

    @Override
    public void processReadyKey(SelectionKey key) {
      if (!key.isReadable()) {
        silentCloseChannel();
        f.completeExceptionally(new EOFException("channel not readable"));
        pendingTransactions.remove(this);
        return;
      }

      DatagramChannel channel = (DatagramChannel) key.channel();
      ByteBuffer buffer = ByteBuffer.allocate(max);
      int read;
      try {
        read = channel.read(buffer);
        if (read <= 0) {
          throw new EOFException();
        }
      } catch (IOException e) {
        silentCloseChannel();
        f.completeExceptionally(e);
        pendingTransactions.remove(this);
        return;
      }

      buffer.flip();
      byte[] data = new byte[read];
      System.arraycopy(buffer.array(), 0, data, 0, read);
      verboseLog(
          "UDP read",
          channel.socket().getLocalSocketAddress(),
          channel.socket().getRemoteSocketAddress(),
          data);
      silentCloseChannel();
      f.complete(data);
      pendingTransactions.remove(this);
    }

    private void silentCloseChannel() {
      try {
        channel.disconnect();
      } catch (IOException e) {
        // ignore, we either already have everything we need or can't do anything
      } finally {
        try {
          channel.close();
        } catch (IOException e) {
          // ignore
        }
      }
    }
  }

  static CompletableFuture<byte[]> sendrecv(
      InetSocketAddress local, InetSocketAddress remote, byte[] data, int max, Duration timeout) {
    CompletableFuture<byte[]> f = new CompletableFuture<>();
    try {
      final Selector selector = selector();
      DatagramChannel channel = DatagramChannel.open();
      channel.configureBlocking(false);
      if (local == null || local.getPort() == 0) {
        boolean bound = false;
        for (int i = 0; i < 1024; i++) {
          try {
            InetSocketAddress addr = null;
            if (local == null) {
              if (prng != null) {
                addr = new InetSocketAddress(prng.nextInt(EPHEMERAL_RANGE) + EPHEMERAL_START);
              }
            } else {
              int port = local.getPort();
              if (port == 0 && prng != null) {
                port = prng.nextInt(EPHEMERAL_RANGE) + EPHEMERAL_START;
              }

              addr = new InetSocketAddress(local.getAddress(), port);
            }

            channel.bind(addr);
            bound = true;
            break;
          } catch (SocketException e) {
            // ignore, we'll try another random port
          }
        }

        if (!bound) {
          channel.close();
          f.completeExceptionally(new IOException("No available source port found"));
          return f;
        }
      }

      channel.connect(remote);
      long endTime = System.nanoTime() + timeout.toNanos();
      Transaction t = new Transaction(data, max, endTime, channel, f);
      pendingTransactions.add(t);
      registrationQueue.add(t);
      selector.wakeup();
    } catch (IOException e) {
      f.completeExceptionally(e);
    }

    return f;
  }

  private static void closeUdp() {
    registrationQueue.clear();
    EOFException closing = new EOFException("Client is closing");
    pendingTransactions.forEach(t -> t.f.completeExceptionally(closing));
    pendingTransactions.clear();
  }
}


text:
rpi_android_kernel
==================

Android kernel for raspberry pi


text:
@implementation BADrawView

- (void)setDrawBlock:(DrawBlock)drawBlock {
    _drawBlock = drawBlock;
    [self setNeedsDisplay];
}

- (void)drawRect:(CGRect)rect {
    if (self.drawBlock) {
        self.drawBlock(rect);
    }
}

- (void)setFrame:(CGRect)frame {
    [super setFrame:frame];
    [self setNeedsDisplay];
}

@end


text:
Now for a new construct, an infinite while loop!

Infinite while loops are used to make a set of code execute repeatedly, over and over, until the user decides to stop it.

An infinite while loop's structure looks like this:

```python
while True:
    <execute this indented code>
    <jump back to the top of the while statement>
```

For example, will constantly print the pattern "1 2 3 1 2 3 1 2 3 1 2 3..." over and over.

```python
while True:
    print "1"
    print "2"
    print "3"
```

We can make the computer count to infinity like this:

```python
counter = 0
while True:
    counter = counter + 1
    print counter
```

We can make the computer act like a clock by counting seconds, using time.sleep to make the computer pause between each second.
```python
import time
counter = 0
while True:
    counter = counter + 1
    print counter
    time.sleep(1)
```

### Flower Path in Minecraft
```
import time
import mcpi.minecraft as minecraft
mc = minecraft.Minecraft.create(address="199.96.85.3", name="seanybob")

while True:

    pos = mc.player.getPos()
    x = pos.x
    y = pos.y
    z = pos.z

    block = 38
    mc.setBlock(x, y, z, block)

    time.sleep(0.1)
```

A trail of flowers behind us! We can change this to be any block we want, of course. Let's change it to fire, block ID 51.

You can stop an infinite loop with control+c in your terminal/shell.

#### CHALLENGE

- Using the code above as a base, make a roller coaster! You will want to place Powered Rail, and also put redstone blocks underneath each power rail.


text:
'use strict';

var angular = require('angular');

describe('cc-number', function () {

  beforeEach(angular.mock.module(require('../')));

  var $compile, element, scope, controller;
  beforeEach(angular.mock.inject(function ($injector) {
    $compile   = $injector.get('$compile');
    element    = angular.element('<input ng-model="card.number" cc-number cc-type="cardType" />');
    scope      = $injector.get('$rootScope').$new();
    scope.card = {};
    controller = $compile(element)(scope).controller('ngModel');
  }));

  it('adds a numeric pattern', function () {
    expect(element.attr('pattern')).to.equal('[0-9]*');
  });

  it('accepts a valid card', function () {
    controller.$setViewValue('4242 4242 4242 4242');
    expect(controller.$valid).to.be.true;
    expect(scope.card.number).to.equal('4242424242424242');
  });

  it('accepts a valid card with specified type', function () {
    scope.cardType = 'Visa';
    controller.$setViewValue('4242 4242 4242 4242');
    scope.$digest();
    expect(controller.$error.ccNumberType).to.not.be.ok;
  });

  it('rejects a luhn-invalid card', function () {
    controller.$setViewValue('4242424242424241');
    expect(controller.$error.ccNumber).to.be.true;
    expect(scope.card.number).to.be.undefined;
  });

  it('rejects a luhn-valid card with no matching type', function () {
    controller.$setViewValue('42');
    expect(controller.$error.ccNumber).to.be.true;
    expect(scope.card.number).to.be.undefined;
  });

  it('rejects an invalid card', function () {
    controller.$setViewValue('4242424242424241');
    expect(controller.$error.ccNumber).to.be.true;
    expect(scope.card.number).to.be.undefined;
  });

  it('rejects an invalid card when the type is a mismatch', function () {
    scope.cardType = 'American Express';
    controller.$setViewValue('4242 4242 4242 4242');
    scope.$digest();
    expect(controller.$error.ccNumber).to.not.be.ok;
    expect(controller.$error.ccNumberType).to.be.true;
  });

  describe('$ccType', function () {

    var ccNumberController;
    beforeEach(function () {
      ccNumberController = element.controller('ccNumber');
      scope.$digest();
    });

    it('exposes a calculated card type', function () {
      controller.$setViewValue('4242424242424242');
      scope.$digest();
      expect(ccNumberController.type).to.equal('Visa');
    });

    it('syncs the type with the ngModelController', function () {
      controller.$setViewValue('4242424242424242');
      scope.$digest();
      expect(controller.$ccType).to.equal('Visa');
    });

  });

  describe('$ccEagerType', function () {

    var ccNumberController;
    beforeEach(function () {
      element.attr('cc-eager-type', '');
      ccNumberController = $compile(element)(scope).controller('ccNumber');
      controller = element.controller('ngModel');
      scope.$digest();
    });

    it('eagerly checks the type', function () {
      controller.$setViewValue('42');
      scope.$digest();
      expect(ccNumberController.eagerType).to.equal('Visa');
    });

    it('syncs the eager type with the ngModelController', function () {
      controller.$setViewValue('42');
      expect(controller.$ccEagerType).to.equal('Visa');
    });

  });

});


text:
cdr been clearer
===

The other day, I noticed [a flurry of people arguing](http://github.com/rails/rails/commit/22af62cf486721ee2e45bb720c42ac2f4121faf4#comments "Comments on a commit to rails") about whether adding methods like `#second`, `#third`, and `#fourth` to `Array` is a good idea or not.

I quipped:

> Would anyone prefer methods like caddr?

I'd better clear something up. I have never written a method like `#fourth` for myself, but I am not rabidly opposed to their inclusion in Rails or Ruby either. My opinion on opening core classes is that it is not sustainable in the long run, but at the same time I'm not losing sleep over the idea that upgrading to Edge Rails will break some piece of code where I've defined the method `#second` as meaning an instance of array seconds the nomination of another model object for speaker of the house.

If it isn't going to break my code, or if people using it isn't going to make their code unreadable... It's hard for me to get worked up about it.

When I asked if people would prefer `caddr`, I was absolutely not suggesting that `#fourth` was clearly superior because it's English. Lisp's `c(a|d)+r` methods are like specialized tools. They are readable to professional Lisp programmers because (a) they are a standard part of the language, and (b) they are more powerful than `#fourth` because they can reach into any arbitrary nested list and extract a node.

Words become unwieldy when you need a lot of them to get the job done. That's why I don't write "The fourteenth day of the sixth month of the year one thousand, nine hundred, and sixty-two" when people ask me my birth date, and that's why terser tools are important parts of programming. If you had to reach into a nested list, you might find `.fourth.last.first.third` a little cumbersome.

I think it's perfectly fine to want to write Ruby code that looks like English. And if you aren't writing "The fourteenth day of the sixth month of the year one thousand, nine hundred, and sixty-two" but rather "The fourth item of this list," it's no big whup to me if you prefer `#fourth` to `[3]`.

So why did I ask the question? I guess I was trying to provoke people into doing something other than arguing about whether David had just moved their cheese. While it's fine to say you like `#fourth`, I think it's also even better to say "Ok, but what would be *really* useful is..."

That's all.

p.s. If you press me to give a firm opinion, I choose [blue in green](http://bikeshed.com) :-)

---

My recent work:

![](http://i.minus.com/iL337yTdgFj7.png)[![JavaScript Allongé](http://i.minus.com/iW2E1A8M5UWe6.jpeg)](http://leanpub.com/javascript-allonge "JavaScript Allongé")![](http://i.minus.com/iL337yTdgFj7.png)[![CoffeeScript Ristretto](http://i.minus.com/iMmGxzIZkHSLD.jpeg)](http://leanpub.com/coffeescript-ristretto "CoffeeScript Ristretto")![](http://i.minus.com/iL337yTdgFj7.png)[![Kestrels, Quirky Birds, and Hopeless Egocentricity](http://i.minus.com/ibw1f1ARQ4bhi1.jpeg)](http://leanpub.com/combinators "Kestrels, Quirky Birds, and Hopeless Egocentricity")

* [JavaScript Allongé](http://leanpub.com/javascript-allonge), [CoffeeScript Ristretto](http://leanpub.com/coffeescript-ristretto), and my [other books](http://leanpub.com/u/raganwald).
* [allong.es](http://allong.es), practical function combinators and decorators for JavaScript.
* [Method Combinators](https://github.com/raganwald/method-combinators), a CoffeeScript/JavaScript library for writing method decorators, simply and easily.
* [jQuery Combinators](http://github.com/raganwald/jquery-combinators), what else? A jQuery plugin for writing your own fluent, jQuery-like code.

---

(Spot a bug or a spelling mistake? This is a Github repo, fork it and send me a pull request!)

[Reg Braithwaite](http://braythwayt.com) | [@raganwald](http://twitter.com/raganwald)


text:
use params::InitParams;

/// Initialise the kernel heap.
//  TODO: this is the Worst Thing In The Universe. De-stupid-ify it.
pub unsafe fn initialize<'a>(params: &InitParams) -> Result<&'a str, &'a str> {
    // let heap_base_ptr = params.heap_base.as_mut_ptr();
    let heap_size: u64 = (params.heap_top - params.heap_base).into();
    // buddy::system::init_heap(heap_base_ptr, heap_size as usize);
    Ok("[ OKAY ]")
}


text:
package cm.dart.jsonexample1.converters;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * Created by bwa on 10/24/15.
 */
class StringToInputStreamReaderConverter implements Converter<String, InputStreamReader> {
    @Override
    public InputStreamReader convert(String from) throws IOException {
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(from.getBytes("UTF-8"));
        InputStreamReader inputStreamReader = new InputStreamReader(byteArrayInputStream);
        return inputStreamReader;
    }
}


text:
/* @flow */

import {
  InputTypeComposer,
  type ObjectTypeComposerFieldConfigAsObjectDefinition,
} from 'graphql-compose';
import { getTypeName, type CommonOpts, desc } from '../../../utils';
import { getAnalyzedAsFieldConfigMap } from '../../Commons/FieldNames';

export function getFuzzyITC<TContext>(
  opts: CommonOpts<TContext>
): InputTypeComposer<TContext> | ObjectTypeComposerFieldConfigAsObjectDefinition<any, any> {
  const name = getTypeName('QueryFuzzy', opts);
  const description = desc(
    `
    The fuzzy query uses similarity based on Levenshtein edit distance.
    [Documentation](https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-fuzzy-query.html)
  `
  );

  const subName = getTypeName('QueryFuzzySettings', opts);
  const fields = getAnalyzedAsFieldConfigMap(
    opts,
    opts.getOrCreateITC(subName, () => ({
      name: subName,
      fields: {
        value: 'String!',
        boost: 'Float',
        fuzziness: 'Int',
        prefix_length: 'Int',
        max_expansions: 'Int',
      },
    }))
  );

  if (typeof fields === 'object') {
    return opts.getOrCreateITC(name, () => ({
      name,
      description,
      fields,
    }));
  }

  return {
    type: 'JSON',
    description,
  };
}


text:
package com.github.rnowling.bps.datagenerator.framework.markovmodels;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import static org.junit.matchers.JUnitMatchers.hasItem;

import java.util.Arrays;

import org.junit.Test;

import com.github.rnowling.bps.datagenerator.framework.SeedFactory;
import com.github.rnowling.bps.datagenerator.framework.markovmodels.MarkovModel;
import com.github.rnowling.bps.datagenerator.framework.markovmodels.MarkovModelBuilder;
import com.github.rnowling.bps.datagenerator.framework.markovmodels.MarkovProcess;

public class TestMarkovProcess
{

	@Test
	public void test() throws Exception
	{
		SeedFactory factory = new SeedFactory(1245);
		MarkovModelBuilder<String> builder = MarkovModelBuilder.create();

		builder.addStartState("a", 1.0);
		builder.addTransition("a", "b", 1.0);
		builder.addTransition("a", "c", 1.0);

		MarkovModel<String> msm = builder.build();
		MarkovProcess<String> process = MarkovProcess.create(msm, factory);

		String firstState = process.sample();
		assertEquals(firstState, "a");

		String secondState = process.sample();
		assertThat(Arrays.asList("b", "c"), hasItem(secondState));
	}

}


text:
package com.griddynamics.maven.plugin.cm.algorithms.tree;

import com.griddynamics.maven.plugin.cm.MergeException;
import com.griddynamics.maven.plugin.cm.TreeMergeContext;
import org.codehaus.plexus.util.FileUtils;

import java.io.File;
import java.io.IOException;

public class CopyTreeMergeAlgorithm
        extends AbstractConfigurableTreeMergeAlgorithm {

    @Override
    protected boolean canMerge(File source, File target) {
        return source.isDirectory() && !target.exists();
    }

    @Override
    public void merge(TreeMergeContext mergeContext) throws IOException, MergeException {
        org.apache.commons.io.FileUtils.copyDirectory(mergeContext.getSourceDir(), mergeContext.getTargetDir());
    }

}


text:
package net.ssehub.easy.instantiation.core.model.vilTypes;

/**
 * Allows defining type compatibilities of later defined types.
 *
 * @author Holger Eichelberger
 */
public interface IActualTypeAssignmentProvider {

    /**
     * Returns whether type1 is a super class of or equal to type2.
     *
     * @param type1 the first type to check
     * @param type2 the second type to check
     * @return true if assignable, false else
     */
    @Invisible
    public boolean isAssignableFrom(IMetaType type1, IMetaType type2);

}


text:
"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = previousThursday;

var _index = _interopRequireDefault(require("../_lib/requiredArgs/index.js"));

var _index2 = _interopRequireDefault(require("../previousDay/index.js"));

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

/**
 * @name previousThursday
 * @category Weekday Helpers
 * @summary When is the previous Thursday?
 *
 * @description
 * When is the previous Thursday?
 *
 * @param {Date | number} date - the date to start counting from
 * @returns {Date} the previous Thursday
 * @throws {TypeError} 1 argument required
 *
 * @example
 * // When is the previous Thursday before Jun, 18, 2021?
 * const result = previousThursday(new Date(2021, 5, 18))
 * //=> Thu June 17 2021 00:00:00
 */
function previousThursday(date) {
  (0, _index.default)(1, arguments);
  return (0, _index2.default)(date, 4);
}

module.exports = exports.default;


text:
using System.Collections.Generic;
using System.Text.Json;
using Azure.Core;

namespace Azure.ResourceManager.Network.Models
{
    public partial class AzureFirewallNetworkRule : IUtf8JsonSerializable
    {
        void IUtf8JsonSerializable.Write(Utf8JsonWriter writer)
        {
            writer.WriteStartObject();
            if (Optional.IsDefined(Name))
            {
                writer.WritePropertyName("name");
                writer.WriteStringValue(Name);
            }
            if (Optional.IsDefined(Description))
            {
                writer.WritePropertyName("description");
                writer.WriteStringValue(Description);
            }
            if (Optional.IsCollectionDefined(Protocols))
            {
                writer.WritePropertyName("protocols");
                writer.WriteStartArray();
                foreach (var item in Protocols)
                {
                    writer.WriteStringValue(item.ToString());
                }
                writer.WriteEndArray();
            }
            if (Optional.IsCollectionDefined(SourceAddresses))
            {
                writer.WritePropertyName("sourceAddresses");
                writer.WriteStartArray();
                foreach (var item in SourceAddresses)
                {
                    writer.WriteStringValue(item);
                }
                writer.WriteEndArray();
            }
            if (Optional.IsCollectionDefined(DestinationAddresses))
            {
                writer.WritePropertyName("destinationAddresses");
                writer.WriteStartArray();
                foreach (var item in DestinationAddresses)
                {
                    writer.WriteStringValue(item);
                }
                writer.WriteEndArray();
            }
            if (Optional.IsCollectionDefined(DestinationPorts))
            {
                writer.WritePropertyName("destinationPorts");
                writer.WriteStartArray();
                foreach (var item in DestinationPorts)
                {
                    writer.WriteStringValue(item);
                }
                writer.WriteEndArray();
            }
            if (Optional.IsCollectionDefined(DestinationFqdns))
            {
                writer.WritePropertyName("destinationFqdns");
                writer.WriteStartArray();
                foreach (var item in DestinationFqdns)
                {
                    writer.WriteStringValue(item);
                }
                writer.WriteEndArray();
            }
            if (Optional.IsCollectionDefined(SourceIPGroups))
            {
                writer.WritePropertyName("sourceIpGroups");
                writer.WriteStartArray();
                foreach (var item in SourceIPGroups)
                {
                    writer.WriteStringValue(item);
                }
                writer.WriteEndArray();
            }
            if (Optional.IsCollectionDefined(DestinationIPGroups))
            {
                writer.WritePropertyName("destinationIpGroups");
                writer.WriteStartArray();
                foreach (var item in DestinationIPGroups)
                {
                    writer.WriteStringValue(item);
                }
                writer.WriteEndArray();
            }
            writer.WriteEndObject();
        }

        internal static AzureFirewallNetworkRule DeserializeAzureFirewallNetworkRule(JsonElement element)
        {
            Optional<string> name = default;
            Optional<string> description = default;
            Optional<IList<AzureFirewallNetworkRuleProtocol>> protocols = default;
            Optional<IList<string>> sourceAddresses = default;
            Optional<IList<string>> destinationAddresses = default;
            Optional<IList<string>> destinationPorts = default;
            Optional<IList<string>> destinationFqdns = default;
            Optional<IList<string>> sourceIPGroups = default;
            Optional<IList<string>> destinationIPGroups = default;
            foreach (var property in element.EnumerateObject())
            {
                if (property.NameEquals("name"))
                {
                    name = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("description"))
                {
                    description = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("protocols"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    List<AzureFirewallNetworkRuleProtocol> array = new List<AzureFirewallNetworkRuleProtocol>();
                    foreach (var item in property.Value.EnumerateArray())
                    {
                        array.Add(new AzureFirewallNetworkRuleProtocol(item.GetString()));
                    }
                    protocols = array;
                    continue;
                }
                if (property.NameEquals("sourceAddresses"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    List<string> array = new List<string>();
                    foreach (var item in property.Value.EnumerateArray())
                    {
                        array.Add(item.GetString());
                    }
                    sourceAddresses = array;
                    continue;
                }
                if (property.NameEquals("destinationAddresses"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    List<string> array = new List<string>();
                    foreach (var item in property.Value.EnumerateArray())
                    {
                        array.Add(item.GetString());
                    }
                    destinationAddresses = array;
                    continue;
                }
                if (property.NameEquals("destinationPorts"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    List<string> array = new List<string>();
                    foreach (var item in property.Value.EnumerateArray())
                    {
                        array.Add(item.GetString());
                    }
                    destinationPorts = array;
                    continue;
                }
                if (property.NameEquals("destinationFqdns"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    List<string> array = new List<string>();
                    foreach (var item in property.Value.EnumerateArray())
                    {
                        array.Add(item.GetString());
                    }
                    destinationFqdns = array;
                    continue;
                }
                if (property.NameEquals("sourceIpGroups"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    List<string> array = new List<string>();
                    foreach (var item in property.Value.EnumerateArray())
                    {
                        array.Add(item.GetString());
                    }
                    sourceIPGroups = array;
                    continue;
                }
                if (property.NameEquals("destinationIpGroups"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    List<string> array = new List<string>();
                    foreach (var item in property.Value.EnumerateArray())
                    {
                        array.Add(item.GetString());
                    }
                    destinationIPGroups = array;
                    continue;
                }
            }
            return new AzureFirewallNetworkRule(name.Value, description.Value, Optional.ToList(protocols), Optional.ToList(sourceAddresses), Optional.ToList(destinationAddresses), Optional.ToList(destinationPorts), Optional.ToList(destinationFqdns), Optional.ToList(sourceIPGroups), Optional.ToList(destinationIPGroups));
        }
    }
}


text:
namespace ash {
namespace {

DockedWindowLayoutManager* GetDockedLayoutManagerAtPoint(
    const gfx::Point& point) {
  gfx::Display display = ScreenUtil::FindDisplayContainingPoint(point);
  if (!display.is_valid())
    return NULL;
  aura::Window* root = Shell::GetInstance()
                           ->window_tree_host_manager()
                           ->GetRootWindowForDisplayId(display.id());
  aura::Window* dock_container = Shell::GetContainer(
      root, kShellWindowId_DockedContainer);
  return static_cast<DockedWindowLayoutManager*>(
      dock_container->layout_manager());
}

}  // namespace

DockedWindowResizer::~DockedWindowResizer() {
}

// static
DockedWindowResizer*
DockedWindowResizer::Create(WindowResizer* next_window_resizer,
                            wm::WindowState* window_state) {
  return new DockedWindowResizer(next_window_resizer, window_state);
}

void DockedWindowResizer::Drag(const gfx::Point& location, int event_flags) {
  last_location_ = location;
  ::wm::ConvertPointToScreen(GetTarget()->parent(), &last_location_);
  if (!did_move_or_resize_) {
    did_move_or_resize_ = true;
    StartedDragging();
  }
  gfx::Point offset;
  gfx::Rect bounds(CalculateBoundsForDrag(location));
  MaybeSnapToEdge(bounds, &offset);
  gfx::Point modified_location(location);
  modified_location.Offset(offset.x(), offset.y());

  base::WeakPtr<DockedWindowResizer> resizer(weak_ptr_factory_.GetWeakPtr());
  next_window_resizer_->Drag(modified_location, event_flags);
  if (!resizer)
    return;

  DockedWindowLayoutManager* new_dock_layout =
      GetDockedLayoutManagerAtPoint(last_location_);
  if (new_dock_layout && new_dock_layout != dock_layout_) {
    // The window is being dragged to a new display. If the previous
    // container is the current parent of the window it will be informed of
    // the end of drag when the window is reparented, otherwise let the
    // previous container know the drag is complete. If we told the
    // window's parent that the drag was complete it would begin
    // positioning the window.
    if (is_docked_ && dock_layout_->is_dragged_window_docked())
      dock_layout_->UndockDraggedWindow();
    if (dock_layout_ != initial_dock_layout_)
      dock_layout_->FinishDragging(
          DOCKED_ACTION_NONE,
          details().source == aura::client::WINDOW_MOVE_SOURCE_MOUSE ?
              DOCKED_ACTION_SOURCE_MOUSE : DOCKED_ACTION_SOURCE_TOUCH);
    is_docked_ = false;
    dock_layout_ = new_dock_layout;
    // The window's initial layout manager already knows that the drag is
    // in progress for this window.
    if (new_dock_layout != initial_dock_layout_)
      new_dock_layout->StartDragging(GetTarget());
  }
  // Window could get docked by the WorkspaceWindowResizer, update the state.
  is_docked_ = dock_layout_->is_dragged_window_docked();
  // Whenever a window is dragged out of the dock it will be auto-sized
  // in the dock if it gets docked again.
  if (!is_docked_)
    was_bounds_changed_by_user_ = false;
}

void DockedWindowResizer::CompleteDrag() {
  // The root window can change when dragging into a different screen.
  next_window_resizer_->CompleteDrag();
  FinishedDragging(aura::client::MOVE_SUCCESSFUL);
}

void DockedWindowResizer::RevertDrag() {
  next_window_resizer_->RevertDrag();
  // Restore docked state to what it was before the drag if necessary.
  if (is_docked_ != was_docked_) {
    is_docked_ = was_docked_;
    if (is_docked_)
      dock_layout_->DockDraggedWindow(GetTarget());
    else
      dock_layout_->UndockDraggedWindow();
  }
  FinishedDragging(aura::client::MOVE_CANCELED);
}

DockedWindowResizer::DockedWindowResizer(WindowResizer* next_window_resizer,
                                         wm::WindowState* window_state)
    : WindowResizer(window_state),
      next_window_resizer_(next_window_resizer),
      dock_layout_(NULL),
      initial_dock_layout_(NULL),
      did_move_or_resize_(false),
      was_docked_(false),
      is_docked_(false),
      was_bounds_changed_by_user_(window_state->bounds_changed_by_user()),
      weak_ptr_factory_(this) {
  DCHECK(details().is_resizable);
  aura::Window* dock_container = Shell::GetContainer(
      GetTarget()->GetRootWindow(),
      kShellWindowId_DockedContainer);
  dock_layout_ = static_cast<DockedWindowLayoutManager*>(
      dock_container->layout_manager());
  initial_dock_layout_ = dock_layout_;
  was_docked_ = GetTarget()->parent() == dock_container;
  is_docked_ = was_docked_;
}

void DockedWindowResizer::MaybeSnapToEdge(const gfx::Rect& bounds,
                                          gfx::Point* offset) {
  // Windows only snap magnetically when they were previously docked.
  if (!was_docked_)
    return;
  DockedAlignment dock_alignment = dock_layout_->CalculateAlignment();
  gfx::Rect dock_bounds = ScreenUtil::ConvertRectFromScreen(
      GetTarget()->parent(),
      dock_layout_->dock_container()->GetBoundsInScreen());

  // Short-range magnetism when retaining docked state. Same constant as in
  // MagnetismMatcher is used for consistency.
  const int kSnapToDockDistance = MagnetismMatcher::kMagneticDistance;

  if (dock_alignment == DOCKED_ALIGNMENT_LEFT ||
      dock_alignment == DOCKED_ALIGNMENT_NONE) {
    const int distance = bounds.x() - dock_bounds.x();
    if (distance < kSnapToDockDistance && distance > 0) {
      offset->set_x(-distance);
      return;
    }
  }
  if (dock_alignment == DOCKED_ALIGNMENT_RIGHT ||
      dock_alignment == DOCKED_ALIGNMENT_NONE) {
    const int distance = dock_bounds.right() - bounds.right();
    if (distance < kSnapToDockDistance && distance > 0)
      offset->set_x(distance);
  }
}

void DockedWindowResizer::StartedDragging() {
  // During resizing the window width is preserved by DockedwindowLayoutManager.
  if (is_docked_ &&
      (details().bounds_change & WindowResizer::kBoundsChange_Resizes)) {
    window_state_->set_bounds_changed_by_user(true);
  }

  // Tell the dock layout manager that we are dragging this window.
  // At this point we are not yet animating the window as it may not be
  // inside the docked area.
  dock_layout_->StartDragging(GetTarget());
  // Reparent workspace windows during the drag to elevate them above workspace.
  // Other windows for which the DockedWindowResizer is instantiated include
  // panels and windows that are already docked. Those do not need reparenting.
  if (GetTarget()->type() != ui::wm::WINDOW_TYPE_PANEL &&
      GetTarget()->parent()->id() == kShellWindowId_DefaultContainer) {
    // Reparent the window into the docked windows container in order to get it
    // on top of other docked windows.
    aura::Window* docked_container = Shell::GetContainer(
        GetTarget()->GetRootWindow(),
        kShellWindowId_DockedContainer);
    wm::ReparentChildWithTransientChildren(GetTarget(),
                                           GetTarget()->parent(),
                                           docked_container);
  }
  if (is_docked_)
    dock_layout_->DockDraggedWindow(GetTarget());
}

void DockedWindowResizer::FinishedDragging(
    aura::client::WindowMoveResult move_result) {
  if (!did_move_or_resize_)
    return;
  did_move_or_resize_ = false;
  aura::Window* window = GetTarget();
  const bool is_attached_panel = window->type() == ui::wm::WINDOW_TYPE_PANEL &&
                                 window_state_->panel_attached();
  const bool is_resized =
      (details().bounds_change & WindowResizer::kBoundsChange_Resizes) != 0;

  // Undock the window if it is not in the normal, docked or minimized state
  // type. This happens if a user snaps or maximizes a window using a
  // keyboard shortcut while it is being dragged.
  if (!window_state_->IsMinimized() && !window_state_->IsDocked() &&
      !window_state_->IsNormalStateType())
    is_docked_ = false;

  // When drag is completed the dragged docked window is resized to the bounds
  // calculated by the layout manager that conform to other docked windows.
  if (!is_attached_panel && is_docked_ && !is_resized) {
    gfx::Rect bounds = ScreenUtil::ConvertRectFromScreen(
        window->parent(), dock_layout_->dragged_bounds());
    if (!bounds.IsEmpty() && bounds.width() != window->bounds().width()) {
      window->SetBounds(bounds);
    }
  }
  // If a window has restore bounds, update the restore origin but not the size.
  // The size gets restored when a window is undocked.
  if (is_resized && is_docked_ && window_state_->HasRestoreBounds()) {
    gfx::Rect restore_bounds = window->GetBoundsInScreen();
    restore_bounds.set_size(window_state_->GetRestoreBoundsInScreen().size());
    window_state_->SetRestoreBoundsInScreen(restore_bounds);
  }

  // Check if the window needs to be docked or returned to workspace.
  DockedAction action = MaybeReparentWindowOnDragCompletion(is_resized,
                                                            is_attached_panel);
  dock_layout_->FinishDragging(
      move_result == aura::client::MOVE_CANCELED ? DOCKED_ACTION_NONE : action,
      details().source == aura::client::WINDOW_MOVE_SOURCE_MOUSE ?
          DOCKED_ACTION_SOURCE_MOUSE : DOCKED_ACTION_SOURCE_TOUCH);

  // If we started the drag in one root window and moved into another root
  // but then canceled the drag we may need to inform the original layout
  // manager that the drag is finished.
  if (initial_dock_layout_ != dock_layout_)
    initial_dock_layout_->FinishDragging(
        DOCKED_ACTION_NONE,
        details().source == aura::client::WINDOW_MOVE_SOURCE_MOUSE ?
            DOCKED_ACTION_SOURCE_MOUSE : DOCKED_ACTION_SOURCE_TOUCH);
  is_docked_ = false;
}

DockedAction DockedWindowResizer::MaybeReparentWindowOnDragCompletion(
    bool is_resized, bool is_attached_panel) {
  aura::Window* window = GetTarget();

  // Check if the window needs to be docked or returned to workspace.
  DockedAction action = DOCKED_ACTION_NONE;
  aura::Window* dock_container = Shell::GetContainer(
      window->GetRootWindow(),
      kShellWindowId_DockedContainer);
  if ((is_resized || !is_attached_panel) &&
      is_docked_ != (window->parent() == dock_container)) {
    if (is_docked_) {
      wm::ReparentChildWithTransientChildren(window,
                                             window->parent(),
                                             dock_container);
      action = DOCKED_ACTION_DOCK;
    } else if (window->parent()->id() == kShellWindowId_DockedContainer) {
      // Reparent the window back to workspace.
      // We need to be careful to give ParentWindowWithContext a location in
      // the right root window (matching the logic in DragWindowResizer) based
      // on which root window a mouse pointer is in. We want to undock into the
      // right screen near the edge of a multiscreen setup (based on where the
      // mouse is).
      gfx::Rect near_last_location(last_location_, gfx::Size());
      // Reparenting will cause Relayout and possible dock shrinking.
      aura::Window* previous_parent = window->parent();
      aura::client::ParentWindowWithContext(window, window, near_last_location);
      if (window->parent() != previous_parent) {
        wm::ReparentTransientChildrenOfChild(window,
                                             previous_parent,
                                             window->parent());
      }
      action = was_docked_ ? DOCKED_ACTION_UNDOCK : DOCKED_ACTION_NONE;
    }
  } else {
    // |action| is recorded in UMA and used to maintain |window_state_|.
    if (is_resized && is_docked_ && was_docked_)
      action = DOCKED_ACTION_RESIZE;
    else if (is_docked_ && was_docked_)
      action = DOCKED_ACTION_REORDER;
    else if (is_docked_ && !was_docked_)
      action = DOCKED_ACTION_DOCK;
    else if (!is_docked_ && was_docked_)
      action = DOCKED_ACTION_UNDOCK;
    else
      action = DOCKED_ACTION_NONE;
  }
  // When a window is newly docked it is auto-sized by docked layout adjusting
  // to other windows. If it is just dragged (but not resized) while being
  // docked it is auto-sized unless it has been resized while being docked
  // before.
  if (is_docked_) {
    wm::GetWindowState(window)->set_bounds_changed_by_user(
        was_docked_ && (is_resized || was_bounds_changed_by_user_));
  }

  if (action == DOCKED_ACTION_DOCK) {
    const wm::WMEvent event(wm::WM_EVENT_DOCK);
    window_state_->OnWMEvent(&event);
  } else if (wm::GetWindowState(window)->IsDocked() &&
             action == DOCKED_ACTION_UNDOCK) {
    const wm::WMEvent event(wm::WM_EVENT_NORMAL);
    window_state_->OnWMEvent(&event);
  }

  return action;
}

}  // namespace ash


text:
set(CMAKE_DEPENDS_LANGUAGES
  "C"
  "CXX"
  )
# The set of files for implicit dependencies of each language:
set(CMAKE_DEPENDS_CHECK_C
  "/home/alastar/projects/RakSyncWorker/minIni.c" "/home/alastar/projects/RakSyncWorker/build/CMakeFiles/raksyncworker.dir/minIni.c.o"
  )
set(CMAKE_C_COMPILER_ID "GNU")

# The include file search paths:
set(CMAKE_C_TARGET_INCLUDE_PATH
  "../Deps/RakNet/Source"
  "../Deps/bullet/src"
  )
set(CMAKE_DEPENDS_CHECK_CXX
  "/home/alastar/projects/RakSyncWorker/Client.cpp" "/home/alastar/projects/RakSyncWorker/build/CMakeFiles/raksyncworker.dir/Client.cpp.o"
  "/home/alastar/projects/RakSyncWorker/ConfigLoader.cpp" "/home/alastar/projects/RakSyncWorker/build/CMakeFiles/raksyncworker.dir/ConfigLoader.cpp.o"
  "/home/alastar/projects/RakSyncWorker/Entity.cpp" "/home/alastar/projects/RakSyncWorker/build/CMakeFiles/raksyncworker.dir/Entity.cpp.o"
  "/home/alastar/projects/RakSyncWorker/FileManager.cpp" "/home/alastar/projects/RakSyncWorker/build/CMakeFiles/raksyncworker.dir/FileManager.cpp.o"
  "/home/alastar/projects/RakSyncWorker/MotionState.cpp" "/home/alastar/projects/RakSyncWorker/build/CMakeFiles/raksyncworker.dir/MotionState.cpp.o"
  "/home/alastar/projects/RakSyncWorker/NetworkListener.cpp" "/home/alastar/projects/RakSyncWorker/build/CMakeFiles/raksyncworker.dir/NetworkListener.cpp.o"
  "/home/alastar/projects/RakSyncWorker/Room.cpp" "/home/alastar/projects/RakSyncWorker/build/CMakeFiles/raksyncworker.dir/Room.cpp.o"
  "/home/alastar/projects/RakSyncWorker/RoomProcessor.cpp" "/home/alastar/projects/RakSyncWorker/build/CMakeFiles/raksyncworker.dir/RoomProcessor.cpp.o"
  "/home/alastar/projects/RakSyncWorker/Server.cpp" "/home/alastar/projects/RakSyncWorker/build/CMakeFiles/raksyncworker.dir/Server.cpp.o"
  "/home/alastar/projects/RakSyncWorker/SyncWorker.cpp" "/home/alastar/projects/RakSyncWorker/build/CMakeFiles/raksyncworker.dir/SyncWorker.cpp.o"
  "/home/alastar/projects/RakSyncWorker/stdafx.cpp" "/home/alastar/projects/RakSyncWorker/build/CMakeFiles/raksyncworker.dir/stdafx.cpp.o"
  )
set(CMAKE_CXX_COMPILER_ID "GNU")

# The include file search paths:
set(CMAKE_CXX_TARGET_INCLUDE_PATH
  "../Deps/RakNet/Source"
  "../Deps/bullet/src"
  )

# Targets to which this target links.
set(CMAKE_TARGET_LINKED_INFO_FILES
  )


text:
import os
import sys
import transaction

from sqlalchemy import engine_from_config

from pyramid.paster import (
    get_appsettings,
    setup_logging,
    )

from pyramid.scripts.common import parse_vars

from ..models import (
    DBSession,
    #MyModel,
    User,
    Group,
    Base,
    Permission, Category, Item)

def usage(argv):
    cmd = os.path.basename(argv[0])
    print('usage: %s <config_uri> [var=value]\n'
          '(example: "%s development.ini")' % (cmd, cmd))
    sys.exit(1)

def main(argv=sys.argv):
    if len(argv) < 2:
        usage(argv)
    config_uri = argv[1]
    options = parse_vars(argv[2:])
    setup_logging(config_uri)
    settings = get_appsettings(config_uri, options=options)
    engine = engine_from_config(settings, 'sqlalchemy.')
    DBSession.configure(bind=engine)
    Base.metadata.create_all(engine)
    with transaction.manager:
        #model = MyModel(name='one', value=1)
        #DBSession.add(model)

        perm_item_manage = Permission()
        perm_item_manage.name = 'item'
        DBSession.add(perm_item_manage)

        perm_user_manage = Permission()
        perm_user_manage.name = 'user'
        DBSession.add(perm_user_manage)

        perm_order_manage = Permission()
        perm_order_manage.name = 'order'
        DBSession.add(perm_order_manage)

        gadmin = Group()
        gadmin.name = 'Administrators'
        gadmin.permissions.append(perm_item_manage)
        gadmin.permissions.append(perm_order_manage)
        gadmin.permissions.append(perm_user_manage)
        DBSession.add(gadmin)

        admin = User()
        admin.name = 'admin'
        admin.password = 'admin'
        admin.email = 'admin@localhost'
        admin.group = gadmin
        DBSession.add(admin)

        cat_food = Category()
        cat_food.name = 'Food'
        DBSession.add(cat_food)

        cat_fruit = Category()
        cat_fruit.name = 'Fruit'
        cat_fruit.parent = cat_food
        DBSession.add(cat_fruit)

        cat_vegetable = Category()
        cat_vegetable.name = 'Vegetable'
        cat_vegetable.parent = cat_food
        DBSession.add(cat_vegetable)

        iapple = Item()
        iapple.name = 'Apple'
        iapple.description = '
This is a red apple
'
        iapple.price = 1.3
        iapple.category = cat_fruit
        DBSession.add(iapple)


text:
package org.codegist.crest.serializer.primitive;

import org.codegist.crest.CRestConfig;

import static org.codegist.common.lang.Strings.isBlank;

/**
  * @author laurent.gilles@codegist.org
 */
public class BooleanPrimitiveDeserializer extends BooleanWrapperDeserializer {

    public BooleanPrimitiveDeserializer(CRestConfig crestConfig) {
        super(crestConfig);
    }

    /**
     * @inheritDoc
     */
    public Boolean deserialize(String value) {
        return isBlank(value) ? Boolean.FALSE : super.deserialize(value);
    }

}


text:
//---------------------------------------------------------------------
// <copyright file="BaseTest.cs" company="Microsoft">
//      Copyright (C) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
// </copyright>
//---------------------------------------------------------------------

namespace Microsoft.Test.OData.Framework.Reliability
{
    using Microsoft.Test.DataDriven;
    using Microsoft.VisualStudio.TestTools.UnitTesting;

    /// <summary>
    /// Base test class
    /// </summary>
    [TestClass]
    public class TestBase : DataDrivenTest
    {
        /// <summary>
        /// 'TestContext' is declared as a public property
        /// so that it can be accessed by the test harness;
        /// otherwise MSTest will not be able to manage the object.
        /// MSTest also requires this property be non-static.
        /// </summary>
        private TestContext testContext;

        /// <summary>
        /// Gets or sets test context
        /// </summary>
        public TestContext TestContext
        {
            get
            {
                return this.testContext;
            }

            set
            {
                this.testContext = value;
                TestConfig.LoadContextParameter(this.testContext.Properties);
                MsTestLogger.Attach(this.testContext);
            }
        }

        /// <summary>
        /// Test initialization
        /// </summary>
        [TestInitialize]
        public void BaseTestInit()
        {
            Log.StartTestCase(TestContext.TestName);
        }

        /// <summary>
        /// Test Cleanup
        /// </summary>
        [TestCleanup]
        public void BaseTestCleanUp()
        {
            Log.StopTestCase(TestContext.TestName);
        }
    }
}


text:
package org.apache.olio.workload.loader;

import com.sun.faban.driver.util.Random;
import org.apache.olio.workload.util.UserName;
import org.apache.olio.workload.util.RandomUtil;
import org.apache.olio.workload.util.ScaleFactors;
import org.apache.olio.workload.loader.framework.Loadable;
import org.apache.olio.workload.loader.framework.ThreadConnection;
import org.apache.olio.workload.loader.framework.ThreadResource;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Person loader
 */
public class Person extends Loadable {

    private static final String STATEMENT = "insert into PERSON (username, " +
            "password, firstname, lastname, email, telephone, imageurl, " +
            "imagethumburl, summary, timezone, ADDRESS_addressid)" +
            "values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
    static Logger logger = Logger.getLogger(Person.class.getName());

    String[] fields = new String[10];
    int addressId;

    public String getClearStatement() {
        return "truncate table PERSON";
    }

    public void prepare() {
        int id = getSequence();
        ++id;
        ThreadResource tr = ThreadResource.getInstance();
        Random r = tr.getRandom();
        StringBuilder b = tr.getBuffer();
        fields[0] = UserName.getUserName(id);
        fields[1] = String.valueOf(id);
        fields[2] = RandomUtil.randomName(r, b, 2, 12).toString();
        b.setLength(0);
        fields[3] = RandomUtil.randomName(r, b, 5, 15).toString();
        fields[4] = r.makeCString(3, 10);
        fields[4] = fields[2] + '_' + fields[3] + '@' + fields[4] + ".com";
        b.setLength(0);
        fields[5] = RandomUtil.randomPhone(r, b);
        fields[6] = "p" + id + ".jpg";
        fields[7] = "p" + id + "t.jpg";
        fields[8] = RandomUtil.randomText(r, 250, 2500);
        fields[9] = "PST";
        addressId = r.random(1, ScaleFactors.users);
    }

    public void load() {
        ThreadConnection c = ThreadConnection.getInstance();
        try {
            PreparedStatement s = c.prepareStatement(STATEMENT);
            for (int i = 0; i < fields.length; i++)
                s.setString(i + 1, fields[i]);
            s.setInt(11, addressId);
            c.addBatch();
        } catch (SQLException e) {
            logger.log(Level.SEVERE, e.getMessage(), e);
        }
    }
     /**
     * Update ID after all the data is loaded.
     * So we update the ID_GEN table at postload and add 1 to count.
     */
    public void postLoad() {
        ThreadConnection c = ThreadConnection.getInstance();
        try {
            //update id
             logger.fine("Updating Person ID");

             c.prepareStatement("INSERT INTO ID_GEN " +
                    "(GEN_KEY, GEN_VALUE) " +
                    "VALUES ('PERSON_ID', "+ ScaleFactors.users+1  + ")");
             c.executeUpdate();
        } catch (SQLException e) {
            logger.log(Level.SEVERE, e.getMessage(), e);
            //LoadController.increaseErrorCount();
        }

    }
}


text:
All notable changes to this project will be documented in this file.
This project adheres to [Semantic Versioning](http://semver.org/).

## [0.0.2] - 2015-04-26
### Added
- Babel.js classes support


text:
package com.apkplugin.android.service;

public class ProxyService2 extends BaseProxyService {

}


text:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE TS>
<TS version="2.0">
<context>
    <name>design/admin/popupmenu</name>
    <message>
        <source>Upload multiple files</source>
        <translation type="unfinished"></translation>
    </message>
</context>
<context>
    <name>extension/ezmultiupload</name>
    <message>
        <source>Multiupload</source>
        <translation>Multiupload</translation>
    </message>
    <message>
        <source>Error</source>
        <translation>Error</translation>
    </message>
    <message>
        <source>The files are uploaded to</source>
        <translation>Els arxius s'han penjat a</translation>
    </message>
    <message>
        <source>Select files</source>
        <translation>Selecciona els fitxers</translation>
    </message>
    <message>
        <source>Unable to load Flash content. You can download the latest version of Flash Player from the</source>
        <translation type="obsolete">No es pot carregar el contingut Flash. Pot descarregar l'última versió del Flash Player a</translation>
    </message>
    <message>
        <source>Adobe Flash Player Download Center</source>
        <translation type="obsolete">Centre de descàrregues d'Adobe Flash Player</translation>
    </message>
    <message>
        <source>All files received.</source>
        <translation>S'han rebut tots els arxius.</translation>
    </message>
    <message>
        <source>Thumbnail created.</source>
        <translation>S'ha creat el thumbnail (imatge en miniatura).</translation>
    </message>
    <message>
        <source>Starting...</source>
        <translation type="obsolete">Iniciant...</translation>
    </message>
    <message>
        <source>Cancel</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <source>Upload canceled.</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <source>Allowed Files</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <source>Could not load flash(or not loaded yet), this is needed for multiupload!</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <source>Javascript has been disabled, this is needed for multiupload!</source>
        <translation type="unfinished"></translation>
    </message>
</context>
</TS>


text:
package org.song.http.framework.ok;

import org.song.http.framework.ability.IHttpProgress;

import java.io.IOException;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import okio.Buffer;
import okio.BufferedSink;
import okio.ForwardingSink;
import okio.Okio;
import okio.Sink;

/**
 * Created by song on 2016/11/25
 * 添加了文件上传进度的RequestBody
 * 使用包装 唔...简洁多了 不用写实现
 */
public class RequestBodyProgress extends RequestBody {

    private IHttpProgress iHttpProgress;
    private RequestBody requestBody;
    private long len;
    private String mark;

    public RequestBodyProgress(RequestBody requestBody, IHttpProgress iHttpProgress, String key) {
        if (iHttpProgress == null)
            throw new IllegalArgumentException("IHttpProgress can not null");
        this.requestBody = requestBody;
        this.iHttpProgress = iHttpProgress;
        this.mark = key;
    }

    public RequestBodyProgress(RequestBody requestBody, IHttpProgress iHttpProgress) {
        this(requestBody, iHttpProgress, "up");
    }

    @Override
    public MediaType contentType() {
        return requestBody.contentType();
    }

    @Override
    public long contentLength() throws IOException {
        if (len != 0)
            return len;
        return len = requestBody.contentLength();
    }

    private BufferedSink bufferedSink;

    @Override
    public void writeTo(BufferedSink sink) throws IOException {
        if (bufferedSink == null) {
            bufferedSink = Okio.buffer(sink(sink));
        }
        requestBody.writeTo(bufferedSink);
        //必须调用flush,否则最后一部分数据可能不会被写入
        bufferedSink.flush();
    }

    //包装
    private Sink sink(Sink sink) {
        return new ForwardingSink(sink) {
            private long current;

            @Override
            public void write(Buffer source, long byteCount) throws IOException {
                super.write(source, byteCount);
                current += byteCount;
                iHttpProgress.onProgress(current, contentLength(), mark);
            }
        };
    }

}


text:
package org.lvu.adapters.SubAdapters.picture;

import android.content.Context;
import android.support.annotation.NonNull;
import android.view.View;
import android.view.ViewGroup;

import org.lvu.R;
import org.lvu.adapters.BasePictureListAdapter;
import org.lvu.models.Data;
import org.lvu.utils.HttpUtil;
import org.lvu.utils.ImmerseUtil;

import java.util.List;

/**
 * Created by wuyr on 6/23/16 6:16 PM.
 */
public class GifPictureAdapter extends EvilComicsAdapter {

    public GifPictureAdapter(Context context, int layoutId, List<Data> data) {
        super(context, layoutId, data);
    }

    @Override
    public BasePictureListAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        if (viewType == ITEM_TYPE_BOTTOM && ImmerseUtil.isAboveKITKAT()
                && ImmerseUtil.isHasNavigationBar(mContext))
            return new FooterHolder(mLayoutInflater.inflate(
                    R.layout.recycler_view_item_footer, parent, false));
        return new ViewHolder(mLayoutInflater.inflate(mLayoutId, parent, false));
    }

    @Override
    protected String getUrl() {
        return "http://www.lovefou.com/dongtaitu/";
    }

    @Override
    protected String getPageUrl() {
        return "http://www.lovefou.com/dongtaitu/list_%s.html";
    }

    @Override
    public void syncData(@NonNull String url) {
        if (url.isEmpty())
            url = URL;
        HttpUtil.getGifList(url, mSyncDataCallbackListener);
    }

    @Override
    public void loadNext() {
        if (mNextPageUrl == null || mNextPageUrl.isEmpty())
            syncData("");
        else
            HttpUtil.getGifList(mNextPageUrl, mLoadNextCallbackListener);
    }

    @Override
    public void loadPrevious() {
        int page = getCurrentPage() - 1;
        if (page <= 1) {
            syncData("");
            return;
        }
        String pageUrl = getPageUrl();
        HttpUtil.getGifList(String.format(pageUrl, String.valueOf(page)), mLoadPreviousCallbackListener);
    }

    @Override
    public void jumpToPage(int page) {
        if (page == 1)
            syncData("");
        else {
            String pageUrl = getPageUrl();
            HttpUtil.getGifList(String.format(pageUrl, String.valueOf(page)), mOnJumpPageCallbackListener);
        }
    }

    public static class ViewHolder extends BasePictureListAdapter.ViewHolder {

        private boolean isGifPlaying;

        public ViewHolder(View itemView) {
            super(itemView);
        }

        public boolean isGifPlaying() {
            return isGifPlaying;
        }

        public void setGifPlaying(boolean gifPlaying) {
            isGifPlaying = gifPlaying;
        }

    }
}


text:
"""
Query capability built on skew metamodel

tags_spec -> s3, elb, rds
"""
from __future__ import absolute_import, division, print_function, unicode_literals

import functools
import itertools
import jmespath
import json

import six
from botocore.client import ClientError
from concurrent.futures import as_completed

from c7n.actions import ActionRegistry
from c7n.filters import FilterRegistry, MetricsFilter
from c7n.tags import register_ec2_tags, register_universal_tags
from c7n.utils import (
    local_session, generate_arn, get_retry, chunks, camelResource)
from c7n.registry import PluginRegistry
from c7n.manager import ResourceManager

class ResourceQuery(object):

    def __init__(self, session_factory):
        self.session_factory = session_factory

    @staticmethod
    def resolve(resource_type):
        if not isinstance(resource_type, type):
            raise ValueError(resource_type)
        else:
            m = resource_type
        return m

    def _invoke_client_enum(self, client, enum_op, params, path):
        if client.can_paginate(enum_op):
            p = client.get_paginator(enum_op)
            results = p.paginate(**params)
            data = results.build_full_result()
        else:
            op = getattr(client, enum_op)
            data = op(**params)

        if path:
            path = jmespath.compile(path)
            data = path.search(data)

        return data

    def filter(self, resource_type, **params):
        """Query a set of resources."""
        m = self.resolve(resource_type)
        client = local_session(self.session_factory).client(
            m.service)
        enum_op, path, extra_args = m.enum_spec
        if extra_args:
            params.update(extra_args)
        return self._invoke_client_enum(client, enum_op, params, path) or []

    def get(self, resource_type, identities):
        """Get resources by identities
        """
        m = self.resolve(resource_type)
        params = {}
        client_filter = False

        # Try to formulate server side query
        if m.filter_name:
            if m.filter_type == 'list':
                params[m.filter_name] = identities
            elif m.filter_type == 'scalar':
                assert len(identities) == 1, "Scalar server side filter"
                params[m.filter_name] = identities[0]
        else:
            client_filter = True

        resources = self.filter(resource_type, **params)
        if client_filter:
            # This logic was added to prevent the issue from:
            # https://github.com/capitalone/cloud-custodian/issues/1398
            if all(map(lambda r: isinstance(r, six.string_types), resources)):
                resources = [r for r in resources if r in identities]
            else:
                resources = [r for r in resources if r[m.id] in identities]

        return resources

class ChildResourceQuery(ResourceQuery):
    """A resource query for resources that must be queried with parent information.

    Several resource types can only be queried in the context of their
    parents identifiers. ie. efs mount targets (parent efs), route53 resource
    records (parent hosted zone), ecs services (ecs cluster).
    """
    def __init__(self, session_factory, manager):
        self.session_factory = session_factory
        self.manager = manager

    def filter(self, resource_type, **params):
        """Query a set of resources."""
        m = self.resolve(resource_type)
        client = local_session(self.session_factory).client(m.service)

        enum_op, path, extra_args = m.enum_spec
        if extra_args:
            params.update(extra_args)

        parent_type, parent_key = m.parent_spec
        parents = self.manager.get_resource_manager(parent_type)
        parent_ids = [p[parents.resource_type.id] for p in parents.resources()]

        # Bail out with no parent ids...
        existing_param = parent_key in params
        if not existing_param and len(parent_ids) == 0:
            return []

        # Handle a query with parent id
        if existing_param:
            return self._invoke_client_enum(client, enum_op, params, path)

        # Have to query separately for each parent's children.
        results = []
        for parent_id in parent_ids:
            merged_params = dict(params, **{parent_key: parent_id})
            subset = self._invoke_client_enum(
                client, enum_op, merged_params, path)
            if subset:
                results.extend(subset)

        return results

class QueryMeta(type):

    def __new__(cls, name, parents, attrs):
        if 'resource_type' not in attrs:
            return super(QueryMeta, cls).__new__(cls, name, parents, attrs)

        if 'filter_registry' not in attrs:
            attrs['filter_registry'] = FilterRegistry(
                '%s.filters' % name.lower())
        if 'action_registry' not in attrs:
            attrs['action_registry'] = ActionRegistry(
                '%s.filters' % name.lower())

        if attrs['resource_type']:
            m = ResourceQuery.resolve(attrs['resource_type'])
            # Generic cloud watch metrics support
            if m.dimension:
                attrs['filter_registry'].register('metrics', MetricsFilter)
            # EC2 Service boilerplate ...
            if m.service == 'ec2':
                # Generic ec2 retry
                attrs['retry'] = staticmethod(get_retry((
                    'RequestLimitExceeded', 'Client.RequestLimitExceeded')))
                # Generic ec2 resource tag support
                if getattr(m, 'taggable', True):
                    register_ec2_tags(
                        attrs['filter_registry'], attrs['action_registry'])
            if getattr(m, 'universal_taggable', False):
                register_universal_tags(
                    attrs['filter_registry'], attrs['action_registry'])

        return super(QueryMeta, cls).__new__(cls, name, parents, attrs)

def _napi(op_name):
    return op_name.title().replace('_', '')

sources = PluginRegistry('sources')

@sources.register('describe')
class DescribeSource(object):

    def __init__(self, manager):
        self.manager = manager
        self.query = ResourceQuery(self.manager.session_factory)

    def get_resources(self, ids, cache=True):
        return self.query.get(self.manager.resource_type, ids)

    def resources(self, query):
        if self.manager.retry:
            resources = self.manager.retry(
                self.query.filter, self.manager.resource_type, **query)
        else:
            resources = self.query.filter(self.manager.resource_type, **query)
        return resources

    def get_permissions(self):
        m = self.manager.get_model()
        perms = ['%s:%s' % (m.service, _napi(m.enum_spec[0]))]
        if getattr(m, 'detail_spec', None):
            perms.append("%s:%s" % (m.service, _napi(m.detail_spec[0])))
        return perms

    def augment(self, resources):
        model = self.manager.get_model()
        if getattr(model, 'detail_spec', None):
            detail_spec = getattr(model, 'detail_spec', None)
            _augment = _scalar_augment
        elif getattr(model, 'batch_detail_spec', None):
            detail_spec = getattr(model, 'batch_detail_spec', None)
            _augment = _batch_augment
        else:
            return resources
        _augment = functools.partial(
            _augment, self.manager, model, detail_spec)
        with self.manager.executor_factory(
                max_workers=self.manager.max_workers) as w:
            results = list(w.map(
                _augment, chunks(resources, self.manager.chunk_size)))
            return list(itertools.chain(*results))

@sources.register('describe-child')
class ChildDescribeSource(DescribeSource):

    def __init__(self, manager):
        self.manager = manager
        self.query = ChildResourceQuery(
            self.manager.session_factory, self.manager)

@sources.register('config')
class ConfigSource(object):

    def __init__(self, manager):
        self.manager = manager

    def get_permissions(self):
        return ["config:GetResourceConfigHistory",
                "config:ListDiscoveredResources"]

    def get_resources(self, ids, cache=True):
        client = local_session(self.manager.session_factory).client('config')
        results = []
        m = self.manager.get_model()
        for i in ids:
            revisions = client.get_resource_config_history(
                resourceId=i,
                resourceType=m.config_type,
                limit=1).get('configurationItems')
            if not revisions:
                continue
            results.append(self.load_resource(revisions[0]))
        return results

    def load_resource(self, item):
        if isinstance(item['configuration'], six.string_types):
            item_config = json.loads(item['configuration'])
        else:
            item_config = item['configuration']
        return camelResource(item_config)

    def resources(self, query=None):
        client = local_session(self.manager.session_factory).client('config')
        paginator = client.get_paginator('list_discovered_resources')
        pages = paginator.paginate(
            resourceType=self.manager.get_model().config_type)
        results = []

        with self.manager.executor_factory(max_workers=5) as w:
            resource_ids = [
                r['resourceId'] for r in
                pages.build_full_result()['resourceIdentifiers']]
            self.manager.log.debug(
                "querying %d %s resources",
                len(resource_ids),
                self.manager.__class__.__name__.lower())

            for resource_set in chunks(resource_ids, 50):
                futures = []
                futures.append(w.submit(self.get_resources, resource_set))
                for f in as_completed(futures):
                    if f.exception():
                        self.manager.log.error(
                            "Exception getting resources from config \n %s" % (
                                f.exception()))
                    results.extend(f.result())
        return results

    def augment(self, resources):
        return resources

@six.add_metaclass(QueryMeta)
class QueryResourceManager(ResourceManager):

    resource_type = ""

    retry = None

    # TODO Check if we can move to describe source
    max_workers = 3
    chunk_size = 20

    permissions = ()

    _generate_arn = None

    def __init__(self, data, options):
        super(QueryResourceManager, self).__init__(data, options)
        self.source = self.get_source(self.source_type)

    @property
    def source_type(self):
        return self.data.get('source', 'describe')

    def get_source(self, source_type):
        return sources.get(source_type)(self)

    @classmethod
    def get_model(cls):
        return ResourceQuery.resolve(cls.resource_type)

    @classmethod
    def match_ids(cls, ids):
        """return ids that match this resource type's id format."""
        id_prefix = getattr(cls.get_model(), 'id_prefix', None)
        if id_prefix is not None:
            return [i for i in ids if i.startswith(id_prefix)]
        return ids

    def get_permissions(self):
        perms = self.source.get_permissions()
        if getattr(self, 'permissions', None):
            perms.extend(self.permissions)
        return perms

    def resources(self, query=None):
        key = {'region': self.config.region,
               'resource': str(self.__class__.__name__),
               'q': query}

        if self._cache.load():
            resources = self._cache.get(key)
            if resources is not None:
                self.log.debug("Using cached %s: %d" % (
                    "%s.%s" % (self.__class__.__module__,
                               self.__class__.__name__),
                    len(resources)))
                return self.filter_resources(resources)

        if query is None:
            query = {}

        resources = self.augment(self.source.resources(query))
        self._cache.save(key, resources)
        return self.filter_resources(resources)

    def get_resources(self, ids, cache=True):
        key = {'region': self.config.region,
               'resource': str(self.__class__.__name__),
               'q': None}
        if cache and self._cache.load():
            resources = self._cache.get(key)
            if resources is not None:
                self.log.debug("Using cached results for get_resources")
                m = self.get_model()
                id_set = set(ids)
                return [r for r in resources if r[m.id] in id_set]
        try:
            resources = self.augment(self.source.get_resources(ids))
            return resources
        except ClientError as e:
            self.log.warning("event ids not resolved: %s error:%s" % (ids, e))
            return []

    def augment(self, resources):
        """subclasses may want to augment resources with additional information.

        ie. we want tags by default (rds, elb), and policy, location, acl for
        s3 buckets.
        """
        return self.source.augment(resources)

    @property
    def account_id(self):
        """ Return the current account ID.

        This should now be passed in using the --account-id flag, but for a
        period of time we will support the old behavior of inferring this from
        IAM.
        """
        return self.config.account_id

    def get_arns(self, resources):
        arns = []
        for r in resources:
            _id = r[self.get_model().id]
            if 'arn' in _id[:3]:
                arns.append(_id)
            else:
                arns.append(self.generate_arn(_id))
        return arns

    @property
    def generate_arn(self):
        """ Generates generic arn if ID is not already arn format.
        """
        if self._generate_arn is None:
            self._generate_arn = functools.partial(
                generate_arn,
                self.get_model().service,
                region=self.config.region,
                account_id=self.account_id,
                resource_type=self.get_model().type,
                separator='/')
        return self._generate_arn

class ChildResourceManager(QueryResourceManager):

    @property
    def source_type(self):
        source = self.data.get('source', 'describe-child')
        if source == 'describe':
            source = 'describe-child'
        return source

def _batch_augment(manager, model, detail_spec, resource_set):
    detail_op, param_name, param_key, detail_path = detail_spec
    client = local_session(manager.session_factory).client(model.service)
    op = getattr(client, detail_op)
    if manager.retry:
        args = (op,)
        op = manager.retry
    else:
        args = ()
    kw = {param_name: [param_key and r[param_key] or r for r in resource_set]}
    response = op(*args, **kw)
    return response[detail_path]

def _scalar_augment(manager, model, detail_spec, resource_set):
    detail_op, param_name, param_key, detail_path = detail_spec
    client = local_session(manager.session_factory).client(model.service)
    op = getattr(client, detail_op)
    if manager.retry:
        args = (op,)
        op = manager.retry
    else:
        args = ()
    results = []
    for r in resource_set:
        kw = {param_name: param_key and r[param_key] or r}
        response = op(*args, **kw)
        if detail_path:
            response = response[detail_path]
        else:
            response.pop('ResponseMetadata')
        if param_key is None:
            response[model.id] = r
            r = response
        else:
            r.update(response)
        results.append(r)
    return results


text:
<?php //opening HTML
    $_TITLE_ = "Shopping Cart Editor - Alaska Wildflower Honey";
    $_STYLESHEETS_ = array("/assets/css/cartEditor.css", "/assets/css/fancyHRandButtons.css");
    require_once($_SERVER['DOCUMENT_ROOT'].'/assets/common/header.php');
    require_once($_SERVER['DOCUMENT_ROOT'].'/assets/php/ajax/cartEditorView.php');

    echo '
Your Shopping Cart
';

    if (empty($_SESSION))
    {
        echo '

                Oops! You seemed to have reached this page in error, as your cart is currently empty.

Please visit the Supplies page or the Bees page. Thanks!

';
    }
    else
    {
        //show editor view, and a simple nav button
        echo '
'.getEditorHTML().getEditorTotal().'

            <form action="/checkout/1cart_checkout.php">
                <input type="submit" class="fancy" value="Proceed to Checkout">
            </form>';
    }

    $_JS_ = array("/assets/js/jquery-ui-1.10.4.custom.min.js",
        "/assets/js/cartPreviewUpdater.js", "/assets/js/cartEditor.js");
    require_once($_SERVER['DOCUMENT_ROOT'].'/assets/common/footer.php'); //closing HTML
?>


text:
* {
  font-family: 'roboto', sans-serif;
}
.fix {
  overflow: hidden;
}
p {
  font-family: 'Roboto', sans-serif;
  font-weight: 300;
  font-size: 10pt;
  line-height: 17pt;
}
a {
  color: #ffffff;
}
.clear {
  clear: both;
}
.a1 {
  visibility: visible;
  -webkit-animation-delay: 0.1s;
  -moz-animation-delay: 0.1s;
  animation-delay: 0.1s;
}
.a2 {
  visibility: visible;
  -webkit-animation-delay: 0.2s;
  -moz-animation-delay: 0.2s;
  animation-delay: 0.2s;
}
.a3 {
  visibility: visible;
  -webkit-animation-delay: 0.3s;
  -moz-animation-delay: 0.3s;
  animation-delay: 0.3s;
}
.a4 {
  visibility: visible;
  -webkit-animation-delay: 0.4s;
  -moz-animation-delay: 0.4s;
  animation-delay: 0.4s;
}
.a5 {
  visibility: visible;
  animation-delay: 0.5s;
  -webkit-animation-delay: 0.5s;
  animation-name: fadeIn;
  -webkit-animation-name: fadeIn;
}
h2,
h3 {
  font-family: 'Roboto', sans-serif;
  font-weight: 500;
}
h2 {
  font-size: 22pt;
  line-height: 37pt;
  margin: 0px;
}
h3 {
  font-size: 14pt;
  line-height: 24pt;
}
h4 {
  font-size: 12pt;
  line-height: 20pt;
  opacity: 1;
}
h5 {
  font-size: 10pt;
  margin: 0px;
  padding: 0px;
  line-height: 15pt;
}
.fa {
  font-size: 22px;
}
body {
  background-color: #eae8e7;
  color: #767270;
  text-align: center;
}
.container {
  margin-top: 24px;
}
.sidebar {
  text-align: left;
  color: #ffffff;
  background-color: #26a69a;
  overflow: hidden;
  display: block;
}
.sidebar .heading {
  position: relative;
}
.sidebar .heading .feature-img {
  position: relative;
}
.sidebar .heading .feature-img img {
  width: 100%;
}
.sidebar .heading .button-collapse {
  display: block !important;
}
.sidebar .heading .nav-icon {
  position: absolute;
  top: 0;
  padding: 0 16px;
}
.sidebar .heading nav {
  background-color: initial;
  box-shadow: initial;
}
.sidebar .heading nav .button-collapse i {
  height: 30px;
  font-size: 18pt;
  line-height: 24pt;
  background-color: #5da4d9;
  margin-top: 20px;
  padding: 0px 6px;
}
.sidebar .heading nav .side-nav h3 {
  color: #5da4d9;
  padding: 0 15px;
}
.sidebar .heading nav .side-nav li a:hover {
  color: #5da4d9;
}
.sidebar .heading nav .side-nav li:hover {
  background-color: transparent !important;
}
.sidebar .heading .title {
  position: absolute;
  right: 11px;
  bottom: 46px;
}
.sidebar .heading .title span {
  margin-top: -5px;
  font-size: 10pt;
  margin: 0px;
  padding: 0px;
  line-height: 15pt;
}
.sidebar .icon {
  margin-top: 8px;
}
.sidebar .icon .fa {
  display: inherit;
  text-align: center;
}
.sidebar .sidebar-item {
  overflow: hidden;
  margin-top: 10px;
}
.sidebar .sidebar-item:first-child {
  margin-top: 30px;
}
.sidebar .section-item-details {
  padding-right: 26px;
  margin-bottom: 30px;
}
.sidebar .section-item-details p {
  margin: 0px;
}
.sidebar .info {
  border-bottom: 1px solid #fff;
  padding-left: 0px;
}
.sidebar .info span {
  opacity: 0.7;
  font-weight: 300;
}
.sidebar .personal {
  margin-bottom: 20px;
}
.sidebar .personal h4 {
  margin: 0px;
}
.sidebar .work h4 {
  margin-bottom: 0px;
}
.sidebar .address-details h4 {
  margin-top: 0px;
}
.sidebar .address-details h4 span {
  font-size: 10pt;
}
.sidebar .skill-line {
  padding-right: 30px;
  padding-left: 0px;
}
.sidebar .skill-line .progress {
  background-color: #36d1c2;
  height: 2px;
  overflow: visible;
}
.sidebar .skill-line .determinate {
  background-color: #ffffff;
}
.sidebar .skill-line .determinate .fa {
  font-size: 12px;
  position: absolute;
  top: -5px;
  right: 0px;
  margin-left: 50%;
}
.sidebar .skill-line h3 {
  margin-top: 0px;
  margin-bottom: 20px;
}
.sidebar .skill-line span {
  opacity: initial;
}
#section {
  overflow: hidden;
}
.section {
  padding-left: 32px !important;
  text-align: left;
}
.section .fa {
  text-align: center;
  display: block;
  font-size: 30pt;
}
.section .section-wrapper {
  background-color: #ffffff;
  overflow: hidden;
  margin-bottom: 24px;
  padding-bottom: 24px !important;
}
.section .section-wrapper .section-icon {
  margin-top: 40px;
}
.section .section-wrapper h2 {
  margin-top: 30px;
  margin-bottom: 25px;
}
.custom-content {
  padding-right: 0px !important;
}
.custom-content-wrapper {
  padding-right: 30px;
  margin-bottom: 25px;
  border-bottom: 1px solid #bdbdbd;
}
.custom-content-wrapper:last-child {
  border-bottom: initial;
}
.custom-content-wrapper h3 {
  margin: 0px;
  font-size: 12pt;
  line-height: 20pt;
}
.custom-content-wrapper h3 span {
  color: #767270;
}
.custom-content-wrapper span {
  color: #26a69a;
  margin-top: 0px;
  font-size: 10pt;
  line-height: 15pt;
}
.custom-content-wrapper p {
  margin-top: 0px;
  margin-bottom: 25px;
}
.interests ul {
  padding-left: 0px;
}
.interests ul li {
  list-style-type: none;
  display: inline-block;
  width: 19%;
}
.interests ul li .fa {
  color: #26a69a;
  text-align: left;
}


text:
using Microsoft.Extensions.Logging;

namespace Microsoft.AspNetCore.Cors;

internal static partial class CORSLoggerExtensions
{
    [LoggerMessage(1, LogLevel.Debug, "The request is a preflight request.", EventName = "IsPreflightRequest")]
    public static partial void IsPreflightRequest(this ILogger logger);

    [LoggerMessage(2, LogLevel.Debug, "The request has an origin header: '{origin}'.", EventName = "RequestHasOriginHeader")]
    public static partial void RequestHasOriginHeader(this ILogger logger, string origin);

    [LoggerMessage(3, LogLevel.Debug, "The request does not have an origin header.", EventName = "RequestDoesNotHaveOriginHeader")]
    public static partial void RequestDoesNotHaveOriginHeader(this ILogger logger);

    [LoggerMessage(4, LogLevel.Information, "CORS policy execution successful.", EventName = "PolicySuccess")]
    public static partial void PolicySuccess(this ILogger logger);

    [LoggerMessage(5, LogLevel.Information, "CORS policy execution failed.", EventName = "PolicyFailure")]
    public static partial void PolicyFailure(this ILogger logger);

    [LoggerMessage(6, LogLevel.Information, "Request origin {origin} does not have permission to access the resource.", EventName = "OriginNotAllowed")]
    public static partial void OriginNotAllowed(this ILogger logger, string origin);

    [LoggerMessage(7, LogLevel.Information, "Request method {accessControlRequestMethod} not allowed in CORS policy.", EventName = "AccessControlMethodNotAllowed")]
    public static partial void AccessControlMethodNotAllowed(this ILogger logger, string accessControlRequestMethod);

    [LoggerMessage(8, LogLevel.Information, "Request header '{requestHeader}' not allowed in CORS policy.", EventName = "RequestHeaderNotAllowed")]
    public static partial void RequestHeaderNotAllowed(this ILogger logger, string requestHeader);

    [LoggerMessage(9, LogLevel.Warning, "Failed to apply CORS Response headers.", EventName = "FailedToSetCorsHeaders")]
    public static partial void FailedToSetCorsHeaders(this ILogger logger, Exception? exception);

    [LoggerMessage(10, LogLevel.Information, "No CORS policy found for the specified request.", EventName = "NoCorsPolicyFound")]
    public static partial void NoCorsPolicyFound(this ILogger logger);

    [LoggerMessage(12, LogLevel.Debug, "This request uses the HTTP OPTIONS method but does not have an Access-Control-Request-Method header. This request will not be treated as a CORS preflight request.", EventName = "IsNotPreflightRequest")]
    public static partial void IsNotPreflightRequest(this ILogger logger);
}