text:
package streams

import common._

/**
 * This component implements the solver for the Bloxorz game
 */
trait Solver extends GameDef {

  /**
   * Returns `true` if the block `b` is at the final position
   */
  def done(b: Block): Boolean = b.b1 == goal && b.b2 == goal

  /**
   * This function takes two arguments: the current block `b` and
   * a list of moves `history` that was required to reach the
   * position of `b`.
   *
   * The `head` element of the `history` list is the latest move
   * that was executed, i.e. the last move that was performed for
   * the block to end up at position `b`.
   *
   * The function returns a stream of pairs: the first element of
   * the each pair is a neighboring block, and the second element
   * is the augmented history of moves required to reach this block.
   *
   * It should only return valid neighbors, i.e. block positions
   * that are inside the terrain.
   */
  def neighborsWithHistory(b: Block, history: List[Move]): Stream[(Block, List[Move])] =
    for {
      pair <- b.legalNeighbors.toStream
      (block, move) = pair
    } yield (block, move :: history)

  /**
   * This function returns the list of neighbors without the block
   * positions that have already been explored. We will use it to
   * make sure that we don't explore circular paths.
   */
  def newNeighborsOnly(neighbors: Stream[(Block, List[Move])],
                       explored: Set[Block]): Stream[(Block, List[Move])] =
    neighbors filter { case (b,_) => !(explored contains b) }

  /**
   * The function `from` returns the stream of all possible paths
   * that can be followed, starting at the `head` of the `initial`
   * stream.
   *
   * The blocks in the stream `initial` are sorted by ascending path
   * length: the block positions with the shortest paths (length of
   * move list) are at the head of the stream.
   *
   * The parameter `explored` is a set of block positions that have
   * been visited before, on the path to any of the blocks in the
   * stream `initial`. When search reaches a block that has already
   * been explored before, that position should not be included a
   * second time to avoid cycles.
   *
   * The resulting stream should be sorted by ascending path length,
   * i.e. the block positions that can be reached with the fewest
   * amount of moves should appear first in the stream.
   *
   * Note: the solution should not look at or compare the lengths
   * of different paths - the implementation should naturally
   * construct the correctly sorted stream.
   */
  def from(initial: Stream[(Block, List[Move])],
           explored: Set[Block]): Stream[(Block, List[Move])] = initial match {
    case Stream.Empty => initial
    case (b, history) #:: xs => {
      //println("block= " + b + ", length = " + history.length + ", moves= ["+ history.mkString(", ") +"]")
      val newlyExplored = explored + b
      val toVisit = newNeighborsOnly(neighborsWithHistory(b, history), newlyExplored)
      (b,history) #:: from(xs ++ toVisit, newlyExplored)
    }
  }

  /**
   * The stream of all paths that begin at the starting block.
   */
  lazy val pathsFromStart: Stream[(Block, List[Move])] = {
    val initial = (startBlock, List())
    from(List(initial).toStream, Set())
  }

  /**
   * Returns a stream of all possible pairs of the goal block along
   * with the history how it was reached.
   */
  lazy val pathsToGoal: Stream[(Block, List[Move])] =
    pathsFromStart filter {case (b,_) => done(b)}

  /**
   * The (or one of the) shortest sequence(s) of moves to reach the
   * goal. If the goal cannot be reached, the empty list is returned.
   *
   * Note: the `head` element of the returned list should represent
   * the first move that the player should perform from the starting
   * position.
   */
  lazy val solution: List[Move] = {
    val shortestSolution = pathsToGoal.take(10)
    shortestSolution match {
      case Stream.Empty => List()
      case (_, moves) #:: _ => moves.reverse
    }
  }
}


text:
require_relative 'dependencies'
module Inari
  module Cms
    class Engine < ::Rails::Engine
      config.i18n.load_path += Dir[Engine.root.join('config', 'locales', '**', '*.{rb,yml}').to_s]

      initializer :append_migrations do |app|
        unless app.root.to_s.match root.to_s
          config.paths['db/migrate'].expanded.each do |expanded_path|
            app.config.paths['db/migrate'] << expanded_path
          end

        end
      end

      Administrate::Engine.add_stylesheet "administrate/admin-custom"

      config.generators do |g|
        g.stylesheets false
        g.helper false
        g.javascripts false
        g.test_framework false, fixtures: false
        g.template_engine :slim
      end

      # http://edgeguides.rubyonrails.org/engines.html#overriding-models-and-controllers
      config.to_prepare do
        Dir.glob(Rails.root + 'app/decorators/**/*_decorator*.rb').each do |c|
          require_dependency(c)
        end
      end
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
package org.apache.sis.internal.metadata;

import java.util.Date;
import org.junit.Test;
import org.apache.sis.test.TestCase;

import static org.junit.Assert.*;

/**
 * Tests the {@link MetadataUtilities} class.
 *
 * @author  Martin Desruisseaux (Geomatys)
 * @version 0.4
 * @since   0.3
 * @module
 */
public final strictfp class MetadataUtilitiesTest extends TestCase {
    /**
     * Tests {@link MetadataUtilities#toMilliseconds(Date)}.
     */
    @Test
    public void testToMilliseconds() {
        assertEquals(1000,           MetadataUtilities.toMilliseconds(new Date(1000)));
        assertEquals(Long.MIN_VALUE, MetadataUtilities.toMilliseconds(null));
    }

    /**
     * Tests {@link MetadataUtilities#toDate(long)}.
     */
    @Test
    public void testToDate() {
        assertEquals(new Date(1000), MetadataUtilities.toDate(1000));
        assertNull(MetadataUtilities.toDate(Long.MIN_VALUE));
    }
}


text:
package org.batfish.datamodel;

import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertThat;

import org.junit.Test;

public class IpProtocolTest {

  @Test
  public void testFromString() {
    for (IpProtocol ipProtocol : IpProtocol.values()) {
      assertThat(IpProtocol.fromString(ipProtocol.name()), equalTo(ipProtocol));
    }
  }
}


text:
package game;

public interface PlayerMotionWatcher {
	public void playerMoved(float x, float y, float z, float angle, float y_angle,PlayerStats s); // angle in degree
}


text:
'use strict';

const React = require('react');

opaque type DoNotCommitUsageOfPureComponentDebug = {...};

/**
 * Identifies which prop or state changes triggered a re-render of a PureComponent. Usage:
 *
 * Change `extends React.PureComponent` to `extends PureComponentDebug` or inject it
 * everywhere by putting this line in your app setup:
 *
 *    React.PureComponent = require('PureComponentDebug');
 *
 * Should only be used for local testing, and will trigger a flow failure if you try to
 * commit any usages.
 */
class PureComponentDebug<
  P: DoNotCommitUsageOfPureComponentDebug,
  S: ?Object = void,
> extends React.Component<P, S> {
  shouldComponentUpdate(nextProps: P, nextState: S): boolean {
    const tag = this.constructor.name;
    let ret = false;
    const prevPropsKeys = Object.keys(this.props);
    const nextPropsKeys = Object.keys(nextProps);
    if (prevPropsKeys.length !== nextPropsKeys.length) {
      ret = true;
      console.warn(
        'PureComponentDebug: different prop keys',
        tag,
        prevPropsKeys.filter(key => !nextPropsKeys.includes(key)),
        nextPropsKeys.filter(key => !prevPropsKeys.includes(key)),
      );
    }
    const prevStateKeys = Object.keys(this.state || {});
    const nextStateKeys = Object.keys(nextState || {});
    if (prevStateKeys.length !== nextStateKeys.length) {
      ret = true;
      console.warn(
        'PureComponentDebug: different state keys',
        tag,
        prevStateKeys.filter(key => !nextStateKeys.includes(key)),
        nextStateKeys.filter(key => !prevStateKeys.includes(key)),
      );
    }
    for (const key in this.props) {
      if (this.props[key] !== nextProps[key]) {
        ret = true;
        console.warn('PureComponentDebug: different prop values', tag, key);
      }
    }
    for (const key in this.state) {
      if (this.state[key] !== (nextState || {})[key]) {
        ret = true;
        console.warn('PureComponentDebug: different state values', tag, key);
      }
    }
    return ret;
  }
}

module.exports = PureComponentDebug;


text:
var events = require('events')
  , util = require('util')
  , EventEmitter = events.EventEmitter;

/**
 * Hixie Sender implementation
 */

function Sender(socket) {
  this.socket = socket;
}

module.exports = Sender;

/**
 * Inherits from EventEmitter.
 */

util.inherits(Sender, events.EventEmitter);

/**
 * Frames and writes data.
 *
 * @api public
 */

Sender.prototype.send = function(data, options, cb) {
  if (options && options.binary) {
    this.error('hixie websockets do not support binary');
    return;
  }

  var length = Buffer.byteLength(data)
    , buffer = new Buffer(2 + length);

  buffer.write('\x00', 'binary');
  buffer.write(data, 1, 'utf8');
  buffer.write('\xff', 1 + length, 'binary');

  try {
    this.socket.write(buffer, 'binary', cb);
  } catch (e) {
    this.error(e.toString());
  }
}

/**
 * Sends a close instruction to the remote party.
 *
 * @api public
 */

Sender.prototype.close = function(code, data, mask, cb) {
  var buffer = new Buffer([0xff, 0x00]);
  try {
    this.socket.write(buffer, 'binary', cb);
  } catch (e) {
    this.error(e.toString());
  }
}

/**
 * Sends a ping message to the remote party. Not available for hixie.
 *
 * @api public
 */

Sender.prototype.ping = function(data, options) {}

/**
 * Sends a pong message to the remote party. Not available for hixie.
 *
 * @api public
 */

Sender.prototype.pong = function(data, options) {}

/**
 * Handles an error
 *
 * @api private
 */

Sender.prototype.error = function (reason) {
  this.emit('error', reason);
  return this;
}


text:
common-css:
  - "/css/bootstrap.min.css"
  - "/css/bootstrap-social.css"
  - "/css/main.css"
common-ext-css:
  - "//maxcdn.bootstrapcdn.com/font-awesome/4.6.0/css/font-awesome.min.css"
common-googlefonts:
  - "Lora:400,700,400italic,700italic"
  - "Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800"
common-js:
  - "/js/jquery-1.11.2.min.js"
  - "/js/bootstrap.min.js"
  - "/js/main.js"
---

<!DOCTYPE html>

  {% include head.html %}

    {% include gtm_body.html %}

    {% include nav.html %}

    {{ content }}

    {% include footer.html %}

    {% include footer-scripts.html %}


text:
FactoryGirl.define do
  factory :miq_schedule_worker, :parent => :miq_worker, :class => "MiqScheduleWorker"
end


text:
<?php

namespace Nlp\Tokenizer;

class WhitespaceTokenizerTest extends \PHPUnit_Framework_TestCase
{
    public function testTokenize()
    {
        $tokenizer = new WhitespaceTokenizer();
        $tokens = $tokenizer->tokenize("Hello world! My name's Alexey %) qwrqw123123");
        $this->assertEquals(Array
        (
            "Hello",
            "world!",
            "My",
            "name's",
            "Alexey",
            "%)",
            "qwrqw123123",
        ), $tokens);
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Ceratostomella capilliformis E. Bommer, M. Rousseau & Sacc.

### Remarks
null


text:
/*	Copyright (c) 1988 AT&T	*/
/*	  All Rights Reserved  	*/

#ifndef	_STORCLASS_H
#define	_STORCLASS_H

#pragma ident	"%Z%%M%	%I%	%E% SMI"	/* SVr4.0 1.6 */

#ifdef	__cplusplus
extern "C" {
#endif

/*
 *   STORAGE CLASSES
 */

#define	C_EFCN		-1	/* physical end of function */
#define	C_NULL		0
#define	C_AUTO		1	/* automatic variable */
#define	C_EXT		2	/* external symbol */
#define	C_STAT		3	/* static */
#define	C_REG		4	/* register variable */
#define	C_EXTDEF	5	/* external definition */
#define	C_LABEL		6	/* label */
#define	C_ULABEL	7	/* undefined label */
#define	C_MOS		8	/* member of structure */
#define	C_ARG		9	/* function argument */
#define	C_STRTAG	10	/* structure tag */
#define	C_MOU		11	/* member of union */
#define	C_UNTAG		12	/* union tag */
#define	C_TPDEF		13	/* type definition */
#define	C_USTATIC	14	/* undefined static */
#define	C_ENTAG		15	/* enumeration tag */
#define	C_MOE		16	/* member of enumeration */
#define	C_REGPARM	17	/* register parameter */
#define	C_FIELD		18	/* bit field */
#define	C_BLOCK		100	/* ".bb" or ".eb" */
#define	C_FCN		101	/* ".bf" or ".ef" */
#define	C_EOS		102	/* end of structure */
#define	C_FILE		103	/* file name */

/*
 * The following storage class is a "dummy" used only by STS
 * for line number entries reformatted as symbol table entries
 */

#define	C_LINE		104
#define	C_ALIAS	105	/* duplicate tag */
#define	C_HIDDEN	106	/* special storage class for external */
				/* symbols in dmert public libraries */
#define	 C_SHADOW	107	/* shadow symbol */

#ifdef	__cplusplus
}
#endif

#endif	/* _STORCLASS_H */


text:
package com.fireflysource.log;

/**
 * @author Pengtao Qiu
 */
public class Configuration {

    private String name;
    private String level;
    private String path;
    private boolean console;
    private long maxFileSize;
    private String charset;
    private String formatter;
    private String logNameFormatter;
    private String logFilter;
    private String maxSplitTime;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getLevel() {
        return level;
    }

    public void setLevel(String level) {
        this.level = level;
    }

    public String getPath() {
        return path;
    }

    public void setPath(String path) {
        this.path = path;
    }

    public boolean isConsole() {
        return console;
    }

    public void setConsole(boolean console) {
        this.console = console;
    }

    public long getMaxFileSize() {
        return maxFileSize;
    }

    public void setMaxFileSize(long maxFileSize) {
        this.maxFileSize = maxFileSize;
    }

    public String getCharset() {
        return charset;
    }

    public void setCharset(String charset) {
        this.charset = charset;
    }

    public String getFormatter() {
        return formatter;
    }

    public void setFormatter(String formatter) {
        this.formatter = formatter;
    }

    public String getLogNameFormatter() {
        return logNameFormatter;
    }

    public void setLogNameFormatter(String logNameFormatter) {
        this.logNameFormatter = logNameFormatter;
    }

    public String getLogFilter() {
        return logFilter;
    }

    public void setLogFilter(String logFilter) {
        this.logFilter = logFilter;
    }

    public String getMaxSplitTime() {
        return maxSplitTime;
    }

    public void setMaxSplitTime(String maxSplitTime) {
        this.maxSplitTime = maxSplitTime;
    }
}


text:
<?php

namespace Ogone;

interface PaymentResponse extends Response
{
    /**
     * @var int
     */
    const STATUS_INCOMPLETE_OR_INVALID = 0;
    /**
     * @var int
     */
    const STATUS_CANCELLED_BY_CLIENT = 1;
    /**
     * @var int
     */
    const STATUS_AUTHORISATION_REFUSED = 2;
    /**
     * @var int
     */
    const STATUS_AUTHORISED = 5;
    /**
     * @var int
     */
    const STATUS_AUTHORISED_AND_CANCELED = 6;
    /**
     * @var int
     */
    const STATUS_PAYMENT_DELETED = 7;
    /**
     * @var int
     */
    const STATUS_REFUND = 8;
    /**
     * @var int
     */
    const STATUS_PAYMENT_REQUESTED = 9;
    /**
     * @var int
     */
    const STATUS_AUTHORISATION_WAITING = 51;
    /**
     * @var int
     */
    const STATUS_AUTHORISATION_NOT_KNOWN = 52;
    /**
     * @var int
     */
    const STATUS_PAYMENT = 91;
    /**
     * @var int
     */
    const STATUS_PAYMENT_UNCERTAIN = 92;
    /**
     * @var int
     */
    const STATUS_PAYMENT_REFUSED = 93;

    /**
     * The authorisation deletion will be processed offline.
     *
     * @var int
     */
    const STATUS_PENDING_AUTHORISATION_CANCELLATION = 61;

    /**
     * A technical problem arose during the authorisation deletion process, giving an unpredictable result.
     *
     * The merchant can contact the acquirer helpdesk to establish the precise status of the payment or wait until we
     * have updated the status in our system.
     *
     * Usually NCERROR will contain a 200x error
     *
     * @var int
     */
    const STATUS_UNKNOWN_AUTHORISATION_CANCELLATION = 62;

    /**
     * A technical problem arose. Usually NCERROR will contain a 300x error
     *
     * @var int
     */
    const STATUS_DENIED_AUTHORISATION_CANCELLATION = 63;

    /**
     * Waiting for payment cancellation/deletion
     *
     * @var int
     */
    const STATUS_PENDING_PAYMENT_CANCELLATION = 71;

    /**
     * @var int
     */
    const STATUS_UNKNOWN_PAYMENT_CANCELLATION = 72;

    /**
     * @var int
     */
    const STATUS_DENIED_PAYMENT_CANCELLATION = 73;

    /**
     * @var int
     */
    const STATUS_PAYMENT_CANCELLED = 74;

    /**
     * Waiting for refund of the payment
     *
     * @var int
     */
    const STATUS_PENDING_REFUND = 81;

    /**
     * When the payment is set to paid manually
     * @var int
     */
    const STATUS_PAYMENT_BY_MERCHANT = 95;
}


text:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.astuetz.viewpager.extensions"
    android:versionCode="1"
    android:versionName="1.0" >
    <application />

</manifest>


text:
Title: Exercise 28
Date: 2017-04-18 3:42PM

[Today's exercise](https://learnpythonthehardway.org/book/ex28.html) is applying truth tables to statements to arrive at the boolean answers.

```
# Exercise 28
# https://learnpythonthehardway.org/book/ex28.html

print True and True  # True
print False and True  # False
print 1 == 1 and 2 == 1  # False
print "test" == "test"  # True
print 1 == 1 or 2 != 1  # True
print True and 1 == 1  # True
print False and 0 != 0  # False
print True or 1 == 1  # True
print "test" == "testing"  # False
print 1 != 0 and 2 == 1  # False
print "test" != "testing"  # True
print "test" == 1  # False
print not (True and False)  # True
print not (1 == 1 and 0 != 1)  # False
print not (10 == 1 or 1000 == 1000)  # False
print not (1 != 10 or 3 == 4)  # False
print not ("testing" == "testing" and "Zed" == "Cool Guy")  # True
print 1 == 1 and (not ("testing" == 1 or 1 == 0))  # True
print "chunky" == "bacon" and (not (3 == 4 or 3 == 3))  # False
print 3 == 3 and (not ("testing" == "testing" or "Python" == "Fun"))  # False
```

And evaluating each:

![Exercise 28]({filename}/images/ex28.png "Exercise 28")

Here are the [equality operators](https://docs.python.org/2/library/stdtypes.html#comparisons) from the study drill:

| Operation | Meaning |
| --------- | ------- |
| `<` | strictly less than |
| `<=` | less than or equal |
| `>` | strictly greater than |
| `>=` | greater than or equal |
| `==` | equal |
| `!=` | not equal |
| `is` | object identity |
| `is not` | negated object identity |

I'm a little surprised that there is no mention of "[truthiness](https://en.wikipedia.org/wiki/Truthiness)" in the exercise, but maybe that's a little advanced at the moment. If you study each of the statements, you'll notice that each was written as a comparison of equality rather than standalone truth tests.

For example, `1 == 1 and 2 == 1` or `"test" == "testing"` ultimately evaluates to `True` or `False`. But is `1`...`True`? Is `"test"`?

[Python's docs](https://docs.python.org/2/library/stdtypes.html#truth-value-testing) list what values are `False`:

- `None`
- `False` (duh)
- `0` (and zero equivalents in floats, etc.)
- `[]`
- `()`
- `''`

One of my favorites is a `datetime` object whose value is midnight. Objects are usually truthy, but [not so for midnight](https://lwn.net/Articles/590299/). Ruh roh.

```
>>> import datetime
>>> datetime.time(0, 0, 0) == True
False
```

 And guess what? It hasn't changed for Python 3! That ship has sailed!

![Truthiness]({filename}/images/truthiness.png "Truthiness")

I love it when developers debate semantics as interfaces with the world because it shows they're *just as much of a designer as a UX designer is*. Their medium just happens to be code. You wouldn't know it, but they want intuition as much as the next person.

> There's a great saying in the usability world: "You can't document your way out of a usability problem". What it means is that if all the affordances of your application (or programming language!) push users towards a particular logical conclusion (in this case, "datetime.time values are not numbers"), having a caveat in your documentation isn't going to help, because people aren't even going to think to ask the question. It doesn't matter if you originally had a good reason for the behaviour, you've ended up in a place where your behaviour is confusing and inconsistent, because there is one piece of behaviour that is out of line with an otherwise consistent mental model.


text:
#ifndef __CLHEPFL_H__
#define __CLHEPFL_H__

#include "padding.h"
#define LOCK_ALGORITHM "CLHEPFL"
#define NEED_CONTEXT 1
#define SUPPORT_WAITING 1

// CLHEPFL using standard interface from M.L.Scott

typedef struct clhepfl_node {
    volatile int spin __attribute__((aligned(L_CACHE_LINE_SIZE)));
    char __pad[pad_to_cache_line(sizeof(int))];
} clhepfl_node_t __attribute__((aligned(L_CACHE_LINE_SIZE)));

typedef struct clhepfl_mutex {
    clhepfl_node_t dummy __attribute__((aligned(L_CACHE_LINE_SIZE)));
    // clhepfl_node_t is cache aligned
    clhepfl_node_t *volatile head;
    clhepfl_node_t *volatile tail;
#if COND_VAR
    pthread_mutex_t posix_lock;
    char __pad[pad_to_cache_line(sizeof(clhepfl_node_t *) +
                                 sizeof(clhepfl_node_t *) +
                                 sizeof(pthread_mutex_t))];
#else
    char __pad[pad_to_cache_line(sizeof(clhepfl_node_t *) +
                                 sizeof(clhepfl_node_t *))];
#endif
} clhepfl_mutex_t __attribute__((aligned(L_CACHE_LINE_SIZE)));

typedef struct clhepfl_context {
    clhepfl_node_t initial;
    clhepfl_node_t *volatile current
        __attribute__((aligned(L_CACHE_LINE_SIZE)));
    char __pad[pad_to_cache_line(sizeof(clhepfl_node_t) +
                                 sizeof(clhepfl_node_t *))];
} clhepfl_context_t __attribute__((aligned(L_CACHE_LINE_SIZE)));

typedef pthread_cond_t clhepfl_cond_t;

clhepfl_mutex_t *clhepfl_mutex_create(const pthread_mutexattr_t *attr);
int clhepfl_mutex_lock(clhepfl_mutex_t *impl, clhepfl_context_t *me);
int clhepfl_mutex_trylock(clhepfl_mutex_t *impl, clhepfl_context_t *me);
void clhepfl_mutex_unlock(clhepfl_mutex_t *impl, clhepfl_context_t *me);
int clhepfl_mutex_destroy(clhepfl_mutex_t *lock);
int clhepfl_cond_init(clhepfl_cond_t *cond, const pthread_condattr_t *attr);
int clhepfl_cond_timedwait(clhepfl_cond_t *cond, clhepfl_mutex_t *lock,
                           clhepfl_context_t *me, const struct timespec *ts);
int clhepfl_cond_wait(clhepfl_cond_t *cond, clhepfl_mutex_t *lock,
                      clhepfl_context_t *me);
int clhepfl_cond_signal(clhepfl_cond_t *cond);
int clhepfl_cond_broadcast(clhepfl_cond_t *cond);
int clhepfl_cond_destroy(clhepfl_cond_t *cond);
void clhepfl_thread_start(void);
void clhepfl_thread_exit(void);
void clhepfl_application_init(void);
void clhepfl_application_exit(void);
void clhepfl_init_context(clhepfl_mutex_t *impl, clhepfl_context_t *context,
                          int number);

typedef clhepfl_mutex_t lock_mutex_t;
typedef clhepfl_context_t lock_context_t;
typedef clhepfl_cond_t lock_cond_t;

#define lock_mutex_create clhepfl_mutex_create
#define lock_mutex_lock clhepfl_mutex_lock
#define lock_mutex_trylock clhepfl_mutex_trylock
#define lock_mutex_unlock clhepfl_mutex_unlock
#define lock_mutex_destroy clhepfl_mutex_destroy
#define lock_cond_init clhepfl_cond_init
#define lock_cond_timedwait clhepfl_cond_timedwait
#define lock_cond_wait clhepfl_cond_wait
#define lock_cond_signal clhepfl_cond_signal
#define lock_cond_broadcast clhepfl_cond_broadcast
#define lock_cond_destroy clhepfl_cond_destroy
#define lock_thread_start clhepfl_thread_start
#define lock_thread_exit clhepfl_thread_exit
#define lock_application_init clhepfl_application_init
#define lock_application_exit clhepfl_application_exit
#define lock_init_context clhepfl_init_context

#endif // __CLHEPFL_H__


text:
package com.xiaogua.better.class_init;

import org.junit.Test;

public class TestFieldInitClass {

	@Test
	public void testFieldInitClass() {
		FieldInitClass test = new FieldInitClass();
		System.out.println(test.normal_a);
		System.out.println(test.final_c);
		System.out.println(FieldInitClass.static_b);
	}

	@Test
	public void testGetBaseField() {
		System.out.println("c=" + Sub_Extend_Base_Class.c);
	}

	@Test
	public void testBaseSetFieldValue() {
		System.out.println("before set value,c=" + Sub_Extend_Base_Class.c);
		Sub_Extend_Base_Class.c = '8';
		System.out.println("after set value,c=" + Sub_Extend_Base_Class.c);
	}

	@Test
	public void testNewBaseFieldInitClass() {
		Sub_Extend_Base_Class.c = '8';
		System.out.println(Sub_Extend_Base_Class.c);
		System.out.println("----------before new class--------------------");
		new Sub_Extend_Base_Class();
		System.out.println(Sub_Extend_Base_Class.c);
	}
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
edu.cmu.cs.stage3.alice.core.response.set
</TITLE>

<META NAME="date" CONTENT="2011-12-11">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../../../stylesheet.css" TITLE="Style">

edu.cmu.cs.stage3.alice.core.response.set

Classes

Add

Remove

SetItemResponse

SetResponse


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/colorPrimary"
    >
  <RelativeLayout
      android:id="@+id/toolbar"
      android:layout_width="match_parent"
      android:layout_height="?android:actionBarSize"
      android:background="@color/colorToolbar"
      android:padding="16dp"
      >
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:text="@string/country_picker"
        android:textAlignment="center"
        android:textColor="@android:color/white"
        android:textStyle="bold"
        />
  </RelativeLayout>
  <ScrollView
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:layout_below="@+id/toolbar"
      >
    <LinearLayout
        android:id="@+id/detail_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        >
      <LinearLayout
          android:layout_width="match_parent"
          android:layout_height="wrap_content"
          android:paddingBottom="8dp"
          android:paddingEnd="16dp"
          android:paddingStart="16dp"
          android:paddingTop="8dp"
          >
        <TextView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="@string/new_theme"
            android:textColor="@android:color/white"
            />
        <androidx.appcompat.widget.SwitchCompat
            android:id="@+id/theme_toggle_switch"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            />
      </LinearLayout>
      <LinearLayout
          android:layout_width="match_parent"
          android:layout_height="wrap_content"
          android:paddingBottom="8dp"
          android:paddingEnd="16dp"
          android:paddingStart="16dp"
          android:paddingTop="8dp"
          >
        <TextView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="@string/custom_style"
            android:textColor="@android:color/white"
            />
        <androidx.appcompat.widget.SwitchCompat
            android:id="@+id/custom_style_toggle_switch"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            />
      </LinearLayout>
      <LinearLayout
          android:layout_width="match_parent"
          android:layout_height="wrap_content"
          android:paddingBottom="8dp"
          android:paddingEnd="16dp"
          android:paddingStart="16dp"
          android:paddingTop="8dp"
          >
        <TextView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="@string/use_bottom_sheet"
            android:textColor="@android:color/white"
            />
        <androidx.appcompat.widget.SwitchCompat
            android:id="@+id/bottom_sheet_switch"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            />
      </LinearLayout>
      <LinearLayout
          android:layout_width="match_parent"
          android:layout_height="wrap_content"
          android:paddingBottom="8dp"
          android:paddingEnd="16dp"
          android:paddingStart="16dp"
          android:paddingTop="8dp"
          >
        <TextView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="@string/allow_search"
            android:textColor="@android:color/white"
            />
        <androidx.appcompat.widget.SwitchCompat
            android:id="@+id/search_switch"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            />
      </LinearLayout>
      <LinearLayout
          android:layout_width="match_parent"
          android:layout_height="wrap_content"
          android:orientation="vertical"
          android:paddingBottom="8dp"
          android:paddingEnd="16dp"
          android:paddingStart="16dp"
          android:paddingTop="8dp"
          >
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/sort_by"
            android:textColor="@android:color/white"
            />
        <RadioGroup
            android:id="@+id/sort_by_radio_group"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            >
          <RadioButton
              android:id="@+id/none_radio_button"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:buttonTint="@android:color/white"
              android:checked="true"
              android:text="@string/none_default"
              android:textColor="@android:color/white"
              />
          <RadioButton
              android:id="@+id/name_radio_button"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:buttonTint="@android:color/white"
              android:text="@string/name"
              android:textColor="@android:color/white"
              />
          <RadioButton
              android:id="@+id/dial_code_radio_button"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:buttonTint="@android:color/white"
              android:text="@string/dial_code"
              android:textColor="@android:color/white"
              />
          <RadioButton
              android:id="@+id/iso_radio_button"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:buttonTint="@android:color/white"
              android:text="@string/iso_code"
              android:textColor="@android:color/white"
              />
        </RadioGroup>
      </LinearLayout>
      <LinearLayout
          android:layout_width="match_parent"
          android:layout_height="match_parent"
          android:layout_marginTop="8dp"
          android:orientation="horizontal"
          >
        <Button
            android:id="@+id/by_name_button"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_marginEnd="4dp"
            android:layout_weight="1"
            android:background="@color/colorAccent"
            android:paddingEnd="16dp"
            android:paddingStart="16dp"
            android:text="@string/get_country_by_name"
            android:textColor="@android:color/white"
            />
        <Button
            android:id="@+id/by_sim_button"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_marginStart="4dp"
            android:layout_weight="1"
            android:background="@color/colorAccent"
            android:paddingEnd="16dp"
            android:paddingStart="16dp"
            android:text="@string/get_country_by_sim"
            android:textColor="@android:color/white"
            />
      </LinearLayout>
      <LinearLayout
          android:layout_width="match_parent"
          android:layout_height="match_parent"
          android:layout_marginTop="8dp"
          android:orientation="horizontal"
          >
        <Button
            android:id="@+id/by_local_button"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_marginEnd="4dp"
            android:layout_weight="1"
            android:background="@color/colorAccent"
            android:paddingEnd="16dp"
            android:paddingStart="16dp"
            android:text="@string/get_country_by_local"
            android:textColor="@android:color/white"
            />
        <Button
            android:id="@+id/by_iso_button"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_marginStart="4dp"
            android:layout_weight="1"
            android:background="@color/colorAccent"
            android:paddingEnd="16dp"
            android:paddingStart="16dp"
            android:text="@string/get_country_by_iso"
            android:textColor="@android:color/white"
            />
      </LinearLayout>
      <Button
          android:id="@+id/country_picker_button"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:layout_gravity="center"
          android:layout_marginTop="8dp"
          android:background="@color/colorAccent"
          android:paddingEnd="16dp"
          android:paddingStart="16dp"
          android:text="@string/pick_country"
          android:textColor="@android:color/white"
          />
    </LinearLayout>
  </ScrollView>

</RelativeLayout>


text:
class MountPathingGoal : public Goal
{
public:
	MountPathingGoal(Mob *, float, float, bool);
	virtual ~MountPathingGoal();
	virtual bool canUse();
	virtual bool canContinueToUse();
	virtual void start();
	virtual void stop();
	virtual void tick();
	virtual void getAttackReachSqr();
};


text:
require 'test_helper'
require 'generators/emailvision4rails/setup_generator'

class SetupGeneratorTest < Rails::Generators::TestCase
  tests Emailvision4rails::SetupGenerator

  destination File.join(Rails.root, "tmp")
  setup :prepare_destination

  def test_setup_generator
    run_generator
    assert_file "config/emailvision.yml"
  end
end


text:
export class GithubContributorService {
  constructor ($log, $http) {
    'ngInject'

    this.$log = $log
    this.$http = $http
    this.apiHost = 'https://api.github.com/repos/Swiip/generator-gulp-angular'
  }

  getContributors (limit = 30) {
    return this.$http.get(this.apiHost + '/contributors?per_page=' + limit)
      .then((response) => {
        return response.data
      })
      .catch((error) => {
        this.$log.error('XHR Failed for getContributors.\n' + angular.toJson(error.data, true))
      })
  }
}


text:
/* global angular,ApplicationConfiguration,_, moment */
'use strict';

angular.module('core')
 .service('Events', ['$http', '$q', 'Auth',
    function ($http, $q, Auth) {
      function calculateAttendees(event) {
        event.attending = [];
        event.notResponded = [];
        event.declined = [];
        // the creator is attending.
        event.attending.push({
          name: event.creator.name,
          phoneNumber: event.creator.phoneNumber,
          inviteOn: event.created,
          repliedOn: event.created,
          created: true
        });
        _.each(event.invited, function(invitee) {
          if (invitee.status === 'accepted') {
            event.attending.push(invitee);
          } else if (invitee.statue === 'declined') {
            event.declined.push(invitee);
          } else {
            event.notResponded.push(invitee);
          }
        });
        return event;
      }
      function nextMonday8pm() {
        return moment().day(8).hours(20).minutes(0).seconds(0).milliseconds(0);
      }
      this.createOrUpdateAndInvite = function(eid, messages) {
        if (eid === 'new') {
          return this.createAndInvite(messages);
        } else {
          return this.addInvited(eid, messages);
        }
      };
      function buildInvited(messages) {
        return [
          {
            name : messages[0].name,
            phoneNumber: messages[0].phoneNumber,
            message : messages[0].message,
            status: 'invited',
            invitedOn: new Date(),
            invitedBy: Auth.user._id
          },
          {
            name : messages[1].name,
            phoneNumber: messages[1].phoneNumber,
            message : messages[1].message,
            status: 'invited',
            invitedOn: new Date(),
            invitedBy: Auth.user._id
          }
        ];
      }
      this.createAndInvite = function(messages) {
        var event = {
          invited: buildInvited(messages),
          creator: Auth.user._id,
          when: nextMonday8pm()
        };
        var url = ApplicationConfiguration.baseUrl + '/auth/event/createAndInvite';
        return $http.post(url, event, {headers: {'X-Device-UUID':Auth.user.uuid}}).then(function (res) {
          return res.data;
        });
      };
      this.addInvited = function(eid, messages) {
        var invited = buildInvited(messages);
        var url = ApplicationConfiguration.baseUrl + '/auth/event/addInvited/'+eid;
        return $http.post(url, invited, {headers: {'X-Device-UUID':Auth.user.uuid}}).then(function (res) {
          return calculateAttendees(res.data.event);
        });
      };
      this.all = function(eid) {
        var url = ApplicationConfiguration.baseUrl + '/auth/event/all';
        return $http.get(url, {headers: {'X-Device-UUID':Auth.user.uuid}}).then(function (res) {
          return res.data;
        });
      };
      this.get = function(eid) {
        var url = ApplicationConfiguration.baseUrl + '/auth/event/get/'+eid;
        return $http.get(url, {headers: {'X-Device-UUID':Auth.user.uuid}}).then(function (res) {
          return calculateAttendees(res.data.event);
        });
      };
      this.getAnon = function(eid, inviteCode) {
        var url = ApplicationConfiguration.baseUrl + '/event/get/'+eid+'/'+inviteCode;
        return $http.get(url).then(function (res) {
          return res.data;
        });
      };
  }]);


text:
class AddEditedAtToPosts < ActiveRecord::Migration
  def self.up
    add_column "posts", "edited_at", :datetime
  end

  def self.down
    remove_column "posts", "edited_at"
  end
end


text:
package com.mycompany.app.bean;

import java.util.Date;

/**
 * Created with IntelliJ IDEA.
 * User: pc2
 * Date: 16-1-6
 * Time: 下午3:41
 * To change this template use File | Settings | File Templates.
 */
public class User {
    private long id;
    private String userName;
    private String nickName;
    private int age;
    private double salary;
    private Date birthday;

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getNickName() {
        return nickName;
    }

    public void setNickName(String nickName) {
        this.nickName = nickName;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public double getSalary() {
        return salary;
    }

    public void setSalary(double salary) {
        this.salary = salary;
    }

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", userName='" + userName + '\'' +
                ", nickName='" + nickName + '\'' +
                ", age=" + age +
                ", salary=" + salary +
                ", birthday=" + birthday +
                '}';
    }
}


text:
/*
 * Core initialization routines.
 */

#include <config/version.h>
#include <config/release.h>
#include <config/enable_nls.h>
#include <config/localedir.h>
#include <config/ag_network.h>
#include <config/ag_threads.h>
#include <config/have_gettimeofday.h>
#include <config/have_select.h>
#include <config/have_cygwin.h>
#include <config/have_clock_gettime.h>

#ifdef AG_THREADS
#include <config/have_pthreads_xopen.h>
#include <config/have_pthread_mutex_recursive.h>
#include <config/have_pthread_mutex_recursive_np.h>
#endif

#include "core.h"
#include "config.h"
#include "dso.h"
#ifdef AG_NETWORK
#include "rcs.h"
#endif

#include <stdio.h>
#include <stdlib.h>
#ifndef _WIN32
#include <unistd.h>
#endif

#ifdef AG_THREADS
pthread_mutexattr_t agRecursiveMutexAttr;	/* Recursive mutex attributes */
#endif

AG_Config *agConfig;				/* Global Agar config data */
void (*agAtexitFunc)(void) = NULL;		/* User exit function */
void (*agAtexitFuncEv)(AG_Event *) = NULL;	/* User exit handler */
char *agProgName = NULL;			/* User program name */

int agVerbose = 0;		/* Verbose console output */
int agTerminating = 0;		/* Application is exiting */

int
AG_InitCore(const char *progname, Uint flags)
{
	if (flags & AG_VERBOSE)
		agVerbose = 1;

	if ((agProgName = TryStrdup(progname)) == NULL)
		return (-1);

#ifdef ENABLE_NLS
	bindtextdomain("agar", LOCALEDIR);
	bind_textdomain_codeset("agar", "UTF-8");
	textdomain("agar");
#endif

	AG_InitError();
	AG_GetCPUInfo(&agCPU);

#ifdef AG_THREADS
#ifdef _XBOX
	ptw32_processInitialize();
#endif
	pthread_mutexattr_init(&agRecursiveMutexAttr);
# if defined(HAVE_PTHREAD_MUTEX_RECURSIVE_NP)
	pthread_mutexattr_settype(&agRecursiveMutexAttr,
	    PTHREAD_MUTEX_RECURSIVE_NP);
# else
	pthread_mutexattr_settype(&agRecursiveMutexAttr,
	    PTHREAD_MUTEX_RECURSIVE);
# endif
	AG_MutexInitRecursive(&agDSOLock);
#endif /* AG_THREADS */

	AG_InitClassTbl();
	AG_RegisterClass(&agConfigClass);
	AG_RegisterClass(&agDbObjectClass);
	AG_RegisterClass(&agDbClass);

#if defined(HAVE_GETTIMEOFDAY) && !defined(HAVE_CYGWIN)
# if defined(AG_THREADS) && defined(HAVE_CLOCK_GETTIME)
	AG_SetTimeOps(&agTimeOps_condwait);
# else
#  if defined(HAVE_SELECT)
	AG_SetTimeOps(&agTimeOps_gettimeofday);
#  endif
# endif
#elif defined(_WIN32)
	AG_SetTimeOps(&agTimeOps_win32);
#else
	AG_SetTimeOps(&agTimeOps_dummy);
#endif

	AG_InitTimeouts();
	AG_DataSourceInitSubsystem();

	if ((agConfig = TryMalloc(sizeof(AG_Config))) == NULL) {
		return (-1);
	}
	if (AG_ConfigInit(agConfig, flags) == -1) {
		return (-1);
	}
	if (!(flags & AG_NO_CFG_AUTOLOAD)) {
		(void)AG_ConfigLoad();
	}
#ifdef AG_NETWORK
	AG_InitNetwork(0);
#endif
	return (0);
}

#ifdef AG_NETWORK
int
AG_InitNetwork(Uint flags)
{
	AG_RcsInit();
	return (0);
}
#endif /* AG_NETWORK */

/* Register a function to invoke in AG_Quit(). */
void
AG_AtExitFunc(void (*func)(void))
{
	agAtexitFunc = func;
}

void
AG_AtExitFuncEv(void (*func)(AG_Event *))
{
	agAtexitFuncEv = func;
}

/* Immediately terminate the application. */
void
AG_Quit(void)
{
	AG_Destroy();
	exit(0);
}

/* Clean up the resources allocated by Agar-Core. */
void
AG_Destroy(void)
{
	if (agAtexitFunc != NULL) { agAtexitFunc(); }
	if (agAtexitFuncEv != NULL) { agAtexitFuncEv(NULL); }

#ifdef AG_NETWORK
	AG_RcsDestroy();
#endif
	AG_ObjectDestroy(agConfig);
	AG_DataSourceDestroySubsystem();

	AG_DestroyTimeouts();
	AG_DestroyError();
	AG_DestroyClassTbl();
	Free(agProgName);
}

void
AG_GetVersion(AG_AgarVersion *ver)
{
	ver->major = AGAR_MAJOR_VERSION;
	ver->minor = AGAR_MINOR_VERSION;
	ver->patch = AGAR_PATCHLEVEL;
	ver->release = RELEASE;
}


text:
module.exports = function(kernelP) {
  return (function() {

    var Utils = require('../../utils.js');

    var gKernelP = kernelP;

    var GeneralizedLinearRegressionSummary = require('./GeneralizedLinearRegressionSummary')();

    /**
     * @classdesc
     * :: Experimental ::
     * Summary of {@link GeneralizedLinearRegression} fitting and model.
     *
     * @param dataset Dataset to be summarized.
     * @param origModel Model to be summarized.  This is copied to create an internal
     *                  model which cannot be modified from outside.
     * @param diagInvAtWA diagonal of matrix (A^T * W * A)^-1 in the last iteration
     * @param numIterations number of iterations
     * @param solver the solver algorithm used for model training
     * @class
     * @memberof module:eclairjs/ml/regression
     * @extends module:eclairjs/ml/regression.GeneralizedLinearRegressionTrainingSummary
     */
    function GeneralizedLinearRegressionTrainingSummary(kernelP, refIdP) {
        Utils.handleConstructor(this, arguments, gKernelP);
    };

    GeneralizedLinearRegressionTrainingSummary.prototype = Object.create(GeneralizedLinearRegressionSummary.prototype);

    GeneralizedLinearRegressionTrainingSummary.prototype.constructor = GeneralizedLinearRegressionTrainingSummary;

    /**
     * An immutable unique ID for the object and its derivatives.
     * @returns {Promise.<string>}
     */
    GeneralizedLinearRegressionTrainingSummary.prototype.uid = function () {
      var args = {
        target: this,
        method: 'uid',
        args: Utils.wrapArguments(arguments),
        returnType: String
      };

      return Utils.generate(args);
    };

    /**
     * Standard error of estimated coefficients and intercept.
     * @returns {Promise.<number[]>}
     */
    GeneralizedLinearRegressionTrainingSummary.prototype.coefficientStandardErrors = function () {
      var args = {
        target: this,
        method: 'coefficientStandardErrors',
        args: Utils.wrapArguments(arguments),
        returnType: [Number]
      };

      return Utils.generate(args);
    };

    /**
     * T-statistic of estimated coefficients and intercept.
     * @returns {Promise.<number[]>}
     */
    GeneralizedLinearRegressionTrainingSummary.prototype.tValues = function () {
      var args = {
        target: this,
        method: 'tValues',
        args: Utils.wrapArguments(arguments),
        returnType: [Number]
      };

      return Utils.generate(args);
    };

    /**
     * Two-sided p-value of estimated coefficients and intercept.
     * @returns {Promise.<number[]>}
     */
    GeneralizedLinearRegressionTrainingSummary.prototype.pValues = function () {
      var args = {
        target: this,
        method: 'pValues',
        args: Utils.wrapArguments(arguments),
        returnType: [Number]
      };

      return Utils.generate(args);
    };

    GeneralizedLinearRegressionTrainingSummary.moduleLocation = '/ml/regression/GeneralizedLinearRegressionTrainingSummary';

    return GeneralizedLinearRegressionTrainingSummary;
  })();
};


text:
[BOOST 1.53](http://sourceforge.net/projects/boost/files/boost/1.53.0/) is required. You can use newer versions too,
but you have to change include dir path in projects properties.

1. Download this archive and extract it into the dir `boost_1_53_0` on the same level as project source folder to
   obtain this dirs structure:

   ```bash
   boost_1_53_0        # BOOST sources root (boost, doc, libs, etc. folders)
   <your_project_dir>  # Folder for your new project
   TagGame             # mango2d demo project source dir (optional)
   GemsGame            # mango2d demo project source dir (optional)
   ```

2. Launch `bootstrap.bat` for Windows and `bootstrap.sh` for Mac

### Building BOOST on Mac for Apple LLVM compiler 4.2
```bash
./b2 -a --layout=tagged --toolset=clang link=static threading=multi \
cxxflags="-arch i386 -arch x86_64 -stdlib=libc++ -std=c++11 -mmacosx-version-min=10.7 \
-fvisibility-inlines-hidden" stage debug release
```

### ~~Building BOOST on Mac for LLVM GCC 4.2~~ (NOT USED)
```bash
./b2 --toolset=clang --layout=tagged link=static stage debug release
```

### Building BOOST on Windows
```bash
./b2 link=static stage debug release
```

#### Usefull b2 flags
* `./b2 -a`: rebuild al
* `./b2 -d+2`: print commands before execution
* `./b2 cxxflags="-v"`: print compiler info (add it to both XCode properties and b2 command line then compare versions)
* `./b2 --with-filesystem --with-chrono`: Build only specified libraries


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Fusarium roseum var. vitalhae Sacc.

### Remarks
null


text:
package com.etsy.statsd.profiler.reporter.mock;

import com.google.common.base.Function;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;

/**
 * Mockito Answer for use testing reporters
 */
public class ReporterAnswer implements Answer {
    private Function<Object[], Void> testCase;

    public ReporterAnswer(Function<Object[], Void> testCase) {
        this.testCase = testCase;
    }

    @Override
    public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
        Object[] args = invocationOnMock.getArguments();
        testCase.apply(args);

        return null;
    }
}


text:
import ctypes as ct
_ConvNet = ct.cdll.LoadLibrary('_ConvNet.so')

import gnumpy as g

def convUp(images, filters, moduleStride = 1, paddingStart = 0):
    assert paddingStart <= 0
    numChannels, imSizeX, imSizeX, numImages = images.shape
    numFilterChannels, filterSizeX, filterSizeX, numFilters = filters.shape

    assert (abs(paddingStart) + imSizeX - filterSizeX) % moduleStride == 0

    numModulesX = (abs(paddingStart) + imSizeX - filterSizeX)/moduleStride + 1
    numModules = numModulesX**2

    numGroups = 1
    #moduleStride = 1

    targets = g.zeros((numFilters, numModulesX, numModulesX, numImages))

    numImgColors = numChannels

    imagesCu = images._base.p_mat
    filtersCu = filters._base.p_mat
    targetsCu = targets._base.p_mat

    imagesCu_orig, filtersCu_orig, targetsCu_orig = \
        [tuple(x.contents.size) for x in
         (imagesCu, filtersCu, targetsCu)]

    from numpy import prod
    filtersTotSize = filters.size
    filtersCu.contents.size[0] = numFilterChannels * filterSizeX**2
    filtersCu.contents.size[1] = numFilters
    assert filtersTotSize == prod(filtersCu.contents.size)

    imagesTotSize = images.size
    imagesCu.contents.size[0] = numImgColors * imSizeX**2
    imagesCu.contents.size[1] = numImages
    assert imagesTotSize == prod(imagesCu.contents.size)

    targetsTotSize = targets.size
    targetsCu.contents.size[0] = numFilters * numModulesX**2
    targetsCu.contents.size[1] = numImages
    assert targetsTotSize == prod(targetsCu.contents.size)

    _ConvNet.convUp(imagesCu,
                   filtersCu,
                   targetsCu,

                   numModulesX,
                   paddingStart,
                   moduleStride,
                   numImgColors,

                   numGroups,
                   )

    for i in range(2):
        filtersCu.contents.size[i] = filtersCu_orig[i]
        imagesCu.contents.size[i] = imagesCu_orig[i]
        targetsCu.contents.size[i] = targetsCu_orig[i]

    return targets

def convDown(hidActs, filters, moduleStride = 1, paddingStart = 0):
    numGroups = 1

    assert paddingStart <= 0
    numFilters, numModulesX, numModulesX, numImages = hidActs.shape
    numFilterChannels, filterSizeX, filterSizeX, numFilters = filters.shape

    numModules = numModulesX**2
    #numModulesX = (abs(paddingStart) + imSizeX - filterSizeX + 1)
    #imSizeX = numModulesX - abs(paddingStart) + filterSizeX - 1
    imSizeX = (numModulesX - 1) * moduleStride - abs(paddingStart) + filterSizeX

    #assert (abs(paddingStart) + imSizeX - filterSizeX) % moduleStride == 0
    numChannels = numFilterChannels * numGroups

    targets = g.zeros((numChannels, imSizeX, imSizeX, numImages))

    numImgColors = numChannels

    hidActsCu = hidActs._base.p_mat
    filtersCu = filters._base.p_mat
    targetsCu = targets._base.p_mat

# * hidActs:     (numFilters, numModules, numImages)
# * filters:     (numFilterColors, filterPixels, numFilters)               if conv
# *              (numModules, numFilterColors, filterPixels, numFilters)   otherwise
# * targets:     (numImageColors, imgPixels, numImages)

    hidActsCu_orig, filtersCu_orig, targetsCu_orig = \
        [tuple(x.contents.size) for x in
         (hidActsCu, filtersCu, targetsCu)]

    # filters are as before
    from numpy import prod
    filtersTotSize = filters.size
    filtersCu.contents.size[0] = numFilterChannels * filterSizeX**2
    filtersCu.contents.size[1] = numFilters
    assert filtersTotSize == prod(filtersCu.contents.size)

    # hidActs are like the targets of the past:
    hidActsTotSize = hidActs.size
    hidActsCu.contents.size[0] = numFilters * numModulesX**2
    hidActsCu.contents.size[1] = numImages
    assert hidActsTotSize == prod(hidActsCu.contents.size)

    # targets are like images:
    targetsTotSize = targets.size
    targetsCu.contents.size[0] = numImgColors * imSizeX**2
    targetsCu.contents.size[1] = numImages
    assert targetsTotSize == prod(targetsCu.contents.size)

    _ConvNet.convDown(
		       hidActsCu,
		       filtersCu,
		       targetsCu,

		       imSizeX,
		       paddingStart,
		       moduleStride,
		       numImgColors,
		       numGroups)

    for i in range(2):
        filtersCu.contents.size[i] = filtersCu_orig[i]
        hidActsCu.contents.size[i] = hidActsCu_orig[i]
        targetsCu.contents.size[i] = targetsCu_orig[i]

    return targets

def convOutp(images, hidActs, moduleStride = 1, paddingStart = 0, partialSum = None):
    numGroups = 1

    assert paddingStart <= 0
    numFilters, numModulesX, numModulesX, numImages = hidActs.shape
    numChannels, imSizeX, imSizeX, numImages = images.shape
    numFilterChannels = numChannels / numGroups

    #imSizeX = numModulesX - abs(paddingStart) + filterSizeX - 1
    #filterSizeX = (imSizeX - numModulesX + abs(paddingStart))/moduleStride + 1
    filterSizeX = -(numModulesX - 1) * moduleStride + (abs(paddingStart) + imSizeX)

    assert partialSum is None
    partialSum = numModulesX**2

    targets = g.zeros((numFilterChannels, filterSizeX, filterSizeX, numFilters))

    numImgColors = numChannels

    hidActsCu = hidActs._base.p_mat
    imagesCu = images._base.p_mat
    targetsCu = targets._base.p_mat

    imagesCu = images._base.p_mat
    imagesCu_orig, hidActsCu_orig, targetsCu_orig = \
        [tuple(x.contents.size) for x in
         (imagesCu, hidActsCu, targetsCu)]

    from pylab import prod
    imagesTotSize = images.size
    imagesCu.contents.size[0] = numImgColors * imSizeX**2
    imagesCu.contents.size[1] = numImages
    assert imagesTotSize == prod(imagesCu.contents.size)

    hidActsTotSize = hidActs.size
    hidActsCu.contents.size[0] = numFilters * numModulesX**2
    hidActsCu.contents.size[1] = numImages
    assert hidActsTotSize == prod(hidActsCu.contents.size)

    from numpy import prod
    targetsTotSize = targets.size
    targetsCu.contents.size[0] = numFilterChannels * filterSizeX**2
    targetsCu.contents.size[1] = numFilters
    assert targetsTotSize == prod(targetsCu.contents.size)

    _ConvNet.convOutp(
        imagesCu,
        hidActsCu,
        targetsCu,

        numModulesX,
        filterSizeX,
        paddingStart,
        moduleStride,
        numImgColors,
        numGroups,
        partialSum
        )

    for i in range(2):
        imagesCu.contents.size[i] = imagesCu_orig[i]
        hidActsCu.contents.size[i] = hidActsCu_orig[i]
        targetsCu.contents.size[i] = targetsCu_orig[i]

    return targets

def MaxPool(images,
            subsX,
            startX,
            strideX,
            outputsX
       ):

    numChannels, imSizeX, imSizeX, numImages = images.shape
    numImgColors = numChannels

    targets = g.zeros((numChannels, outputsX, outputsX, numImages))

    imagesCu = images._base.p_mat
    targetsCu = targets._base.p_mat

    from pylab import prod
    imagesCu_orig = tuple(imagesCu.contents.size)
    imagesTotSize = images.size
    imagesCu.contents.size[0] = numImgColors * imSizeX**2
    imagesCu.contents.size[1] = numImages
    assert imagesTotSize == prod(imagesCu.contents.size)

    targetsCu_orig = tuple(targetsCu.contents.size)
    targetsTotSize = targets.size
    targetsCu.contents.size[0] = numImgColors * outputsX**2
    targetsCu.contents.size[1] = numImages
    assert targetsTotSize == prod(targetsCu.contents.size)

    numFilters = numImgColors

    _ConvNet.MaxPool(imagesCu,
                  targetsCu,
                  numFilters,
                  subsX,
                  startX,
                  strideX,
                  outputsX
                  )

    for i in range(2):
        targetsCu.contents.size[i]=targetsCu_orig[i]
        imagesCu.contents.size[i]=imagesCu_orig[i]

    return targets

def MaxPoolUndo(images,
                grad,
                maxes,

                subsX,
                startX,
                strideX,
       ):

    numChannels, imSizeX_, imSizeX, numImages = images.shape
    assert imSizeX_ == imSizeX
    numChannels = numChannels

    numChannels, outputsX_, outputsX, numImages = maxes.shape
    assert outputsX_ == outputsX

    assert maxes.shape == grad.shape
    targets = g.zeros(images.shape)

    assert numChannels % 16 == 0

    imagesCu = images._base.p_mat
    maxesCu = maxes._base.p_mat
    gradCu = grad._base.p_mat
    targetsCu = targets._base.p_mat

    from pylab import prod
    imagesCu_orig = tuple(imagesCu.contents.size)
    imagesTotSize = images.size
    imagesCu.contents.size[0] = numChannels * imSizeX**2
    imagesCu.contents.size[1] = numImages
    assert imagesTotSize == prod(imagesCu.contents.size)

    from pylab import prod
    targetsCu_orig = tuple(targetsCu.contents.size)
    targetsTotSize = targets.size
    targetsCu.contents.size[0] = numChannels * imSizeX**2
    targetsCu.contents.size[1] = numImages
    assert targetsTotSize == prod(targetsCu.contents.size)

    maxesCu_orig = tuple(maxesCu.contents.size)
    maxesTotSize = maxes.size
    maxesCu.contents.size[0] = numChannels * outputsX**2
    maxesCu.contents.size[1] = numImages
    assert maxesTotSize == prod(maxesCu.contents.size)

    gradCu_orig = tuple(gradCu.contents.size)
    gradTotSize = grad.size
    gradCu.contents.size[0] = numChannels * outputsX**2
    gradCu.contents.size[1] = numImages
    assert gradTotSize == prod(gradCu.contents.size)

    _ConvNet.MaxPoolUndo(imagesCu,
                     gradCu,
                     maxesCu,
                     targetsCu,

                  subsX,
                  startX,
                  strideX,
                  outputsX
                  )

    for i in range(2):
        targetsCu.contents.size[i]=targetsCu_orig[i]
        imagesCu.contents.size[i]=imagesCu_orig[i]
        gradCu.contents.size[i]=gradCu_orig[i]
        maxesCu.contents.size[i]=maxesCu_orig[i]

    return targets

## dosen't work for some reason.  Investigate the reason.
def AvgPool(images,
            subsX,
            startX,
            strideX,
            outputsX
       ):

    numChannels, imSizeX, imSizeX, numImages = images.shape
    numImgColors = numChannels

    targets = g.zeros((numChannels, outputsX, outputsX, numImages))

    imagesCu = images._base.p_mat
    targetsCu = targets._base.p_mat

    from pylab import prod
    imagesCu_orig = tuple(imagesCu.contents.size)
    imagesTotSize = images.size
    imagesCu.contents.size[0] = numImgColors * imSizeX**2
    imagesCu.contents.size[1] = numImages
    assert imagesTotSize == prod(imagesCu.contents.size)

    targetsCu_orig = tuple(targetsCu.contents.size)
    targetsTotSize = targets.size
    targetsCu.contents.size[0] = numImgColors * outputsX**2
    targetsCu.contents.size[1] = numImages
    assert targetsTotSize == prod(targetsCu.contents.size)

    numFilters = numImgColors

    _ConvNet.AvgPool(imagesCu,
                     targetsCu,
                     numFilters,
                     subsX,
                     startX,
                     strideX,
                     outputsX,
                     subsX**2,
                     )

    for i in range(2):
        targetsCu.contents.size[i]=targetsCu_orig[i]
        imagesCu.contents.size[i]=imagesCu_orig[i]

    return targets

################################################################

def localUp(images, filters):

    numChannels, imSizeX, imSizeX, numImages = images.shape

    ## this is a hell of a filter-matrix.
    numModulesX, numModulesX, numFilterChannels, filterSizeX, filterSizeX, numFilters = filters.shape

    assert numModulesX <= imSizeX

    #numModulesX = (abs(paddingStart) + imSizeX - filterSizeX + 1)

    paddingStart = -(numModulesX - imSizeX + filterSizeX - 1)
    assert paddingStart <= 0

    numModules = numModulesX**2

    numGroups = 1
    moduleStride = 1

    targets = g.zeros((numFilters, numModulesX, numModulesX, numImages))

    numImgColors = numChannels

    imagesCu = images._base.p_mat
    filtersCu = filters._base.p_mat
    targetsCu = targets._base.p_mat

    imagesCu_orig, filtersCu_orig, targetsCu_orig = \
        [tuple(x.contents.size) for x in
         (imagesCu, filtersCu, targetsCu)]

    from numpy import prod
    filtersTotSize = filters.size
    filtersCu.contents.size[0] = numFilterChannels * filterSizeX**2 * numModulesX**2
    filtersCu.contents.size[1] = numFilters
    assert filtersTotSize == prod(filtersCu.contents.size)

    imagesTotSize = images.size
    imagesCu.contents.size[0] = numImgColors * imSizeX**2
    imagesCu.contents.size[1] = numImages
    assert imagesTotSize == prod(imagesCu.contents.size)

    targetsTotSize = targets.size
    targetsCu.contents.size[0] = numFilters * numModulesX**2
    targetsCu.contents.size[1] = numImages
    assert targetsTotSize == prod(targetsCu.contents.size)

    _ConvNet.localUp(imagesCu,
                   filtersCu,
                   targetsCu,

                   numModulesX,
                   paddingStart,
                   moduleStride,
                   numImgColors,

                   numGroups,
                   )

    for i in range(2):
        filtersCu.contents.size[i] = filtersCu_orig[i]
        imagesCu.contents.size[i] = imagesCu_orig[i]
        targetsCu.contents.size[i] = targetsCu_orig[i]

    return targets

def localDown(hidActs, filters, paddingStart = 0):
    numGroups = 1
    moduleStride = 1

    assert paddingStart <= 0
    numFilters, numModulesX, numModulesX, numImages = hidActs.shape
    numModulesX_, numModulesX_, numFilterChannels, filterSizeX, filterSizeX, numFilters = filters.shape

    ##### I DONT SUPPORT THE FUCKING STRIDE. SHIT.
    assert numModulesX_ == numModulesX
    #numModulesX = (abs(paddingStart) + imSizeX - filterSizeX + 1)
    imSizeX = numModulesX - abs(paddingStart) + filterSizeX - 1

    numChannels = numFilterChannels * numGroups

    #paddingStart = -(numModulesX - imSizeX + filterSizeX + 1)

    numModules = numModulesX**2

    targets = g.zeros((numChannels, imSizeX, imSizeX, numImages))

    numImgColors = numChannels

    hidActsCu = hidActs._base.p_mat
    filtersCu = filters._base.p_mat
    targetsCu = targets._base.p_mat

# * hidActs:     (numFilters, numModules, numImages)
# * filters:     (numFilterColors, filterPixels, numFilters)               if conv
# *              (numModules, numFilterColors, filterPixels, numFilters)   otherwise
# * targets:     (numImageColors, imgPixels, numImages)

    hidActsCu_orig, filtersCu_orig, targetsCu_orig = \
        [tuple(x.contents.size) for x in
         (hidActsCu, filtersCu, targetsCu)]

    # filters are as before
    from numpy import prod
    filtersTotSize = filters.size
    filtersCu.contents.size[0] = numFilterChannels * filterSizeX**2 * numModulesX**2
    filtersCu.contents.size[1] = numFilters
    assert filtersTotSize == prod(filtersCu.contents.size)

    # hidActs are like the targets of the past:
    hidActsTotSize = hidActs.size
    hidActsCu.contents.size[0] = numFilters * numModulesX**2
    hidActsCu.contents.size[1] = numImages
    assert hidActsTotSize == prod(hidActsCu.contents.size)

    # targets are like images:
    targetsTotSize = targets.size
    targetsCu.contents.size[0] = numImgColors * imSizeX**2
    targetsCu.contents.size[1] = numImages
    assert targetsTotSize == prod(targetsCu.contents.size)

    _ConvNet.localDown(
		       hidActsCu,
		       filtersCu,
		       targetsCu,

		       imSizeX,
		       paddingStart,
		       moduleStride,
		       numImgColors,
		       numGroups)

    for i in range(2):
        filtersCu.contents.size[i] = filtersCu_orig[i]
        hidActsCu.contents.size[i] = hidActsCu_orig[i]
        targetsCu.contents.size[i] = targetsCu_orig[i]

    return targets

def localOutp(images, hidActs, paddingStart = 0):
    numGroups = 1
    moduleStride = 1

    numFilters, numModulesX, numModulesX, numImages = hidActs.shape
    numChannels, imSizeX, imSizeX, numImages = images.shape
    numFilterChannels = numChannels / numGroups

    #imSizeX = numModulesX - abs(paddingStart) + filterSizeX - 1
    assert paddingStart <= 0
    filterSizeX = imSizeX - numModulesX + abs(paddingStart) + 1

    #assert partialSum is None
    #partialSum = numModulesX**2

    targets = g.zeros((numModulesX, numModulesX, numFilterChannels, filterSizeX, filterSizeX, numFilters))

    numImgColors = numChannels

    hidActsCu = hidActs._base.p_mat
    imagesCu = images._base.p_mat
    targetsCu = targets._base.p_mat

    imagesCu = images._base.p_mat
    imagesCu_orig, hidActsCu_orig, targetsCu_orig = \
        [tuple(x.contents.size) for x in
         (imagesCu, hidActsCu, targetsCu)]

    from pylab import prod
    imagesTotSize = images.size
    imagesCu.contents.size[0] = numImgColors * imSizeX**2
    imagesCu.contents.size[1] = numImages
    assert imagesTotSize == prod(imagesCu.contents.size)

    hidActsTotSize = hidActs.size
    hidActsCu.contents.size[0] = numFilters * numModulesX**2
    hidActsCu.contents.size[1] = numImages
    assert hidActsTotSize == prod(hidActsCu.contents.size)

    from numpy import prod
    targetsTotSize = targets.size
    targetsCu.contents.size[0] = numFilterChannels * filterSizeX**2 * numModulesX**2
    targetsCu.contents.size[1] = numFilters
    assert targetsTotSize == prod(targetsCu.contents.size)

    _ConvNet.localOutp(
        imagesCu,
        hidActsCu,
        targetsCu,

        numModulesX,
        filterSizeX,
        paddingStart,
        moduleStride,
        numImgColors,
        numGroups,
        )

    for i in range(2):
        imagesCu.contents.size[i] = imagesCu_orig[i]
        hidActsCu.contents.size[i] = hidActsCu_orig[i]
        targetsCu.contents.size[i] = targetsCu_orig[i]

    return targets


text:
<?php

use Tygh\Registry;

if (!defined('BOOTSTRAP')) { die('Access denied'); }

fn_define('DB_MAX_ROW_SIZE', 10000);
fn_define('DB_ROWS_PER_PASS', 40);

if ($_SERVER['REQUEST_METHOD']	== 'POST') {

    set_time_limit(3600);

    // Backup database
    if ($mode == 'backup') {

        $dbdump_filename = empty($_REQUEST['dbdump_filename']) ? 'dump_' . date('mdY') . '.sql' : fn_basename($_REQUEST['dbdump_filename']);

        if (!fn_mkdir(Registry::get('config.dir.database'))) {
            fn_set_notification('E', __('error'), __('text_cannot_create_directory', array(
                '[directory]' => fn_get_rel_dir(Registry::get('config.dir.database'))
            )));
            exit;
        }

        $dump_file = Registry::get('config.dir.database') . $dbdump_filename;

        if (is_file($dump_file)) {
            if (!is_writable($dump_file)) {
                fn_set_notification('E', __('error'), __('dump_file_not_writable'));
                exit;
            }
        }

        $dbdump_tables = empty($_REQUEST['dbdump_tables']) ? array() : $_REQUEST['dbdump_tables'];
        $dbdump_schema = !empty($_REQUEST['dbdump_schema']) && $_REQUEST['dbdump_schema'] == 'Y';
        $dbdump_data = !empty($_REQUEST['dbdump_data']) && $_REQUEST['dbdump_data'] == 'Y';

        db_export_to_file($dump_file, $dbdump_tables, $dbdump_schema, $dbdump_data);

        $result = false;
        if ($_REQUEST['dbdump_compress'] == 'Y') {
            fn_set_progress('echo', '
' . __('compressing_backup') . '...', false);

            $result = fn_compress_files($dbdump_filename . '.tgz', $dbdump_filename, dirname($dump_file));
            unlink($dump_file);
        }

        if ($result) {
            fn_set_notification('N', __('notice'), __('done'));
        }
    }

    // Restore
    if ($mode == 'restore') {

        if (!empty($_REQUEST['backup_files'])) {
            fn_restore_dump($_REQUEST['backup_files']);
        }

        fn_set_notification('N', __('notice'), __('done'));
    }

    if ($mode == 'm_delete') {
        if (!empty($_REQUEST['backup_files'])) {
            foreach ($_REQUEST['backup_files'] as $file) {
                @unlink(Registry::get('config.dir.database') . fn_basename($file));
            }
        }
    }

    if ($mode == 'upload') {
        $sql_dump = fn_filter_uploaded_data('sql_dump', array('sql', 'tgz'));

        if (!empty($sql_dump)) {
            $sql_dump = array_shift($sql_dump);
            if (fn_copy($sql_dump['path'], Registry::get('config.dir.database') . $sql_dump['name'])) {
                fn_set_notification('N', __('notice'), __('done'));
            } else {
                fn_set_notification('N', __('notice'), __('dump_cant_create_file'));
            }
        } else {
            fn_set_notification('N', __('notice'), __('cant_upload_file'));
        }
    }

    if ($mode == 'optimize') {
        // Log database optimization
        fn_log_event('database', 'optimize');

        $all_tables = db_get_fields("SHOW TABLES");

        fn_set_progress('parts', sizeof($all_tables));

        foreach ($all_tables as $table) {
            fn_set_progress('echo', __('optimizing_table') . " $table...
");

            db_query("OPTIMIZE TABLE $table");
            db_query("ANALYZE TABLE $table");
            $fields = db_get_hash_array("SHOW COLUMNS FROM $table", 'Field');

            if (!empty($fields['is_global'])) { // Sort table by is_global field
                fn_echo('.');
                db_query("ALTER TABLE $table ORDER BY is_global DESC");
            } elseif (!empty($fields['position'])) { // Sort table by position field
                fn_echo('.');
                db_query("ALTER TABLE $table ORDER BY position");
            }
        }

        fn_set_notification('N', __('notice'), __('done'));
    }

    return array(CONTROLLER_STATUS_OK, "database.manage");
}

if ($mode == 'getfile' && !empty($_REQUEST['file'])) {
    fn_get_file(Registry::get('config.dir.database') . fn_basename($_REQUEST['file']));

} elseif ($mode == 'manage') {

    Registry::set('navigation.tabs', array (
        'backup' => array (
            'title' => __('backup'),
            'js' => true
        ),
        'restore' => array (
            'title' => __('restore'),
            'js' => true
        ),
        'maintenance' => array (
            'title' => __('maintenance'),
            'js' => true
        ),
    ));

    // Calculate database size and fill tables array
    $status_data = db_get_array("SHOW TABLE STATUS");
    $database_size = 0;
    $all_tables = array();
    foreach ($status_data as $k => $v) {
        $database_size += $v['Data_length'] + $v['Index_length'];
        $all_tables[] = $v['Name'];
    }

    Registry::get('view')->assign('database_size', $database_size);
    Registry::get('view')->assign('all_tables', $all_tables);

    $files = fn_get_dir_contents(Registry::get('config.dir.database'), false, true, array('.sql', '.tgz'), '', true);

    sort($files, SORT_STRING);
    $backup_files = array();
    $date_format = Registry::get('settings.Appearance.date_format'). ' ' . Registry::get('settings.Appearance.time_format');
    if (is_array($files)) {
        foreach ($files as $file) {
            $backup_files[$file]['size'] = filesize(Registry::get('config.dir.database') . $file);
            $backup_files[$file]['type'] = strpos($file, '.tgz')===false ? 'sql' : 'tgz';
            $backup_files[$file]['create'] = fn_date_format(filemtime(Registry::get('config.dir.database') . $file), $date_format);
        }
    }

    Registry::get('view')->assign('backup_files', $backup_files);
    Registry::get('view')->assign('backup_dir', fn_get_rel_dir(Registry::get('config.dir.database')));

} elseif ($mode == 'delete') {
    if (!empty($_REQUEST['backup_file'])) {
        fn_rm(Registry::get('config.dir.database') . fn_basename($_REQUEST['backup_file']));
    }

    return array(CONTROLLER_STATUS_REDIRECT, "database.manage?selected_section=restore");
}

function fn_restore_dump($files)
{
    if (empty($files)) {
        return false;
    }

    fn_set_progress('parts', sizeof($files));

    foreach ($files as $file) {
        $is_archive = false;

        $list = array($file);

        if (in_array(fn_get_file_ext($file), array('zip', 'tgz'))) {
            $is_archive = true;

            fn_decompress_files(Registry::get('config.dir.database') . $file, Registry::get('config.dir.database') . '_tmp');

            $list = fn_get_dir_contents(Registry::get('config.dir.database') . '_tmp', false, true, 'sql', '_tmp/');
        }

        foreach ($list as $_file) {
            db_import_sql_file(Registry::get('config.dir.database') . $_file);
        }

        if ($is_archive) {
            fn_rm(Registry::get('config.dir.database') . '_tmp');
        }
    }

    // Log database restore
    fn_log_event('database', 'restore');

    fn_set_hook('database_restore', $files);

    fn_clear_cache();

    return true;
}


text:
module.exports = function (config) {
  config.set({
    autoWatch: false,
    browsers: ['Chrome'],
    client: {
      captureConsole: true
    },
    frameworks: ['jasmine'],
    files: [
      'bower_components/angular/angular.js',
      'bower_components/angular-mocks/angular-mocks.js',
      'dist/format-as-currency.js',
      'test/format-as-currency.js'
    ],
    logLevel: config.LOG_INFO,
    singleRun: true,

    // coverage
    coverageReporter: {
      type : 'lcov',
      dir : 'coverage/',
    },
    preprocessors: {
      'dist/format-as-currency.js': ['coverage']
    },
    reporters: ['progress', 'coverage']
  })
}


text:
<?php
namespace Octal\Support;

use Artisan;
use Illuminate\Support\Facades\Blade;
use Illuminate\Foundation\AliasLoader;
use Illuminate\Support\ServiceProvider;

class OProvider extends ServiceProvider
{
    public function boot()
    {

    }

    public function register()
    {
        include __DIR__ . '/routes.php';

        $loader = AliasLoader::getInstance();

        $this->app->make('Octal\Support\OController');
    }
}


text:
const {schema} = require("../schema")

const $node = (type, attrs, content, marks) => schema.node(type, attrs, content, marks)
const $text = (str, marks) => schema.text(str, marks)
const em = schema.marks.em.create(), strong = schema.marks.strong.create()

function populateDefaultInstances(newInstance) {

newInstance("Example", $node("doc", null, [
  $node("heading", {level: 2}, [$text("Example Document")]),
  $node("paragraph", null, [
    $text("There is nothing here yet. "),
    $text("Add something!", [em])
  ])
]))

newInstance("Business Plan", $node("doc", null, [
  $node("heading", {level: 1}, [$text("Business Plan")]),
  $node("ordered_list", null, [
    $node("list_item", null, [$node("paragraph", null, [$text("Give away software")])]),
    $node("list_item", null, [$node("paragraph", null, [$text("???")])]),
    $node("list_item", null, [$node("paragraph", null, [$text("Profit!!!", [strong])])])
  ])
]))

newInstance("*scratch*", $node("doc", null, [
  $node("code_block", null, [
    $text(";; This buffer is for notes you don't want to save, and for Lisp evaluation.\n;; If you want to create a file, visit that file with C-x C-f,\n;; then enter the text in that file's own buffer.")
  ])
]))

newInstance("Nonsense", $node("doc", null, [
  $node("blockquote", null, [
    $node("paragraph", null, [
      $text("Mona tried to tell me"), $node("hard_break"),
      $text("To stay away from the train line."), $node("hard_break"),
      $text("She said that all the railroad men"), $node("hard_break"),
      $text("Just drink up your blood like wine."), $node("hard_break"),
      $text("An' I said, "Oh, I didn't know that,"), $node("hard_break"),
      $text("But then again, there's only one I've met"), $node("hard_break"),
      $text("An' he just smoked my eyelids"), $node("hard_break"),
      $text("An' punched my cigarette.""), $node("hard_break"),
      $text("Oh, Mama, can this really be the end,"), $node("hard_break"),
      $text("To be stuck inside of Mobile"), $node("hard_break"),
      $text("With the Memphis blues again.")
    ]),
    $node("paragraph", null, [
      $text("— Bob Dylan, "),
      $text("Stuck Inside of Mobile with the Memphis Blues Again", [em])
    ])
  ])
]))

newInstance("Comment Section", $node("doc", null, [
  $node("heading", {level: 1}, [$text("Comment Section")]),
  $node("paragraph", null, [
    $text("The good thing about this comment section is that everybody can delete comments.")
  ]),
  $node("heading", {level: 4}, [$text("From user21841. "), $text("20 seconds ago", [em])]),
  $node("paragraph", null, [
    $text("If you look at it rationally you'll see that open-source software is communism and communism is bad because the free market is our God and savior. Also sheep caused 9/11.")
  ])
]))

}
exports.populateDefaultInstances = populateDefaultInstances


text:
<?php

namespace app\controllers;

use Yii;
use app\models\Gem;
use app\models\GemSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\web\UploadedFile;

/**
 * GemController implements the CRUD actions for Gem model.
 */
class GemController extends Controller
{
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['post'],
                ],
            ],
        ];
    }

    /**
     * Lists all Gem models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new GemSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Creates a new Gem model.
     * If creation is successful, the browser will be redirected to the 'index' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new Gem();

        if ($model->load(Yii::$app->request->post()) && $model->validate()) {

            echo '<pre>';
            var_dump($model->color);
            var_dump($model->getImagePath());
            echo '</pre>';

            $uploadedFile = UploadedFile::getInstance($model, 'image');
            $model->addImage($uploadedFile, true);
            die;

            $model->save();
            return $this->redirect(['index', 'id' => $model->id]);
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Updates an existing Gem model.
     * If update is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['index', 'id' => $model->id]);
        } else {
            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Deletes an existing Gem model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the Gem model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Gem the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Gem::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}


text:
import React from 'react'
import {IconButton, Tooltip} from 'react-toolbox'
import MediaQuery from 'react-responsive'
import classes from './HomeView.scss'

export const renderStatItem = (brandItem, index, tooltip, icon) => {
  const TTStats = Tooltip(IconButton)
  return (

      <MediaQuery minDeviceWidth={767}>
        <TTStats
          icon={icon}
          tooltip={tooltip}
          style={{width: '24px', height: '24px'}}
          >
          { {
            brandItem[index]
          } }
        </TTStats>
      </MediaQuery>
      <MediaQuery maxDeviceWidth={766} />

  )
}


text:
package com.netflix.astyanax.test;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;

import com.google.common.util.concurrent.ThreadFactoryBuilder;
import com.netflix.astyanax.connectionpool.Connection;
import com.netflix.astyanax.connectionpool.ConnectionFactory;
import com.netflix.astyanax.connectionpool.ConnectionPoolConfiguration;
import com.netflix.astyanax.connectionpool.ConnectionPoolMonitor;
import com.netflix.astyanax.connectionpool.Host;
import com.netflix.astyanax.connectionpool.HostConnectionPool;
import com.netflix.astyanax.connectionpool.Operation;
import com.netflix.astyanax.connectionpool.OperationResult;
import com.netflix.astyanax.connectionpool.exceptions.ConnectionException;
import com.netflix.astyanax.connectionpool.exceptions.IsTimeoutException;
import com.netflix.astyanax.connectionpool.exceptions.ThrottledException;
import com.netflix.astyanax.connectionpool.exceptions.UnknownException;
import com.netflix.astyanax.connectionpool.impl.OperationResultImpl;

public class TestConnectionFactory implements ConnectionFactory<TestClient> {
    private final ConnectionPoolConfiguration config;
    private final ExecutorService executor = Executors.newFixedThreadPool(10,
            new ThreadFactoryBuilder().setDaemon(true).build());
    private final ConnectionPoolMonitor monitor;

    public TestConnectionFactory(ConnectionPoolConfiguration config,
            ConnectionPoolMonitor monitor) {
        this.config = config;
        this.monitor = monitor;
    }

    @Override
    public Connection<TestClient> createConnection(
            final HostConnectionPool<TestClient> pool)
            throws ThrottledException {
        return new Connection<TestClient>() {
            private ConnectionException lastException;
            private boolean isOpen = false;
            private AtomicLong operationCounter = new AtomicLong();

            @Override
            public <R> OperationResult<R> execute(Operation<TestClient, R> op)
                    throws ConnectionException {
                long startTime = System.nanoTime();
                long latency = 0;

                // Execute the operation
                try {
                    TestHostType type = TestHostType.get(getHost().getPort());
                    OperationResult<R> result = type.execute(pool, op);
                    long now = System.nanoTime();
                    latency = now - startTime;
                    pool.addLatencySample(latency, now);
                    return new OperationResultImpl<R>(result.getHost(), result.getResult(), latency);
                } catch (Exception e) {
                    long now = System.nanoTime();
                    latency = now - startTime;
                    ConnectionException connectionException;
                    if (!(e instanceof ConnectionException))
                        connectionException = new UnknownException(e);
                    else
                        connectionException = (ConnectionException)e;
                    connectionException.setLatency(latency);

                    if (!(connectionException instanceof IsTimeoutException)) {
                        pool.addLatencySample(latency, now);
                    }
                    else {
                        pool.addLatencySample(TimeUnit.NANOSECONDS.convert(config.getSocketTimeout(), TimeUnit.MILLISECONDS), System.nanoTime());
                    }
                    lastException = connectionException;
                    throw lastException;
                }
            }

            @Override
            public void close() {
                if (isOpen) {
                    monitor.incConnectionClosed(getHost(), lastException);
                    executor.submit(new Runnable() {
                        @Override
                        public void run() {
                            final TestHostType type = TestHostType
                                    .get(getHost().getPort());
                            type.close();
                            isOpen = false;
                        }
                    });
                }
            }

            @Override
            public HostConnectionPool<TestClient> getHostConnectionPool() {
                return pool;
            }

            @Override
            public ConnectionException getLastException() {
                return lastException;
            }

            @Override
            public void open() throws ConnectionException {
                TestHostType type = TestHostType.get(getHost().getPort());
                try {
                    type.open(0);
                    isOpen = true;
                    monitor.incConnectionCreated(getHost());
                } catch (ConnectionException e) {
                    lastException = e;
                    e.setHost(getHost());
                    monitor.incConnectionCreateFailed(getHost(), e);
                    throw e;
                }
            }

            @Override
            public void openAsync(final AsyncOpenCallback<TestClient> callback) {
                final Connection<TestClient> This = this;
                executor.submit(new Runnable() {
                    @Override
                    public void run() {
                        Thread.currentThread().setName("MockConnectionFactory");
                        try {
                            open();
                            callback.success(This);
                        } catch (ConnectionException e) {
                            callback.failure(This, e);
                        } catch (Exception e) {
                            callback.failure(This, new UnknownException(
                                    "Error openning async connection", e));
                        }
                    }
                });
            }

            @Override
            public long getOperationCount() {
                return operationCounter.get();
            }

            @Override
            public Host getHost() {
                return pool.getHost();
            }

            @Override
            public void setMetadata(String key, Object obj) {
                // TODO Auto-generated method stub

            }

            @Override
            public Object getMetadata(String key) {
                // TODO Auto-generated method stub
                return null;
            }

            @Override
            public boolean hasMetadata(String key) {
                // TODO Auto-generated method stub
                return false;
            }
        };
    }
}


text:
<%= view.component("list.messages", {
	collection: {
		loaderArgs: [options.ref]
	}
}, "messages") %>
<% if (options.showPostMessage) { %>
<form class="message-input">
	<textarea placeholder=""></textarea>
	<input type="submit" value="Add comment" />
	Refresh
</form>
<% } %>


text:
import * as _ from 'lodash';
import {IQueryPart} from "../abstract/IQueryPart";
import {IBoundQueryPart} from "../abstract/IBoundQueryPart";
import {QueryContext} from "../common/QueryContext";
import {TypedSetQueryPart} from "./TypedSetQueryPart";
import {UntypedSetQueryPart} from "./UntypedSetQueryPart";
import {LiteralSetQueryPart} from "./LiteralSetQueryPart";

export type SetQueryPartChildren = TypedSetQueryPart<any> | UntypedSetQueryPart | LiteralSetQueryPart | string;

export class SetQueryPart implements IQueryPart {

    constructor(private elements:SetQueryPartChildren[]) {}

    toCypher(ctx:QueryContext):IBoundQueryPart {
        let cypherPart:IBoundQueryPart = {cypherString: 'SET ', params: {}};

        this.elements.forEach((el:SetQueryPartChildren, idx:number) => {
            if (idx > 0) {
                cypherPart.cypherString += ', ';
            }

            if (_.isString(el)) {
                cypherPart.cypherString += el;
            } else {
                let boundCypherQuery = el.toCypher(ctx);
                cypherPart.cypherString += boundCypherQuery.cypherString;
                cypherPart.params = _.merge(cypherPart.params, boundCypherQuery.params);
            }
        });

        return cypherPart;
    }
}