text:
import sympy as sp
from sympy.physics.mechanics import dynamicsymbols
from sympy.printing.pycode import NumPyPrinter
from sympy.utilities.lambdify import _EvaluatorPrinter
from sympy.codegen.ast import AssignmentBase, Symbol, Element, Variable
from sympy.core.function import AppliedUndef
from sympy.core.compatibility import iterable, PY3, string_types
import keyword
import re

t = dynamicsymbols._t

def staticfy_expressions(expr):
    """
    Converts dynamic symbols (i.e., symbols which are implied functions of time)
    to static symbols in expr. Many codegen operations need dynamic symbols
    converted to static.
    """
    dyn_syms = list(sp.physics.mechanics.functions.find_dynamicsymbols(expr))
    dynamic_to_static = {}
    for sym in dyn_syms:
        if (len(sym.args) == 1) and sym.args[0] == t:
            dynamic_to_static[sym] = sp.symbols(sym.__class__.__name__)

    if len(dynamic_to_static) == 0:
        return expr

    new_expr = expr.subs(dynamic_to_static)

    if (sp.Function in expr.__class__.__mro__) and hasattr(expr, 'shape'):
        new_expr.shape = expr.shape

    return new_expr

def process_funcs_to_print(funcs_to_print):
    """
    Prepares a set of sympy expressions to be printed with CSE. The `dict`\s
    are modified in-place.

    funcs_to_print is an iterable of dicts with keys:
        'extra_assignments', a dict of exta assignments before CSE
        'input_args', an Array of the input arguments
        'sym_expr', the symbolic expression to print with CSE
    """

    code_print_params = []
    for funcs_to_print_dict in funcs_to_print:
        extras_dict = {} #funcs_to_print_dict['extra_assignments'].copy()
        for key,val in funcs_to_print_dict['extra_assignments'].items():
            #print(key, val)
            static_key = staticfy_expressions(key)
            static_val = staticfy_expressions(val)
            extras_dict[static_key] = static_val
        funcs_to_print_dict['extra_assignments'] = extras_dict
        if funcs_to_print_dict['input_args']:
            funcs_to_print_dict['input_args'] = staticfy_expressions(funcs_to_print_dict['input_args'])
        funcs_to_print_dict['sym_expr'] = staticfy_expressions(funcs_to_print_dict['sym_expr'])

        tot_size = 1
        if hasattr(funcs_to_print_dict['sym_expr'], 'shape'):
            raveled_shape = funcs_to_print_dict['sym_expr'].shape
            for dim in raveled_shape:
                tot_size = tot_size*dim
            funcs_to_print_dict['sym_expr'] = funcs_to_print_dict['sym_expr'].reshape(tot_size).tolist()

        cse_out = sp.cse(funcs_to_print_dict['sym_expr'], order='none')
        cse_subs = {k:v for k,v in cse_out[0]}
        funcs_to_print_dict['extra_assignments'].update(cse_subs)

        if tot_size > 1:
            funcs_to_print_dict['sym_expr'] = sp.Array(cse_out[1]).reshape(*raveled_shape)
        else:
            funcs_to_print_dict['sym_expr'] = cse_out[1][0]

        code_print_params.append( (funcs_to_print_dict['num_name'], funcs_to_print_dict['input_args'], funcs_to_print_dict['sym_expr'], funcs_to_print_dict['extra_assignments']) )
    return code_print_params

class Assignment(AssignmentBase):
    """
    Represents variable assignment for code generation, but can also use Array
    on the LHS and non-defensively allows a function on RHS with indexed LHS.

    Parameters
    ==========

    lhs : Expr
        Sympy object representing the lhs of the expression. These should be
        singular objects, such as one would use in writing code. Notable types
        include Symbol, MatrixSymbol, MatrixElement, and Indexed. Types that
        subclass these types are also supported.

    rhs : Expr
        Sympy object representing the rhs of the expression. This can be any
        type, provided its shape corresponds to that of the lhs. For example,
        a Matrix type can be assigned to MatrixSymbol, but not to Symbol, as
        the dimensions will not align.
    """

    @classmethod
    def _check_args(cls, lhs, rhs):
        """ Check arguments to __new__ and raise exception if any problems found.

        Derived classes may wish to override this.
        """
        from sympy.matrices.expressions.matexpr import (
            MatrixElement, MatrixSymbol)
        from sympy.tensor.indexed import Indexed

        # Tuple of things that can be on the lhs of an assignment
        assignable = (Symbol, MatrixSymbol, MatrixElement, Indexed, Element, Variable, sp.Array)
        if not isinstance(lhs, assignable):
            raise TypeError("Cannot assign to lhs of type %s." % type(lhs))

        # Indexed types implement shape, but don't define it until later. This
        # causes issues in assignment validation. For now, matrices are defined
        # as anything with a shape that is not an Indexed
        lhs_is_mat = hasattr(lhs, 'shape') and not isinstance(lhs, Indexed)
        rhs_is_mat = hasattr(rhs, 'shape') and not isinstance(rhs, Indexed)

        # If lhs and rhs have same structure, then this assignment is ok
        if lhs_is_mat and not isinstance(rhs, AppliedUndef):
            if not rhs_is_mat:
                raise ValueError("Cannot assign a scalar to a matrix.")
            elif lhs.shape != rhs.shape:
                raise ValueError("Dimensions of lhs and rhs don't align.")
        elif rhs_is_mat and not lhs_is_mat:
            raise ValueError("Cannot assign a matrix to a scalar.")

    op = ':='

class ArrayNumPyPrinter(NumPyPrinter):
    def _print_Max(self, expr):
        return '{0}({1})'.format(self._module_format('numpy.maximum'), ','.join(self._print(i) for i in expr.args))

    def _print_Piecewise(self, expr):
        """Piecewise function printer

        from sympy version:
        # If [default_value, True] is a (expr, cond) sequence in a Piecewise object
        #     it will behave the same as passing the 'default' kwarg to select()
        #     *as long as* it is the last element in expr.args.
        # If this is not the case, it may be triggered prematurely.

        which is just not implemented at all...
        """
        if expr.args[-1].cond == True:
            expr_args = expr.args[:-1]
            default_val = expr.args[-1].expr
        else:
            expr_args = expr.args
            default_val = sp.NaN
        exprs = '[{0}]'.format(','.join(self._print(arg.expr) for arg in expr_args))
        conds = '[{0}]'.format(','.join(self._print(arg.cond) for arg in expr_args))
        return '{0}({1}, {2}, default={3})'.format(
            self._module_format('numpy.select'), conds, exprs,
            self._print(default_val))

    def _print_Heaviside(self, expr):
        return '(({0}>0.0)+0.5*({0}==0.0))'.format(','.join(self._print(i) for i in expr.args))

    def _print_ImmutableDenseNDimArray(self, expr):
        # return str(expr)
        return "numpy.array(%s)" % (self._print(expr.tolist()),)

    def _print_Assignment(self, expr):
        if isinstance(expr.lhs, sp.Array):
            lhs = expr.lhs
            rhs = expr.rhs

            if isinstance(expr.rhs, sp.Piecewise):
                # Here we modify Piecewise so each expression is now
                # an Assignment, and then continue on the print.
                expressions = []
                conditions = []
                for (e, c) in rhs.args:
                    expressions.append(Assignment(lhs, e))
                    conditions.append(c)
                temp = sp.Piecewise(*zip(expressions, conditions))
                return self._print(temp)

            lhs_code = self._print(sp.flatten(lhs.tolist()))
            # TODO: I think this is where I could make it so that the assignment gets pretty robust to multidimensional inputs
            # when I re-wrote the static trimmability function, I just had to apply .T instead of .ravel, that may be sufficient generally
            # since I already flatten the sympy expression that is being generated.... not sure though.
            rhs_code = self._print(rhs) + '.ravel()'
            return self._get_statement("%s = %s" % (lhs_code, rhs_code))

            # I would prefer to have something like this, but isn't clear how
            temp = sp.Dummy()
            lines = [self._print(Assignment(temp, rhs))]
            temp = sp.Indexed(temp.name, lhs.shape)
            for idx, el in enumerate(lhs):
                lines.append('{}[{}]'.format(self._print(temp), 0))
        else:
            if expr.rhs.func == sp.Piecewise:
                # The sympy/printing/codeprinter.py CodePrinter._print_Assignment explicitly
                # folds the assignments into each case, which is never over-written for the NumPyPrinter
                lhs_code = self._print(expr.lhs)
                rhs_code = self._print(expr.rhs)
                return self._get_statement("%s = %s" % (lhs_code, rhs_code))
            return super()._print_Assignment(expr)

class ModuleNumPyPrinter(ArrayNumPyPrinter):
    def __init__(self, for_class=False, **kwargs):
        new_modules = kwargs.pop('function_modules', {})
        new_func_names = kwargs.pop('function_names', {})
        new_constant_modules = kwargs.pop('constant_modules', {})
        new_constant_names = kwargs.pop('constant_names', {})

        super().__init__(**kwargs)

        self.for_class = for_class # --> prepend self to args, assume unknown functions are in self
        # TODO: also assume constants are in self, but need to distinguish from inputs and intermediate computations

        self.known_func_modules = {None: 'numpy'}
        self.known_func_modules.update(new_modules)

        self.known_func_names = new_func_names

        self.known_constant_modules = new_constant_modules
        self.known_constant_names = new_constant_names
        self.functions_not_supported = set()
        self.constants_not_supported = set()

    def _traverse_matrix_indices(self, mat):
        rows, cols = mat.shape
        return ((i, j) for i in range(rows) for j in range(cols))

    def _print_Symbol(self, expr):
        super_ret = super()._print_Symbol(expr)
        if expr in self.known_constant_modules:
            module = self.known_constant_modules[expr]
            if expr in self.known_constant_names:
                const_name = self.known_constant_names[expr]
            else:
                const_name = super_ret
            if module != '':
                return self._module_format('.'.join([module,const_name]))
            else:
                return const_name
        return super_ret

    def _print_Function(self, expr):
        func = expr.func
        if (len(expr.args) == 1) and (expr.args[0] == dynamicsymbols._t):
            return func.__name__
        elif func not in self.known_functions:
            if func in self.known_func_modules:
                module = self.known_func_modules[func]
            elif self.for_class:
                module = 'self'
            else:
                module = ''
            if func in self.known_func_names:
                func_name = self.known_func_names[func]
            else:
                func_name = func.__name__
            if module != '':
                func_text = self._module_format('.'.join([module,func_name]))
            else:
                func_text = func_name
            args = ','.join(self._print(i) for i in expr.args)
            return "{}({})".format(func_text, args)
        else:
            return super()._print_Function(expr)

    def _print_Assignment(self, expr):
        if hasattr(expr.lhs, 'shape'):
            for lhs_element in expr.lhs:
                self.known_constant_modules[lhs_element] = ''
        else:
            self.known_constant_modules[expr.lhs] = ''
        return super()._print_Assignment(expr)

    def __delattr__(self, attr):
        if attr == '_not_supported':
            self.functions_not_supported = self.functions_not_supported.union(self._not_supported)
        return super().__delattr__(attr)

class ModulePrinter(_EvaluatorPrinter):
    _safe_star_args = re.compile(r'^\*{0,2}')

    if PY3:
        @classmethod
        def _is_safe_ident(cls, ident):
            return isinstance(ident, string_types) and cls._safe_star_args.sub('',ident).isidentifier() \
                    and not keyword.iskeyword(ident)
    else:
        @classmethod
        def _is_safe_ident(cls, ident):
            return isinstance(ident, string_types) and cls._safe_ident_re.match(cls._safe_star_args.sub('',ident)) \
                and not (keyword.iskeyword(ident) or ident == 'None')

    def codeprint(self, func_arg_expr_s, extra_pre_lines='', extra_post_lines=''):
        printer = self._exprrepr.__self__
        lines = []
        for module in set(printer.known_func_modules.values()) | set(printer.known_constant_modules.values()):
            if module != '' and not (printer.for_class and module == 'self'):
                lines.append("import {}".format(module))
        if extra_pre_lines != '':
            lines.append(extra_pre_lines)
        lines.append("\n")
        for func_arg_expr in func_arg_expr_s:
            if len(func_arg_expr)==4:
                # do dict assignment?? Maybe nothing extra is needed here, if the printer handles it on assignment
                pass
            lines.append(self.doprint(*func_arg_expr))
            func = sp.Function(func_arg_expr[0])
            if func not in printer.known_func_modules:
                printer.known_func_modules[func] = ''

            for func in func_arg_expr[2].atoms(AppliedUndef):
                if func.func not in printer.known_func_modules:
                    if (len(func.args) == 1) and (func.args[0] == dynamicsymbols._t):
                        pass
                    else:
                        raise ValueError("Unknown function {} in ModulePrinter".format(func.__class__.__name__))
            for const in func_arg_expr[2].atoms(sp.Symbol):
                if const not in printer.known_constant_modules and const not in func_arg_expr[1]:
                    if const == dynamicsymbols._t:
                        pass
                    else:
                        raise ValueError("Unknown symbol {} in ModulePrinter".format(str(const)))

        if extra_post_lines != '':
            lines.append(extra_post_lines)

        if len(printer.functions_not_supported):
            raise ValueError("Unknown functions in ModulePrinter", printer.functions_not_supported)
        return "\n".join(lines)

    # copied and modified from _EvaluatorPrinter.doprint
    def doprint(self, funcname, args, expr, extra_assignments=None):
        """
        Returns the function definition code as a string.

        extra_assignments is a dict of extra assignment definitions or None
        """

        from sympy import Dummy

        if extra_assignments is None:
            extra_assignments = {}

        funcbody = []

        if not iterable(args):
            args = [args]

        argstrs, expr = self._preprocess(args, expr)

        # Generate argument unpacking and final argument list
        funcargs = []
        unpackings = []

        for argstr in argstrs:
            if iterable(argstr):
                funcargs.append(self._argrepr(Dummy()))
                unpackings.extend(self._print_unpacking(argstr, funcargs[-1]))
            else:
                funcargs.append(argstr)

        if self._exprrepr.__self__.for_class:
            funcargs.insert(0, 'self')

        funcsig = 'def {}({}):'.format(funcname, ', '.join(funcargs))

        # Wrap input arguments before unpacking
        funcbody.extend(self._print_funcargwrapping(funcargs))

        funcbody.extend(unpackings)

        # subs_dict = {}
        for lhs, rhs in extra_assignments.items():
            # subbed_rhs = rhs.subs(subs_dict)
            funcbody.append(self._exprrepr(Assignment(lhs, rhs)))
            # subs_dict[lhs] = subbed_rhs

        funcbody.append('return ({})'.format(self._exprrepr(expr)))

        funclines = [funcsig]
        funclines.extend('    ' + line for line in funcbody)

        return '\n'.join(funclines) + '\n'


text:
package org.apache.ignite.internal.processors.cache.datastructures.replicated;

import org.apache.ignite.cache.*;
import org.apache.ignite.internal.processors.cache.datastructures.*;

import static org.apache.ignite.cache.CacheAtomicityMode.*;
import static org.apache.ignite.cache.CacheMemoryMode.*;
import static org.apache.ignite.cache.CacheMode.*;

/**
 * Failover tests for cache data structures.
 */
public class GridCacheReplicatedDataStructuresFailoverSelfTest
    extends GridCacheAbstractDataStructuresFailoverSelfTest {
    /** {@inheritDoc} */
    @Override protected void beforeTest() throws Exception {
        fail("https://issues.apache.org/jira/browse/IGNITE-801");
    }

    /** {@inheritDoc} */
    @Override protected CacheMode collectionCacheMode() {
        return REPLICATED;
    }

    /** {@inheritDoc} */
    @Override protected CacheMemoryMode collectionMemoryMode() {
        return ONHEAP_TIERED;
    }

    /** {@inheritDoc} */
    @Override protected CacheAtomicityMode collectionCacheAtomicityMode() {
        return TRANSACTIONAL;
    }
}

redpajama_set_name: RedPajamaGithub


text:
import { isEmpty } from 'lodash';
import { useCMEditViewDataManager } from '@strapi/helper-plugin';

function useSelect() {
  const { hasDraftAndPublish, modifiedData } = useCMEditViewDataManager();

  let trackerProperty = {};

  if (hasDraftAndPublish) {
    const isDraft = isEmpty(modifiedData.publishedAt);

    trackerProperty = isDraft ? { status: 'draft' } : { status: 'published' };
  }

  return {
    hasDraftAndPublish,
    trackerProperty,
  };
}

export default useSelect;


text:
#ifndef MODULES_RTP_RTCP_INCLUDE_REMOTE_NTP_TIME_ESTIMATOR_H_
#define MODULES_RTP_RTCP_INCLUDE_REMOTE_NTP_TIME_ESTIMATOR_H_

#include <stdint.h>

#include "absl/types/optional.h"
#include "rtc_base/constructor_magic.h"
#include "rtc_base/numerics/moving_median_filter.h"
#include "system_wrappers/include/rtp_to_ntp_estimator.h"

namespace webrtc {

class Clock;

// RemoteNtpTimeEstimator can be used to estimate a given RTP timestamp's NTP
// time in local timebase.
// Note that it needs to be trained with at least 2 RTCP SR (by calling
// |UpdateRtcpTimestamp|) before it can be used.
class RemoteNtpTimeEstimator {
 public:
  explicit RemoteNtpTimeEstimator(Clock* clock);

  ~RemoteNtpTimeEstimator();

  // Updates the estimator with round trip time |rtt|, NTP seconds |ntp_secs|,
  // NTP fraction |ntp_frac| and RTP timestamp |rtp_timestamp|.
  bool UpdateRtcpTimestamp(int64_t rtt,
                           uint32_t ntp_secs,
                           uint32_t ntp_frac,
                           uint32_t rtp_timestamp);

  // Estimates the NTP timestamp in local timebase from |rtp_timestamp|.
  // Returns the NTP timestamp in ms when success. -1 if failed.
  int64_t Estimate(uint32_t rtp_timestamp);

  // Estimates the offset, in milliseconds, between the remote clock and the
  // local one. This is equal to local NTP clock - remote NTP clock.
  absl::optional<int64_t> EstimateRemoteToLocalClockOffsetMs();

 private:
  Clock* clock_;
  MovingMedianFilter<int64_t> ntp_clocks_offset_estimator_;
  RtpToNtpEstimator rtp_to_ntp_;
  int64_t last_timing_log_ms_;
  RTC_DISALLOW_COPY_AND_ASSIGN(RemoteNtpTimeEstimator);
};

}  // namespace webrtc

#endif  // MODULES_RTP_RTCP_INCLUDE_REMOTE_NTP_TIME_ESTIMATOR_H_


text:
class MediasController < ApplicationController
  include MediasHelper
  THUMB_WIDTH = 1300
  def index
    if !File.exist?(media_cache_path)
      FileUtils.mkdir_p(media_cache_path)
    end
    medias = Rails.cache.fetch('medias-controller-index', expires_in: 60.seconds) do
      Dir[media_path.join('*').to_s].sort_by{ |f| File.mtime(f) }.reverse.map do |path|
        handle_name = "handle_#{File.extname(path)[1..-1].downcase}".to_sym
        if methods.include? handle_name
          handle = method handle_name
          handle.call path
        else
          logger.warn "#{handle_name} not found."
        end
      end
    end
    render json: medias
  end

  def image
    render text: download_image(params[:uri], "#{Digest::SHA256.hexdigest(params[:uri])}.jpg")
  end

  def text
    render text: receive_text(params[:text])
  end

  protected

  def handle_txt(path)
    {
      type: 'text',
      text: File.read(path)
    }
  end

  def handle_jpg(path)
    name = File.basename path
    cache_path = media_cache_path.join(name).to_s
    if !File.exist?(cache_path)
      image = MiniMagick::Image.open(path)
      # width = image.width
      # while width > THUMB_WIDTH
      #   width /= 1.4
      # end
      image.resize("1000>x#{THUMB_WIDTH}>")
      image.write(cache_path)
    end
    meta = MiniMagick::Image.open(cache_path)
    {
      type: 'image',
      src: media_cache_uri(name),
      width: meta.width,
      height: meta.height,
      aspectRatio: (1.0 * meta.width / meta.height).round(2),
      lightboxImage: {
        src: media_uri(name),
      }
    }
  end
end


text:
if (!('assertEquals' in this)) { /* allow running this test standalone */
    imports.lang.copyPublicProperties(imports.jsUnit, this);
    gwkjstestRun = function() { return imports.jsUnit.gwkjstestRun(this); };
}

function assertArrayEquals(expected, got) {
    assertEquals(expected.length, got.length);
    for (let i = 0; i < expected.length; i ++) {
        assertEquals(expected[i], got[i]);
    }
}

const GIMarshallingTests = imports.gi.GIMarshallingTests;

// We use Gio and GLib to have some objects that we know exist
const Gio = imports.gi.Gio;
const GLib = imports.gi.GLib;
const GObject = imports.gi.GObject;
const Lang = imports.lang;

function testCArray() {
    var array, sum;

    var result = GIMarshallingTests.init_function(null);
    assertEquals(result.length, 2);
    var success = result[0];
    var newArray = result[1];
    assertEquals(newArray.length, 0);

    array = GIMarshallingTests.array_zero_terminated_return();
    assertEquals("0", array[0]);
    assertEquals("1", array[1]);
    assertEquals("2", array[2]);
    assertEquals(3, array.length);

    array = GIMarshallingTests.array_zero_terminated_return_struct();
    assertEquals(3, array.length);
    assertEquals(42, array[0].long_);
    assertEquals(43, array[1].long_);
    assertEquals(44, array[2].long_);

    array = GIMarshallingTests.array_return();
    assertEquals(4, array.length);
    assertEquals(-1, array[0]);
    assertEquals(0, array[1]);
    assertEquals(1, array[2]);
    assertEquals(2, array[3]);

    [array, sum] = GIMarshallingTests.array_return_etc(9, 5);
    assertEquals(14, sum);
    assertEquals(4, array.length);
    assertEquals(9, array[0]);
    assertEquals(0, array[1]);
    assertEquals(1, array[2]);
    assertEquals(5, array[3]);

    array = GIMarshallingTests.array_out();
    assertEquals(4, array.length);
    assertEquals(-1, array[0]);
    assertEquals(0, array[1]);
    assertEquals(1, array[2]);
    assertEquals(2, array[3]);

    [array, sum] = GIMarshallingTests.array_out_etc(9, 5);
    assertEquals(14, sum);
    assertEquals(4, array.length);
    assertEquals(9, array[0]);
    assertEquals(0, array[1]);
    assertEquals(1, array[2]);
    assertEquals(5, array[3]);

    array = GIMarshallingTests.array_inout([-1, 0, 1, 2]);
    assertEquals(5, array.length);
    assertEquals(-2, array[0]);
    assertEquals(-1, array[1]);
    assertEquals(0, array[2]);
    assertEquals(1, array[3]);
    assertEquals(2, array[4]);

    [array, sum] = GIMarshallingTests.array_inout_etc(9, [-1, 0, 1, 2], 5);
    assertEquals(14, sum);
    assertEquals(5, array.length);
    assertEquals(9, array[0]);
    assertEquals(-1, array[1]);
    assertEquals(0, array[2]);
    assertEquals(1, array[3]);
    assertEquals(5, array[4]);

    GIMarshallingTests.array_string_in(["foo", "bar"]);

    array = [];
    for (var i = 0; i < 3; i++) {
	array[i] = new GIMarshallingTests.BoxedStruct();
	array[i].long_ = i + 1;
    }

    GIMarshallingTests.array_struct_in(array);

    // Run twice to ensure that copies are correctly made for (transfer full)
    GIMarshallingTests.array_struct_take_in(array);
    GIMarshallingTests.array_struct_take_in(array);

    GIMarshallingTests.array_uint8_in ("abcd");
    GIMarshallingTests.array_enum_in([GIMarshallingTests.Enum.VALUE1,
				      GIMarshallingTests.Enum.VALUE2,
				      GIMarshallingTests.Enum.VALUE3]);

    array = [-1, 0, 1, 2];
    GIMarshallingTests.array_in(array);
    GIMarshallingTests.array_in_len_before(array);
    GIMarshallingTests.array_in_len_zero_terminated(array);
    GIMarshallingTests.array_in_guint64_len(array);
    GIMarshallingTests.array_in_guint8_len(array);
}

function testGArray() {
    var array;
    array = GIMarshallingTests.garray_int_none_return();
    assertEquals(-1, array[0]);
    assertEquals(0, array[1]);
    assertEquals(1, array[2]);
    assertEquals(2, array[3]);
    array = GIMarshallingTests.garray_utf8_none_return()
    assertEquals("0", array[0]);
    assertEquals("1", array[1]);
    assertEquals("2", array[2]);
    array = GIMarshallingTests.garray_utf8_container_return()
    assertEquals("0", array[0]);
    assertEquals("1", array[1]);
    assertEquals("2", array[2]);
    array = GIMarshallingTests.garray_utf8_full_return()
    assertEquals("0", array[0]);
    assertEquals("1", array[1]);
    assertEquals("2", array[2]);

    GIMarshallingTests.garray_int_none_in([-1, 0, 1, 2]);
    GIMarshallingTests.garray_utf8_none_in(["0", "1", "2"]);

    array = GIMarshallingTests.garray_utf8_none_out();
    assertEquals("0", array[0]);
    assertEquals("1", array[1]);
    assertEquals("2", array[2]);
    array = GIMarshallingTests.garray_utf8_container_out();
    assertEquals("0", array[0]);
    assertEquals("1", array[1]);
    assertEquals("2", array[2]);
    array = GIMarshallingTests.garray_utf8_full_out();
    assertEquals("0", array[0]);
    assertEquals("1", array[1]);
    assertEquals("2", array[2]);
}

function testByteArray() {
    var i = 0;
    var refByteArray = new imports.byteArray.ByteArray();
    refByteArray[i++] = 0;
    refByteArray[i++] = 49;
    refByteArray[i++] = 0xFF;
    refByteArray[i++] = 51;
    var byteArray = GIMarshallingTests.bytearray_full_return();
    assertEquals(refByteArray.length, byteArray.length);
    for (i = 0; i < refByteArray.length; i++)
	assertEquals(refByteArray[i], byteArray[i]);
    GIMarshallingTests.bytearray_none_in(refByteArray);

    // Another test, with a normal array, to test conversion
    GIMarshallingTests.bytearray_none_in([0, 49, 0xFF, 51]);
}

function testGBytes() {
    var i = 0;
    var refByteArray = new imports.byteArray.ByteArray();
    refByteArray[i++] = 0;
    refByteArray[i++] = 49;
    refByteArray[i++] = 0xFF;
    refByteArray[i++] = 51;
    GIMarshallingTests.gbytes_none_in(refByteArray);

    var bytes = GIMarshallingTests.gbytes_full_return();
    GIMarshallingTests.gbytes_none_in(bytes);

    var array = bytes.toArray();
    assertEquals(array[0], 0);
    assertEquals(array[1], 49);
    assertEquals(array[2], 0xFF);
    assertEquals(array[3], 51);

    bytes = GLib.Bytes.new([0, 49, 0xFF, 51]);
    GIMarshallingTests.gbytes_none_in(bytes);

    bytes = GLib.Bytes.new("const \u2665 utf8");
    GIMarshallingTests.utf8_as_uint8array_in(bytes.toArray());

    bytes = GIMarshallingTests.gbytes_full_return();
    array = bytes.toArray(); // Array should just be holding a ref, not a copy
    assertEquals(array[1], 49);
    array[1] = 42;  // Assignment should force to GByteArray
    assertEquals(array[1], 42);
    array[1] = 49;  // Flip the value back
    GIMarshallingTests.gbytes_none_in(array.toGBytes()); // Now convert back to GBytes

    bytes = GLib.Bytes.new([97, 98, 99, 100]);
    GIMarshallingTests.array_uint8_in(bytes.toArray());
    assertRaises(function() {
	GIMarshallingTests.array_uint8_in(bytes);
    });
}

function testPtrArray() {
    var array;

    GIMarshallingTests.gptrarray_utf8_none_in(["0", "1", "2"]);

    var refArray = ["0", "1", "2"];

    assertArrayEquals(refArray, GIMarshallingTests.gptrarray_utf8_none_return());
    assertArrayEquals(refArray, GIMarshallingTests.gptrarray_utf8_container_return());
    assertArrayEquals(refArray, GIMarshallingTests.gptrarray_utf8_full_return());

    assertArrayEquals(refArray, GIMarshallingTests.gptrarray_utf8_none_out());
    assertArrayEquals(refArray, GIMarshallingTests.gptrarray_utf8_container_out());
    assertArrayEquals(refArray, GIMarshallingTests.gptrarray_utf8_full_out());
}

function testGValue() {
    assertEquals(42, GIMarshallingTests.gvalue_return());
    assertEquals(42, GIMarshallingTests.gvalue_out());

    GIMarshallingTests.gvalue_in(42);
    GIMarshallingTests.gvalue_flat_array([42, "42", true]);

    // gwkjs doesn't support native enum types
    // GIMarshallingTests.gvalue_in_enum(GIMarshallingTests.Enum.VALUE_3);

    // Test a flat GValue round-trip return
    let thing = GIMarshallingTests.return_gvalue_flat_array();
    assertArrayEquals([42, "42", true], thing);
}

function testGType() {
    assertEquals("void", GObject.TYPE_NONE.name);
    assertEquals("gchararray", GObject.TYPE_STRING.name);

    // Make sure "name" is readonly
    try {
        GObject.TYPE_STRING.name = "foo";
    } catch(e) {
    }
    assertEquals("gchararray", GObject.TYPE_STRING.name);

    // Make sure "name" is permanent
    try {
        delete GObject.TYPE_STRING.name;
    } catch(e) {
    }
    assertEquals("gchararray", GObject.TYPE_STRING.name);

    // Make sure "toString" works
    assertEquals("[object GType for 'void']", GObject.TYPE_NONE.toString());
    assertEquals("[object GType for 'gchararray']", GObject.TYPE_STRING.toString());

    // Marshalling tests
    assertEquals(GObject.TYPE_NONE, GIMarshallingTests.gtype_return());
    assertEquals(GObject.TYPE_STRING, GIMarshallingTests.gtype_string_return());

    GIMarshallingTests.gtype_in(GObject.TYPE_NONE);
    GIMarshallingTests.gtype_in(GObject.VoidType);
    GIMarshallingTests.gtype_string_in(GObject.TYPE_STRING);
    GIMarshallingTests.gtype_string_in(GObject.String);
    GIMarshallingTests.gtype_string_in(String);

    assertEquals(GObject.TYPE_NONE, GIMarshallingTests.gtype_out());
    assertEquals(GObject.TYPE_STRING, GIMarshallingTests.gtype_string_out());

    assertEquals(GObject.TYPE_INT, GIMarshallingTests.gtype_inout(GObject.TYPE_NONE));
}

function testGTypePrototype() {
    assertNull(GIRepositoryGType.name);
    assertEquals("[object GType prototype]", GIRepositoryGType.toString());
}

function testGValueGType() {
    // test that inferring the GType for a primitive value or an object works

    // Primitives (and primitive like)
    GIMarshallingTests.gvalue_in_with_type(42, GObject.TYPE_INT);
    GIMarshallingTests.gvalue_in_with_type(42.5, GObject.TYPE_DOUBLE);
    GIMarshallingTests.gvalue_in_with_type('42', GObject.TYPE_STRING);
    GIMarshallingTests.gvalue_in_with_type(GObject.TYPE_GTYPE, GObject.TYPE_GTYPE);

    GIMarshallingTests.gvalue_in_with_type(42, GObject.Int);
    GIMarshallingTests.gvalue_in_with_type(42.5, GObject.Double);
    GIMarshallingTests.gvalue_in_with_type(42.5, Number);

    // Object and interface
    GIMarshallingTests.gvalue_in_with_type(new Gio.SimpleAction, Gio.SimpleAction);
    GIMarshallingTests.gvalue_in_with_type(new Gio.SimpleAction, GObject.Object);
    GIMarshallingTests.gvalue_in_with_type(new Gio.SimpleAction, GObject.TYPE_OBJECT);
    GIMarshallingTests.gvalue_in_with_type(new Gio.SimpleAction, Gio.SimpleAction);

    // Boxed and union
    GIMarshallingTests.gvalue_in_with_type(new GLib.KeyFile, GLib.KeyFile);
    GIMarshallingTests.gvalue_in_with_type(new GLib.KeyFile, GObject.TYPE_BOXED);
    GIMarshallingTests.gvalue_in_with_type(GLib.Variant.new('u', 42), GLib.Variant);
    GIMarshallingTests.gvalue_in_with_type(GLib.Variant.new('u', 42), GObject.TYPE_VARIANT);
    GIMarshallingTests.gvalue_in_with_type(new GIMarshallingTests.BoxedStruct, GIMarshallingTests.BoxedStruct);
    GIMarshallingTests.gvalue_in_with_type(GIMarshallingTests.union_returnv(), GIMarshallingTests.Union);

    // Other
    GIMarshallingTests.gvalue_in_with_type(GObject.ParamSpec.string('my-param', '', '', GObject.ParamFlags.READABLE, ''),
					   GObject.TYPE_PARAM);

    // Foreign
    let Cairo;
    try {
        Cairo = imports.cairo;
    } catch(e) {
        return;
    }

    let surface = new Cairo.ImageSurface(Cairo.Format.ARGB32, 2, 2);
    let cr = new Cairo.Context(surface);
    GIMarshallingTests.gvalue_in_with_type(cr, Cairo.Context);
    GIMarshallingTests.gvalue_in_with_type(surface, Cairo.Surface);
}

function callback_return_value_only() {
    return 42;
}

function callback_one_out_parameter() {
    return 43;
}

function callback_multiple_out_parameters() {
    return [44, 45];
}

function callback_return_value_and_one_out_parameter() {
    return [46, 47];
}

function callback_return_value_and_multiple_out_parameters() {
    return [48, 49, 50];
}

function testCallbacks() {
    let a, b, c;
    a = GIMarshallingTests.callback_return_value_only(callback_return_value_only);
    assertEquals(42, a);

    a = GIMarshallingTests.callback_one_out_parameter(callback_one_out_parameter);
    assertEquals(43, a);

    [a, b] = GIMarshallingTests.callback_multiple_out_parameters(callback_multiple_out_parameters);
    assertEquals(44, a);
    assertEquals(45, b);

    [a, b] = GIMarshallingTests.callback_return_value_and_one_out_parameter(callback_return_value_and_one_out_parameter);
    assertEquals(46, a);
    assertEquals(47, b);

    [a, b, c] = GIMarshallingTests.callback_return_value_and_multiple_out_parameters(callback_return_value_and_multiple_out_parameters);
    assertEquals(48, a);
    assertEquals(49, b);
    assertEquals(50, c);
}

const VFuncTester = new Lang.Class({
    Name: 'VFuncTester',
    Extends: GIMarshallingTests.Object,

    vfunc_vfunc_return_value_only: callback_return_value_only,
    vfunc_vfunc_one_out_parameter: callback_one_out_parameter,
    vfunc_vfunc_multiple_out_parameters: callback_multiple_out_parameters,
    vfunc_vfunc_return_value_and_one_out_parameter: callback_return_value_and_one_out_parameter,
    vfunc_vfunc_return_value_and_multiple_out_parameters: callback_return_value_and_multiple_out_parameters
});

function testVFuncs() {
    let tester = new VFuncTester();
    let a, b, c;
    a = tester.vfunc_return_value_only();
    assertEquals(42, a);

    a = tester.vfunc_one_out_parameter();
    assertEquals(43, a);

    [a, b] = tester.vfunc_multiple_out_parameters();
    assertEquals(44, a);
    assertEquals(45, b);

    [a, b] = tester.vfunc_return_value_and_one_out_parameter();
    assertEquals(46, a);
    assertEquals(47, b);

    [a, b, c] = tester.vfunc_return_value_and_multiple_out_parameters();
    assertEquals(48, a);
    assertEquals(49, b);
    assertEquals(50, c);
}

function testInterfaces() {
    let ifaceImpl = new GIMarshallingTests.InterfaceImpl();
    let itself = ifaceImpl.get_as_interface();

    assertEquals(ifaceImpl, itself);
}

gwkjstestRun();


text:
#include <boost/type_erasure/any.hpp>
#include <boost/type_erasure/tuple.hpp>
#include <boost/type_erasure/builtin.hpp>
#include <boost/type_erasure/operators.hpp>
#include <boost/type_erasure/any_cast.hpp>
#include <boost/type_erasure/binding_of.hpp>
#include <boost/mpl/vector.hpp>

#define BOOST_TEST_MAIN
#include <boost/test/unit_test.hpp>

using namespace boost::type_erasure;

template<class T = _self>
struct common : ::boost::mpl::vector<
    copy_constructible<T>,
    typeid_<T>
> {};

BOOST_AUTO_TEST_CASE(test_binding_of)
{
    typedef ::boost::mpl::vector<common<> > test_concept;
    any<test_concept> x(2);
    binding<test_concept> b = binding_of(x);
    binding<test_concept> expected(
        make_binding<
            ::boost::mpl::map< ::boost::mpl::pair<_self, int> >
        >());
    BOOST_CHECK(b == expected);
}


text:
#if !defined(FUSION_AT_IMPL_07172005_0726)
#define FUSION_AT_IMPL_07172005_0726

#include <boost/fusion/support/detail/access.hpp>
#include <boost/type_traits/is_const.hpp>
#include <boost/type_traits/add_const.hpp>
#include <boost/mpl/if.hpp>
#include <boost/mpl/bool.hpp>

namespace boost { namespace fusion
{
    namespace detail
    {
        template <typename Cons>
        struct cons_deref
        {
            typedef typename Cons::car_type type;
        };

        template <typename Cons, int I>
        struct cons_advance
        {
            typedef typename
                cons_advance<Cons, I-1>::type::cdr_type
            type;
        };

        template <typename Cons>
        struct cons_advance<Cons, 0>
        {
            typedef Cons type;
        };

        template <typename Cons>
        struct cons_advance<Cons, 1>
        {
            typedef typename Cons::cdr_type type;
        };

        template <typename Cons>
        struct cons_advance<Cons, 2>
        {
#if BOOST_WORKAROUND(BOOST_MSVC, > 1400) // VC8 and above
            typedef typename Cons::cdr_type::cdr_type type;
#else
            typedef typename Cons::cdr_type _a;
            typedef typename _a::cdr_type type;
#endif
        };

        template <typename Cons>
        struct cons_advance<Cons, 3>
        {
#if BOOST_WORKAROUND(BOOST_MSVC, > 1400) // VC8 and above
            typedef typename Cons::cdr_type::cdr_type::cdr_type type;
#else
            typedef typename Cons::cdr_type _a;
            typedef typename _a::cdr_type _b;
            typedef typename _b::cdr_type type;
#endif
        };

        template <typename Cons>
        struct cons_advance<Cons, 4>
        {
#if BOOST_WORKAROUND(BOOST_MSVC, > 1400) // VC8 and above
            typedef typename Cons::cdr_type::cdr_type::cdr_type::cdr_type type;
#else
            typedef typename Cons::cdr_type _a;
            typedef typename _a::cdr_type _b;
            typedef typename _b::cdr_type _c;
            typedef typename _c::cdr_type type;
#endif
        };
    }

    struct cons_tag;

    namespace extension
    {
        template <typename Tag>
        struct at_impl;

        template <>
        struct at_impl<cons_tag>
        {
            template <typename Sequence, typename N>
            struct apply
            {
                typedef typename detail::cons_deref<
                    typename detail::cons_advance<Sequence, N::value>::type>::type
                element;

                typedef typename
                    mpl::if_<
                        is_const<Sequence>
                      , typename detail::cref_result<element>::type
                      , typename detail::ref_result<element>::type
                    >::type
                type;

                template <typename Cons, int N2>
                static type
                call(Cons& s, mpl::int_<N2>)
                {
                    return call(s.cdr, mpl::int_<N2-1>());
                }

                template <typename Cons>
                static type
                call(Cons& s, mpl::int_<0>)
                {
                    return s.car;
                }

                static type
                call(Sequence& s)
                {
                    return call(s, mpl::int_<N::value>());
                }
            };
        };
    }
}}

#endif


text:
<title>
Inside the system
</title>

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<?php include "../../legacy-includes/Script.htmlf" ?>

<?php include "../../legacy-includes/TopLogo.htmlf" ?>

<?php include "../../legacy-includes/TopAd.htmlf" ?>

<?php include "../../legacy-includes/LeftButtons.htmlf" ?>

<?php include "../../legacy-includes/BodyInsert.htmlf" ?>

Inside the system

October 25, 2002 | Page 12

Florida's governor: Jeb Bigot

THE BUSH brothers can't seem to get enough of reveling in other people's pain and misery. First, George W. was caught in a televised interview mocking Karla Faye Tucker--a woman on Texas' death row whose execution he presided over as governor. Now, Dubya's baby brother, Florida Gov. Jeb Bush, is getting into the act.

At a recent meeting with Pensacola lawmakers, Jeb told the crowd that he had "devious plans" to prevent a constitutional amendment which would mandate smaller class sizes. He also said that he wants to "give the legislature the power to set teachers' salaries, bypassing locally elected school boards"--a reversal of the current Republican position.

But he got really vicious when he began to comment on the case of Rilya Wilson, the 6-year-old girl who has been "lost" without a trace in the state's foster care system for more than eight months.

To take the heat off the state's mismanagement, Pamela Graham and Geralyn Smith--Rilya's caregivers--were recently arrested on allegations that they illegally collected public assistance checks.

At the meeting with lawmakers, all Jeb could focus on was frat-boy gossip about the two women--implying that they are lesbians. "Bet you don't get that in Pensacola," Bush quipped.

--Associated Press, October 4, 2002

Barbie's dream house gets invaded

MOVE OVER, G.I. Joe. This year, for just under $45, parents can purchase "Forward Command Post"--a bombed-out version of Barbie's "dream house."

The small-scale, but realistic-looking two-story house has pale yellow walls, checkerboard floors and wood-framed windows. But the glass panes in the windows are cracked, and machine gun fire has sprayed the walls.

On the balcony stands a soldier in battle fatigues clutching an assault rifle. There's also a U.S. flag--to show that the neighborhood has officially been taken over.

If that wasn't bad enough, parents can buy their kids an "Osama bin Laden head," offered by Protect and Serve Toys, "to allow enthusiasts to enact what it may be like when we finally catch him."

--San Francisco Chronicle, October 4, 2002

Heard it through the grapevine

"THIS IS a racist and imperialist war. The warmongers who stole the White House (you call them 'hawks,' but I would never disparage such a fine bird) have hijacked a nation's grief and turned it into a perpetual war on any non-white country they choose to describe as terrorist."

--Actor Woody Harrelson

"TO THE men in Washington, the world is just a giant Monopoly board...The giant industries that are polluting our planet as well as violating human rights worldwide are the ones nearest and dearest to the hearts of American politicians."

--Harrelson

"VOTING IN Dade County is a lot like going to a casino. You hope it will work out, but you know it's beyond your control."

--Rep. Carrie Meek (D-Fla.)

"I DON'T know about this Christopher Columbus parade that is basically celebrating some guy who…found America and then killed all the Indians."

--Sopranos actor Joe Pantoliano, on being barred from New York's Columbus Day Parade

"THERE'S AN old saying. In the days of slavery, there were those slaves who lived on the plantation and were those slaves that lived in the house. You got the privilege of living in the house if you served the master…exactly the way the master intended to have you serve him. Colin Powell's committed to come into the house of the master. When Colin Powell dares to suggest something other than what the master wants to hear, he will be turned back out to pasture."

--Singer Harry Belafonte

<?php include "../../legacy-includes/BottomNavLinks.htmlf" ?>

<?php include "../../legacy-includes/RightAdFolder.htmlf" ?>


text:
from .base import Base
from os.path import isdir

class Filter(Base):

	def __init__(self, vim):
		super().__init__(vim)
		self.name = 'devicons_denite_converter'
		self.description = 'add devicons in front of candidates'

	def filter(self, context):
		for candidate in context['candidates']:

			if 'bufnr' in candidate:
				bufname = self.vim.funcs.bufname(candidate['bufnr'])
				filename = self.vim.funcs.fnamemodify(bufname, ':p:t')
			elif 'word' in candidate and 'action__path' in candidate:
				filename = candidate['word']

			icon = self.vim.funcs.WebDevIconsGetFileTypeSymbol(
				filename, isdir(filename))

			# Customize output format if not done already.
			if icon not in candidate.get('abbr', '')[:10]:
				candidate['abbr'] = ' {} {}'.format(
					icon, candidate.get('abbr', candidate['word']))

		return context['candidates']


text:
<?php

namespace Psy\CodeCleaner;

use PhpParser\Node;
use PhpParser\Node\Expr\Variable;
use Psy\Exception\RuntimeException;

/**
 * Validate that the user input does not reference the `$__psysh__` variable.
 */
class LeavePsyshAlonePass extends CodeCleanerPass
{
    /**
     * Validate that the user input does not reference the `$__psysh__` variable.
     *
     * @throws RuntimeException if the user is messing with $__psysh__
     *
     * @param Node $node
     */
    public function enterNode(Node $node)
    {
        if ($node instanceof Variable && $node->name === '__psysh__') {
            throw new RuntimeException('Don\'t mess with $__psysh__. Bad things will happen.');
        }
    }
}


text:
var _ = require('lodash');

var rest = require('../../dal/browser/rest');

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

module.exports = {

    /**
     * @param {User} user
     * @returns {vow.Promise} resolve with {Point[]}
     */
    getPoints: function (user) {
        return rest.request('list', 'getPoints', {userId: user.getId()}, 'GET')
            .then(function (points) {
                return _.map(points, function (point) {
                    return new Point(point);
                });
            });
    },

    /**
     * @param {User} user
     * @param {Point} point
     * @returns {vow.Promise} resolve with {Point}
     */
    addPoint: function (user, point) {
        var requestParams = {
            userId: user.getId(),
            point: JSON.stringify(point)
        };

        return rest.request('list', 'addPoint', requestParams, 'POST')
            .then(function (point) {
                return new Point(point);
            });
    },

    /**
     * @param {User} user
     * @param {Point} point
     * @returns {vow.Promise}
     */
    checkPoint: function (user, point) {
        var requestParams = {
            userId: user.getId(),
            pointId: point.getId()
        };

        return rest.request('list', 'checkPoint', requestParams, 'POST');
    }

};


text:
using Microsoft.Toolkit.Uwp.UI.Animations;
using News.Data;
using News.Helpers;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Threading.Tasks;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.Media.Core;
using Windows.Storage.Streams;
using Windows.UI.Core;
using Windows.UI.ViewManagement;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Media.Animation;
using Windows.UI.Xaml.Media.Imaging;
using Windows.UI.Xaml.Navigation;

// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238

namespace News
{
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    public sealed partial class DetailsPage : Page
    {
        List<NewsItem> Items;
        NewsItem Item;

        private bool section3FirstTime = true;
        private bool section4FirstTime = true;
        private bool relatedsectionFirstTime = true;
        DispatcherTimer videoControlsTimer;

        bool IsFullscreen = false;

        List<AnimatableSection> animatableSections = new List<AnimatableSection>();

        public DetailsPage()
        {
            Items = NewsItem.GetData().Take(6).ToList();
            this.InitializeComponent();
            Window.Current.SizeChanged += Current_SizeChanged;
            CoreWindow.GetForCurrentThread().KeyDown += DetailsPage_KeyDown;

            Loaded += DetailsPage_Loaded;

            UpdateSize(new Size(Window.Current.Bounds.Width, Window.Current.Bounds.Height));

            RootElement.ViewChanged += RootElement_ViewChanged;

            animatableSections.Add(new AnimatableSection(Section1, Section1Animate));
            animatableSections.Add(new AnimatableSection(Section2, Section2Animate));
            animatableSections.Add(new AnimatableSection(Section3, Section3Animate));
            animatableSections.Add(new AnimatableSection(Section4, Section4Animate));
            animatableSections.Add(new AnimatableSection(VideoSection, VideoSectionAnimate));
            animatableSections.Add(new AnimatableSection(RelatedSection, RelatedSectionAnimate));
        }

        private void DetailsPage_KeyDown(CoreWindow sender, KeyEventArgs args)
        {
            switch (args.VirtualKey)
            {
                case Windows.System.VirtualKey.GamepadX:
                    RelatedGridView.Focus(FocusState.Keyboard);
                    break;
            }
        }

        private void DetailsPage_Loaded(object sender, RoutedEventArgs e)
        {
            AnimateSections();
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            var item = e.Parameter as NewsItem;
            if (item != null)
            {
                Item = item;
            }

            var animationService = ConnectedAnimationService.GetForCurrentView();

            var titleAnimation = animationService.GetAnimation("Title");
            if (titleAnimation != null)
            {
                titleAnimation.TryStart(TitleLine);
            }

            var summaryAnimation = animationService.GetAnimation("Summary");
            if (summaryAnimation != null)
            {
                summaryAnimation.TryStart(SummaryText);
            }

            var likesAnimation = animationService.GetAnimation("Likes");
            if (likesAnimation != null)
            {
                likesAnimation.TryStart(LikesStack);
            }
        }

        protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)
        {
            if (VideoPlayer.IsFullWindow)
            {
                e.Cancel = true;
                VideoPlayer.IsFullWindow = false;
                VideoPlayer.AreTransportControlsEnabled = false;
                PlayButton.Focus(FocusState.Keyboard);
                return;
            }

            if (VideoPlayer.Source != null)
            {
                VideoPlayer.Source = null;
                VideoPlayer.MediaPlayer.CurrentStateChanged -= MediaPlayer_CurrentStateChanged;
            }

            base.OnNavigatingFrom(e);
        }

        private void Current_SizeChanged(object sender, Windows.UI.Core.WindowSizeChangedEventArgs e)
        {
            UpdateSize(e.Size);
            AnimateSections();
        }

        private void UpdateSize(Size size)
        {
            HeroGrid.Height = size.Height;
            Section1.Height = size.Height - 100;
        }

        private void RootElement_ViewChanged(object sender, ScrollViewerViewChangedEventArgs e)
        {
            AnimateSections();
        }

        private void AnimateSections()
        {
            foreach (var section in animatableSections)
            {
                if (IsVisibileToUser(section.Element, RootElement))
                {
                    section.Animate();
                }
            }
        }

        private bool IsVisibileToUser(FrameworkElement element, FrameworkElement container)
        {
            if (element == null || container == null)
                return false;

            if (element.Visibility != Visibility.Visible)
                return false;

            Rect elementBounds = element.TransformToVisual(container).TransformBounds(new Rect(0.0, 0.0, element.ActualWidth, element.ActualHeight));
            Rect containerBounds = new Rect(0.0, 0.0, container.ActualWidth, container.ActualHeight);

            return (elementBounds.Height - (containerBounds.Height - elementBounds.Top)) < (elementBounds.Height / 2);
        }

        private void Section1Animate()
        {
            AuthorLine.Offset(offsetY: 20, duration: 0).Then().Fade(1).Offset().Start();
            GlifMain.Offset(offsetY: 20, duration: 0).Then().Fade(1).Offset().Start();
        }

        private void Section2Animate()
        {
            Section2Image.Offset(offsetY: 40, duration: 0).Then().Fade(1).Offset().Start();
            Section2Border.Offset(offsetY: 40, duration: 0).Then().Fade(1).Offset().SetDelay(100).Start();
            Section2Text.Offset(offsetY: 40, duration: 0).Then().Fade(1).Offset().SetDelay(200).Start();
        }

        private void Section3Animate()
        {
            Section3Image.Offset(offsetY: 40, duration: 0).Then().Fade(1).Offset().Start();
            Section3Text1.Offset(offsetY: 40, duration: 0).Then().Fade(1).Offset().SetDelay(100).Start();
            var anim = Section3Text2.Offset(offsetY: 20, duration: 0).Then().Fade(1).Offset();

            anim.SetDelay(section3FirstTime ? 1000 : 200);
            section3FirstTime = false;

            anim.Start();
        }

        private bool section4animating = false;

        private async void Section4Animate()
        {
            if (section4animating) return;
            section4animating = true;
            if (section4FirstTime)
            {
                section4FirstTime = false;
                Section4Arrow.Clip = new RectangleGeometry() { Rect = new Rect(0, 0, Section4Arrow.DesiredSize.Width, Section4Arrow.DesiredSize.Height) };
                Section4Arrow.Clip.Transform = new CompositeTransform() { ScaleX = 1, ScaleY = 0 };
                Section4Arrow.Opacity = 1;

                await Section4Arrow.Reveal(duration: 1500).StartAsync();
            }

            Section4Glif.Offset(offsetY: 40, duration: 0).Then().Fade(1).Offset().Start();
            Section4Text.Offset(offsetY: 40, duration: 0).Then().Fade(1).Offset().SetDelay(100).Start();
            section4animating = false;
        }

        private void VideoSectionAnimate()
        {
            VideoButton.Offset(offsetY: 40, duration: 0).Then().Fade(1).Offset().Start();
            VideoDescription.Offset(offsetY: 40, duration: 0).Then().Fade(1).Offset().Start();
        }

        private void RelatedSectionAnimate()
        {
            if (relatedsectionFirstTime)
            {
                relatedsectionFirstTime = false;
                RelatedText.Clip = new RectangleGeometry() { Rect = new Rect(0, 0, RelatedText.DesiredSize.Width, RelatedText.DesiredSize.Height) };
                RelatedText.Clip.Transform = new CompositeTransform() { ScaleX = 0, ScaleY = 1 };
                RelatedText.Opacity = 1;

                RelatedText.Reveal().StartAsync();
                RelatedGridView.Offset(offsetY: 40, duration: 0).Then().Fade(1).Offset().SetDelay(100).Start();
            }
        }

        private void VideoButton_Click(object sender, RoutedEventArgs e)
        {
            VideoPlayer.Source = MediaSource.CreateFromUri(new Uri("https://adxlive.blob.core.windows.net/asset-3bc60f5a-b30a-4e7d-9ba1-f2a9ce0fbe13/mjsNapol01_high_high.mp4?sv=2012-02-12&sr=c&si=c1742964-8afb-4eb8-8aea-044beb817f78&sig=EeHuyIoVVavEy84V44K2Dkh%2FMNq6yuwV%2BnaXhrwS0Hw%3D&st=2016-08-28T00%3A18%3A44Z&se=2116-08-28T00%3A18%3A44Z"));

            VideoPlayer.Visibility = Visibility.Visible;
            VideoPlayerShadow.Visibility = Visibility.Visible;

            VideoPlayer.AutoPlay = true;
            VideoPlayer.MediaPlayer.CurrentStateChanged += MediaPlayer_CurrentStateChanged;
            VideoPlayer.TransportControls.IsFullWindowButtonVisible = false;
            VideoPlayer.TransportControls.IsFastForwardButtonVisible = true;
            VideoPlayer.TransportControls.IsFastForwardEnabled = true;
            VideoPlayer.TransportControls.IsFastRewindButtonVisible = true;
            VideoPlayer.TransportControls.IsFastRewindEnabled = true;

            VideoTransportControls.Visibility = Visibility.Visible;

            (sender as Button).Fade(0).Start();
            VideoPlayer.Fade(1).Start();
            VideoTransportControls.Fade(1).SetDelay(200).Start();

            Section4.XYFocusDown = PlayButton;
            RelatedGridView.XYFocusUp = PlayButton;

            (sender as Button).IsEnabled = false;
        }

        private void MediaPlayer_CurrentStateChanged(Windows.Media.Playback.MediaPlayer sender, object args)
        {
            var t = PlayButton.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
            {
                switch (sender.PlaybackSession.PlaybackState)
                {
                    case Windows.Media.Playback.MediaPlaybackState.Playing:
                        PlayPauseIcon.Symbol = Symbol.Pause;
                        PlayButton.IsEnabled = true;
                        break;
                    case Windows.Media.Playback.MediaPlaybackState.Paused:
                        PlayPauseIcon.Symbol = Symbol.Play;
                        PlayButton.IsEnabled = true;
                        break;
                    default:
                        PlayButton.IsEnabled = true;
                        break;
                }
            });

        }

        private void VideoTransportControls_GotFocus(object sender, RoutedEventArgs e)
        {
            VideoTransportControls.Fade(1).Start();

            if (videoControlsTimer == null)
            {
                videoControlsTimer = new DispatcherTimer();
                videoControlsTimer.Tick += VideoControlsTimer_Tick;
                videoControlsTimer.Interval = TimeSpan.FromSeconds(2);
            }

            videoControlsTimer.Start();
        }

        private void VideoControlsTimer_Tick(object sender, object e)
        {
            VideoTransportControls.Fade(0).Start();
        }

        private void VideoTransportControls_LostFocus(object sender, RoutedEventArgs e)
        {
            VideoTransportControls.Fade(0).Start();
            if (videoControlsTimer != null)
            {
                videoControlsTimer.Stop();
            }
        }

        private void PlayButton_Clicked(object sender, RoutedEventArgs e)
        {
            var button = sender as Button;
            if (VideoPlayer.MediaPlayer.PlaybackSession.PlaybackState == Windows.Media.Playback.MediaPlaybackState.Playing)
            {
                VideoPlayer.MediaPlayer.Pause();
            }
            else if (VideoPlayer.MediaPlayer.PlaybackSession.PlaybackState == Windows.Media.Playback.MediaPlaybackState.Paused)
            {
                VideoPlayer.MediaPlayer.Play();
            }
        }

        private void FullScreenButton_Clicked(object sender, RoutedEventArgs e)
        {
            VideoPlayer.AreTransportControlsEnabled = true;
            VideoPlayer.IsFullWindow = true;
        }

        private void VideoTransportControls_PointerEntered(object sender, PointerRoutedEventArgs e)
        {
            VideoTransportControls.Fade(1).Start();
        }

        private void VideoTransportControls_PointerExited(object sender, PointerRoutedEventArgs e)
        {
            VideoTransportControls.Fade(0).Start();
        }

        private void VideoTransportControls_Tapped(object sender, TappedRoutedEventArgs e)
        {

        }
    }

    internal class AnimatableSection
    {
        public FrameworkElement Element { get; set; }
        private Action Animation { get; set; }

        private bool _alreadyAnimated = false;

        public AnimatableSection(FrameworkElement element, Action animation)
        {
            Element = element;
            Animation = animation;
        }

        public void Animate()
        {
            if (_alreadyAnimated) return;

            _alreadyAnimated = true;
            Animation?.Invoke();
        }
    }
}


text:
<!DOCTYPE html>

  <title>A2B</title>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

        <link rel="stylesheet" href="A2B.css"></link>

        <link rel="icon" href="icon.png">

      <button type="button" class="navbar-toggle" align="middle"data-toggle="collapse" data-target="#myNavbar">

      </button>
      Home

                Levels

TX State to H-E-B

Torchy's to Dell Diamond

Austin State Capitol to UT Tower

White House to Smithsonian

MLK Jr. Memorial Library to Smithsonian Castle

Big Ben to Buckingham Palace

Royal Opera House to St. Paul's Cathedral

Tour Eiffel to Grand Palais

Gran Palais to Arc de Triomphe

About the game

Developers

Texas State University in Round Rock to H.E.B.

          <button type="button" class="close" data-dismiss="modal">×</button>

A to B

          How to Play:

          1. Click on the panorama view

          2. Navigate with arrow keys

          3. Find the fastest way from Point A to Point B!

          Remember: The best route is not always the most direct or quickest route. Intersections can be tricky and you may find yourself on the wrong side of the road. Just remember to be patient and enjoy the ride!

          <button type="button" class="btn btn-default" data-dismiss="modal">Ready!</button>


text:
<?php

namespace Arnapou\Toolbox\Config;

interface ConfigInterface extends \ArrayAccess {

	/**
	 *
	 * @param string $key
	 * @param mixed $value
	 */
	public function set($key, $value);

	/**
	 *
	 * @param string $key
	 * @param string $default
	 * @return mixed
	 */
	public function get($key, $default = null);

	/**
	 * load config
	 */
	public function load();

	/**
	 * write config
	 */
	public function write();

	/**
	 * return config as array
	 * @return array
	 */
	public function toArray();
}


text:
layout: post
title: "DEVLAND Nummer 2"
date: 2015-06-08 14:15:12
author: fichtl
tags: [events, devland]
---
Diesen Donnerstag (11.06.) ist unser DEVLAND auf der WeAreDevelopers in Perchtoldsdorf bei Wien zu Gast.

http://www.wearedevelopers.org/

... ausserdem werde ich ein wenig über Engineering Culture bei karriere.at sprechen und wir haben einen RoundTable zum selben Thema. Es gibt auch wieder das beliebte Retro-Gaming und unsere schönen Developer-Bierdeckel.

![](/assets/images/devland-nummer-2/IMG_0399.jpg)


text:
<?php
	ini_set('display_errors', 1);
	error_reporting(E_ALL);

	$from = "emailtest@seoportale";
	$to = "eten@intelliants.com";

	$subject = "PHP Mail Test script";
	$message = "This is a test to check the PHP Mail functionality";
	$headers = "From:" . $from;

	mail($to,$subject,$message, $headers);

	echo "Test email sent";

?>


text:
        Field
            <tip>This is the facet field.</tip>

        <input type="text" class="input-small" bs-typeahead="fields.list" ng-model="panel.field" ng-change="set_refresh(true)">

        Number of tags
            <tip>Specify a maximum number of terms to display (Top N).</tip>

        <input class="input-small" type="number" ng-model="panel.size" ng-change="set_refresh(true)">

        Text Alignment
        <select class="input-large" ng-model="panel.alignment" ng-options="f for f in ['horizontal','vertical(+90)','vertical(-90)','vertical and horizontal','Random']"></select>

        Font Scale
            <tip>Increase the size of the word font</tip>

        <select class="input-mini" ng-model="panel.fontScale" ng-options="f for f in [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]"></select>

        Stop Words
            <tip>Stop Words will be ignored, if checked.</tip>

        <input class="input-small" ng-model="panel.ignoreStopWords" type="checkbox" ng-change="set_refresh(true)"></input>


text:
namespace Fixtures.Azure.AcceptanceTestsAzureSpecials
{
    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.Threading;
    using System.Threading.Tasks;
    using Microsoft.Rest;
    using Microsoft.Rest.Azure;
    using Models;

    /// <summary>
    /// Extension methods for SubscriptionInMethodOperations.
    /// </summary>
    public static partial class SubscriptionInMethodOperationsExtensions
    {
            /// <summary>
            /// POST method with subscriptionId modeled in the method.  pass in
            /// subscription id = '1234-5678-9012-3456' to succeed
            /// </summary>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='subscriptionId'>
            /// This should appear as a method parameter, use value '1234-5678-9012-3456'
            /// </param>
            public static void PostMethodLocalValid(this ISubscriptionInMethodOperations operations, string subscriptionId)
            {
                Task.Factory.StartNew(s => ((ISubscriptionInMethodOperations)s).PostMethodLocalValidAsync(subscriptionId), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
            }

            /// <summary>
            /// POST method with subscriptionId modeled in the method.  pass in
            /// subscription id = '1234-5678-9012-3456' to succeed
            /// </summary>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='subscriptionId'>
            /// This should appear as a method parameter, use value '1234-5678-9012-3456'
            /// </param>
            /// <param name='cancellationToken'>
            /// The cancellation token.
            /// </param>
            public static async Task PostMethodLocalValidAsync(this ISubscriptionInMethodOperations operations, string subscriptionId, CancellationToken cancellationToken = default(CancellationToken))
            {
                await operations.PostMethodLocalValidWithHttpMessagesAsync(subscriptionId, null, cancellationToken).ConfigureAwait(false);
            }

            /// <summary>
            /// POST method with subscriptionId modeled in the method.  pass in
            /// subscription id = null, client-side validation should prevent you from
            /// making this call
            /// </summary>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='subscriptionId'>
            /// This should appear as a method parameter, use value null, client-side
            /// validation should prvenet the call
            /// </param>
            public static void PostMethodLocalNull(this ISubscriptionInMethodOperations operations, string subscriptionId)
            {
                Task.Factory.StartNew(s => ((ISubscriptionInMethodOperations)s).PostMethodLocalNullAsync(subscriptionId), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
            }

            /// <summary>
            /// POST method with subscriptionId modeled in the method.  pass in
            /// subscription id = null, client-side validation should prevent you from
            /// making this call
            /// </summary>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='subscriptionId'>
            /// This should appear as a method parameter, use value null, client-side
            /// validation should prvenet the call
            /// </param>
            /// <param name='cancellationToken'>
            /// The cancellation token.
            /// </param>
            public static async Task PostMethodLocalNullAsync(this ISubscriptionInMethodOperations operations, string subscriptionId, CancellationToken cancellationToken = default(CancellationToken))
            {
                await operations.PostMethodLocalNullWithHttpMessagesAsync(subscriptionId, null, cancellationToken).ConfigureAwait(false);
            }

            /// <summary>
            /// POST method with subscriptionId modeled in the method.  pass in
            /// subscription id = '1234-5678-9012-3456' to succeed
            /// </summary>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='subscriptionId'>
            /// Should appear as a method parameter -use value '1234-5678-9012-3456'
            /// </param>
            public static void PostPathLocalValid(this ISubscriptionInMethodOperations operations, string subscriptionId)
            {
                Task.Factory.StartNew(s => ((ISubscriptionInMethodOperations)s).PostPathLocalValidAsync(subscriptionId), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
            }

            /// <summary>
            /// POST method with subscriptionId modeled in the method.  pass in
            /// subscription id = '1234-5678-9012-3456' to succeed
            /// </summary>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='subscriptionId'>
            /// Should appear as a method parameter -use value '1234-5678-9012-3456'
            /// </param>
            /// <param name='cancellationToken'>
            /// The cancellation token.
            /// </param>
            public static async Task PostPathLocalValidAsync(this ISubscriptionInMethodOperations operations, string subscriptionId, CancellationToken cancellationToken = default(CancellationToken))
            {
                await operations.PostPathLocalValidWithHttpMessagesAsync(subscriptionId, null, cancellationToken).ConfigureAwait(false);
            }

            /// <summary>
            /// POST method with subscriptionId modeled in the method.  pass in
            /// subscription id = '1234-5678-9012-3456' to succeed
            /// </summary>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='subscriptionId'>
            /// The subscriptionId, which appears in the path, the value is always
            /// '1234-5678-9012-3456'
            /// </param>
            public static void PostSwaggerLocalValid(this ISubscriptionInMethodOperations operations, string subscriptionId)
            {
                Task.Factory.StartNew(s => ((ISubscriptionInMethodOperations)s).PostSwaggerLocalValidAsync(subscriptionId), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
            }

            /// <summary>
            /// POST method with subscriptionId modeled in the method.  pass in
            /// subscription id = '1234-5678-9012-3456' to succeed
            /// </summary>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='subscriptionId'>
            /// The subscriptionId, which appears in the path, the value is always
            /// '1234-5678-9012-3456'
            /// </param>
            /// <param name='cancellationToken'>
            /// The cancellation token.
            /// </param>
            public static async Task PostSwaggerLocalValidAsync(this ISubscriptionInMethodOperations operations, string subscriptionId, CancellationToken cancellationToken = default(CancellationToken))
            {
                await operations.PostSwaggerLocalValidWithHttpMessagesAsync(subscriptionId, null, cancellationToken).ConfigureAwait(false);
            }

    }
}


text:
typedef struct _FWL_HMONITOR { void* pData; } * FWL_HMONITOR;

class IFWL_AdapterMonitorMgr {
 public:
  virtual ~IFWL_AdapterMonitorMgr() {}
  virtual int32_t CountMonitors() = 0;
  virtual FWL_HMONITOR GetMonitor(int32_t nIndex) = 0;
  virtual FWL_HMONITOR GetCurrentMonitor() = 0;
  virtual FWL_HMONITOR GetMonitorByRect(const CFX_RectF& rect) = 0;
  virtual FWL_HMONITOR GetMonitorByPoint(FX_FLOAT fx, FX_FLOAT fy) = 0;
  virtual FWL_ERR GetMonitorSize(FWL_HMONITOR hMonitor,
                                 FX_FLOAT& fx,
                                 FX_FLOAT& fy) = 0;
};
#endif


text:
@implementation DLSliceTool

NSArray *DLSliceRect(CGRect rect, CGRectEdge edge, NSArray *sliceItems) {

    __block CGFloat calculatedAmount = edge == CGRectMaxXEdge || edge == CGRectMinXEdge ? CGRectGetWidth(rect) : CGRectGetHeight(rect);
    NSMutableArray *calcItems = [NSMutableArray new];
    [sliceItems enumerateObjectsUsingBlock:^(DLSlice *item, NSUInteger idx, BOOL *stop) {
        if (item.type == DLSliceTypeElementCalculate || item.type == DLSliceTypeSpaceCalculate) {
            [calcItems addObject:item];
        } else {
            calculatedAmount -= item.amount;
        }
    }];

    CGFloat calculatedAmountPerItem = 0;
    if (calcItems.count) {
        calculatedAmountPerItem = calculatedAmount / calcItems.count;
    }

    [calcItems enumerateObjectsUsingBlock:^(DLSlice *slice, NSUInteger idx, BOOL *stop) {
        slice.amount = calculatedAmountPerItem;
    }];

    NSMutableArray *partitions = [NSMutableArray new];
    __block CGRect slice, remainder = rect;
    [sliceItems enumerateObjectsUsingBlock:^(DLSlice *item, NSUInteger idx, BOOL *stop) {

        CGRectDivide(remainder, &slice, &remainder, item.amount, edge);
        if (item.type == DLSliceTypeElement || item.type == DLSliceTypeElementCalculate) {
            [partitions addObject:[NSValue valueWithCGRect:slice]];
        }

    }];

    return partitions;
}

@end

@implementation DLSlice

- (instancetype)initWithAmount:(CGFloat)amount type:(DLSliceType)type
{
    self = [super init];
    if (self) {
        self.amount = amount;
        self.type = type;
    }
    return self;
}
@end


text:
var frameModule = require("ui/frame"),
    homeViewModel = require("./home-view-model");

function pageLoaded(args) {
    var page = args.object;

    page.bindingContext = homeViewModel;
}

function menuItemTap(args) {
    var navigateToPath = homeViewModel.get("menuItems")[args.index].modulePath;

    frameModule.topmost().navigate(navigateToPath);
}

exports.pageLoaded = pageLoaded;
exports.menuItemTap = menuItemTap;


text:
from importlib import import_module

from hutch.settings import STORAGE

def create_store():
    module_name, class_name = STORAGE
    mod = import_module(module_name)
    klass = getattr(mod, class_name)
    store = klass()
    store.load()
    return store


text:
.header {
	background-image: url('../images/binary.jpeg');
	height: 200px;
	background-size: cover;
}

.navbar-text {
	margin-top: 19px;
	margin-bottom: 0px;
}


text:
'use strict';
var request = require('request');

class Codeship {
    constructor(apiKey) {
      if (!apiKey) {
        throw 'Invalid API key error';
      }

      this.URL = 'https://codeship.com/api/v1/';
      this.QUERY_STRING = '?api_key=';
      this.apiKey = apiKey;
    }

    listProjects(callback) {
      let projects = [];
      let project = {};

      request.get(
        {
          url: `${this.URL}projects.json${this.QUERY_STRING}${this.apiKey}`,
        },
        (error, response, body) => {
          if (!error && response.statusCode === 200) {
            var res = JSON.parse(body);
            for (let p of res.projects) {
              project.id = p.id;
              project.uuid = p.uuid;
              project.repoName = p.repository_name;
              project.repoProvider = p.repository_provider;

              // Clone an object and push into projects
              projects.push(JSON.parse(JSON.stringify(project)));
            }

            callback(null, projects);
          } else {
            callback(new Error(error));
          }
        });
    }

    getProject(id, callback) {
      if (!id) {
        callback(new Error('Invalid project ID error'), null);
      }

      request.get(
        {
          url: `${this.URL}projects/${id}.json${this.QUERY_STRING}${this.apiKey}`,
        },
        (error, response, body) => {
          if (!error && response.statusCode === 200) {
            var res = JSON.parse(body);

            callback(null, res);
          } else {
            callback(new Error(error));
          }
        });

    }

    getProjectBuildData(id, callback) {
      if (!id) {
        callback(new Error('Invalid project ID error'), null);
      }

      request.get(
        {
          url: `${this.URL}projects/${id}.json${this.QUERY_STRING}${this.apiKey}`,
        },
        (error, response, body) => {
          if (!error && response.statusCode === 200) {
            var res = JSON.parse(body);
            callback(null, res.builds);
          } else {
            callback(new Error(error));
          }
        });

    }

}

module.exports = Codeship;


text:
require 'spec_helper'

module Spree
  describe ReturnsCalculator, type: :model do
    subject { ReturnsCalculator.new }

    let(:return_item) { build(:return_item) }

    it 'compute_shipment must be overridden' do
      expect do
        subject.compute(return_item)
      end.to raise_error(NotImplementedError)
    end
  end
end


text:
var mongoose = require('mongoose');

var Schema = mongoose.Schema;

// Create a user schema.
var userSchema = new Schema({
  email: { type: String, required: true, unique: true },
  password: { type: String, required: true },
  created_at: Date,
  updated_at: Date
});

// On every save, update the timestamp.
userSchema.pre('save', function(next) {
  var currentDate = new Date();

  // Change the updated_at field to current date
  this.updated_at = currentDate;

  // If created_at doesn't exist, add to that field.
  if (!this.created_at)
    this.created_at = currentDate;
  next();
});

// Map the scehma to database.
var User = mongoose.model('users', userSchema);

module.exports = User;


text:
/* ====================
         MODULES
   ==================== */
var express = require("express");
var bodyParser = require("body-parser");
var mongoose = require("mongoose");

var app = express();
	app.use(bodyParser.urlencoded({ extended: true }));
	app.use(bodyParser.json());
	app.use(express.static(__dirname + "/public"));

	app.use(function(req, res, next) {
		res.setHeader('Access-Control-Allow-Origin', '*');
		res.setHeader('Access-Control-Allow-Methods', 'GET, POST');
		res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type, Authorization');
		next();
	});

/* ====================
          MODELS
   ==================== */
var User = require("./app/models/users");
var Bucket = require("./app/models/buckets");

/* ====================
          ROUTES
   ==================== */
app.get("/buckets", function(req, res) {
	Bucket.find().sort("-createdAt").exec(function(err, data) {
		if (err) res.send(err);
		res.json(data);
	});
});

app.get("buckets/:bucketId", function(req, res) {
	Bucket.findById(req.params.bucketId, function(err, bucket) {
		if (err) res.send(err);
		res.json(bucket);
	});
});

app.post("/buckets", function(req, res) {
	var bucket = new Bucket();

	bucket.title = req.body.title;
	bucket.level = req.body.level;
	bucket.links = req.body.links;
	bucket.author = req.body.author;
	bucket.ownerId = req.body.ownerId;
	bucket.stargazers = [];

	bucket.save(function(err) {
		if (err) res.send(err);
		else {
			User.update(
				{ _id: req.body.ownerId },
				{ $push: { buckets: bucket._id } }
			).exec();
			res.send({ message: "Created bucket." });
		}
	});
});

app.put("/buckets/:bucketId/star", function(req, res) {
	Bucket.findById(req.params.bucketId, function(err, bucket) {
		if (err) res.send(err);

		if (bucket.stargazers.indexOf(req.body.userId) < 0) {
			bucket.stargazers.push(req.body.userId);

			User.update(
				{ _id: req.body.userId },
				{ $push: { stargazing: req.params.bucketId } }
			, function(err, raw) {
				if (err) res.send(err);
				bucket.save(function(err) {
					if (err) res.send(err);
					res.json({
						message: "Bucket starred.",
						bucket: bucket
					});
				});
			});
		} else {
			var index = bucket.stargazers.indexOf(req.body.userId);
			bucket.stargazers.splice(index, 1);

			User.update(
				{ _id: req.body.userId },
				{ $pull: { stargazing: req.params.bucketId } }
			, function(err, raw) {
				if (err) res.send(err);
				bucket.save(function(err) {
					if (err) res.send(err);
					res.json({
						message: "Bucket unstarred.",
						bucket: bucket
					});
				});
			});
		}
	});
});

app.delete("buckets/:bucketId", function(req, res) {
	Bucket.remove({ _id: req.params.bucketId }, function(err, bucket) {
		if (err) res.send(err);
		res.send({ message: "Bucket deleted." });
	});
});

app.get("/users", function(req, res) {
	User.find(function(err, data) {
		if (err) res.send(err);
		res.json(data);
	});
});

app.get("users/:userId", function(req, res) {
	User.findById(req.params.userId, function(err, user) {
		if (err) res.send(err);
		res.json(user);
	});
});

app.post("/users", function(req, res) {
	var user = new User();

	user.oauthId = "temp",
	user.name = req.body.name;
	user.avatarURL = "temp",
	user.profileURL = "temp",
	user.stargazing = [];
	user.buckets = [];

	user.save(function(err) {
		if (err) res.send(err);
		res.json({ message: "Created user." });
	});
});

app.delete("users/:userId", function(req, res) {
	User.remove({ _id: req.params.userId }, function(err, user) {
		if (err) res.send(err);
		res.json({ message: "User deleted." });
	});
});

/* ====================
         DATABASE
   ==================== */
var db = require("./config/database");
mongoose.connect(db.url, function(err, database) {
	if (err) console.log(err);
	else console.log("Connected to database.");
});

/* ====================
        START APP
   ==================== */
app.set("port", (process.env.PORT || 5000));
var server = app.listen(app.get("port"), function() {
	var port = app.get("port");
	console.log("LearnBuckets app listening on port %s", port);
});


text:
/**
 * Created by gt60 on 13-10-22.
 */

var ATTACK_DISTANCE = 20;
var ATTACK          = 1;

var FREEZE_COLOR = cc.color(150, 150, 255);
var NORMAL_COLOR = cc.color(255, 255, 255);

/**
 * action that zombies lose head
 */
var Head = cc.Sprite.extend({
    ctor:function () {
        this._super();
        this.initWithSpriteFrameName("ZombieHead_1.png");

        //lost head animation
        var animate = new LostHeadAction();
        this.runAction(cc.Sequence.create(
                        animate,
                        cc.DelayTime.create(1),
                        cc.CallFunc.create(this.removeFromParent, this))
        );
    }
});

var PaperHead = cc.Sprite.extend({
    ctor:function () {
        this._super();
        this.initWithSpriteFrameName("Head_1.png");

        //lost head animation
        var animate = new PaperLostHeadAction();
        this.runAction(cc.Sequence.create(
            animate,
            cc.DelayTime.create(1),
            cc.CallFunc.create(this.removeFromParent, this))
        );
    }
});

var PoleHead = cc.Sprite.extend({
    ctor:function () {
        this._super();
        this.initWithSpriteFrameName("PoleVaultingZombieHead_1.png");

        //lost head animation
        var animate = new PoleLostHeadAction();
        this.runAction(cc.Sequence.create(
            animate,
            cc.DelayTime.create(1),
            cc.CallFunc.create(this.removeFromParent, this))
        );
    }
});

/**
 * Zombies
 */
var Zombie = cc.Sprite.extend({
    _HP:0,
    _velocity:0,
    _row:0,
    _distance:0,
    _attack:0,
    _target:null,

    _stageList:null,
    _nowAction:null,
    _shadow:null,

    _freezeTime:0,
    _state:null,
    //_stage:null,
    _changeFlag:false,
    _isLive:true,
    _isNoHead:false,
    ctor:function (row, type) {
        this._super();

        //init
        this.initWithSpriteFrameName("Zombie_1.png");
        this.initData(type);
        this._row = row;
        this._target = null;
        //this._state = PZ.ZOMBIE_STATE.NORMAL;
        this._changeFlag = true;
        this._isLive = true;
        this._isNoHead = false;

        this.scheduleUpdate();

        //影子
        this._shadow = cc.Sprite.create(cc.spriteFrameCache.getSpriteFrame("plantshadow32.png"));
        this._shadow.setPosition(cc.p(115, 10));
        this.addChild(this._shadow, -2);
    },
    initData:function(type) {
        this._HP = type.STAGE[0].HP;
        this._velocity = type.VELOCITY;
        this._stageList = type.STAGE.slice(0);
        this._distance = ATTACK_DISTANCE;
        this._attack = ATTACK;
    },
    setRow:function (row) {
        this._row = row;
    },
    getRow:function () {
        return this._row;
    },
    removeState:function (state) {
        this._state &= ~state;
    },
    addState:function (state) {
        this._state |= state;
    },
    getState:function () {
        return this._state;
    },
    isLive:function () {
        return this._isLive;
    },
    onEnter:function () {
        this._super();
        this.getParent().addZombie();
    },
    onExit:function () {
        this._super();
        this.getParent().removeZombie();
    },
    update:function (dt) {
        //冰冻状态监测
        if (this._freezeTime > 0) {
            this._freezeTime -= dt;
        } else {
            if (this.getState() & PZ.ZOMBIE_STATE.FREEZED) {
                this.removeState(PZ.ZOMBIE_STATE.FREEZED);
                this.setFreeze(0);
            }
        }

        if (!(this.getState() & PZ.ZOMBIE_STATE.TIED)) {
            //索敌检测
            this.searchPlant(dt);
        }
        //更新动作
        this.updateAction();
    },
    searchPlant:function (dt) {
        if (this._target == null) {
            this.unschedule(this.attack);
            this.setPosition(cc.p(this.getPositionX() - dt * this._velocity, this.getPositionY()));
            for (var i = 0; i < PZ.CONTAINER.PLANTS[this.getRow() - 1].length; ++i) {
                this._target = PZ.CONTAINER.PLANTS[this.getRow() - 1][i];
                if (this._target && this._target.isLive()
                    && Math.abs(this.getPositionX() - this._target.getPositionX()) < this._distance) {
                    this.addState(PZ.ZOMBIE_STATE.ATTACK);
                    this._changeFlag = true;
                    this.schedule(this.attack, 1);
                    break;
                } else {
                    this._target = null;
                }
            }
        }
    },
    updateAction:function () {
        this.checkStage();

        if (this._stageList.length == 1) {
            if (this._isLive) {
                this.die();
                this._changeFlag = false;
            }
        }

        if (this._changeFlag) {
            var action;
            if (this.getState() & PZ.ZOMBIE_STATE.ATTACK) {
                action = createAnimaeByStage(this._stageList[0].ACTION + 1);
            } else {
                action = createAnimaeByStage(this._stageList[0].ACTION);
            }
            this._nowAction = cc.Speed.create(action, 1);
            this.stopAllActions();
            this.runAction(this._nowAction);

            //以下逻辑是为了阶段改变时重新冰冷,即减慢帧
            if (this.getState() & PZ.ZOMBIE_STATE.FREEZED) {
                this._nowAction.setSpeed(0.5);
            }

            this._changeFlag = false;
        }
    },
    setFreeze:function (time) {
        if (time) {
            if (!(this.getState() & PZ.ZOMBIE_STATE.FREEZED)) {
                this._nowAction.setSpeed(0.5);
                this.setColor(FREEZE_COLOR);
                this._velocity /= 2;
                this._attack /= 2;
            }

            this.addState(PZ.ZOMBIE_STATE.FREEZED);
            this._freezeTime = time;
        } else {
            this._nowAction.setSpeed(1);
            this._velocity *= 2;
            this._attack *= 2;
            this.setColor(NORMAL_COLOR);
        }
    },
    attack:function () {
        if (this._target) {
            this._target.hurt(this._attack);
        }
        if (this._target && !this._target.isLive()) {
            this._target = null;
            this.removeState(PZ.ZOMBIE_STATE.ATTACK);
            this._changeFlag = true;
        }
    },
    hurt:function (value) {
        this._HP -= value;
        var action1 = cc.FadeTo.create(0.05, 120);
        var action2 = cc.FadeIn.create(0.05, 255);
        this.runAction(cc.Sequence.create(action1, action2));
    },
    _dieAndClear:function () {
        this._isLive = false;
        for (var i = 0; i < PZ.CONTAINER.ZOMBIES.length; ++i) {
            if (PZ.CONTAINER.ZOMBIES[this.getRow() - 1][i] == this) {
                PZ.CONTAINER.ZOMBIES[this.getRow() - 1][i] = null;
                break;
            }
        }
    },
    die:function () {
        this.setOpacity(255);
        this._dieAndClear();

        var animate = createAnimaeByStage(this._stageList[0].ACTION);
        var action = cc.Sequence.create(
            cc.CallFunc.create(this.unscheduleUpdate, this),
            animate,
            cc.DelayTime.create(1.5),
            cc.CallFunc.create(this.removeFromParent, this)
        );
        this.stopAllActions();
        this.runAction(action);
    },
    bombDie:function () {
        this._dieAndClear();

        var animate = new BombDieAction();
        var action = cc.Sequence.create(
            cc.CallFunc.create(this.unscheduleUpdate, this),
            animate,
            cc.DelayTime.create(1),
            cc.CallFunc.create(this.removeFromParent, this)
        );
        this.stopAllActions();
        this.runAction(action);

    },
    eaten:function () {
        this._dieAndClear();
        this.removeFromParent(true);
    },
    _isIceTied:false,
    setIceTie:function (time) {
        this.setColor(cc.color(120, 120, 255));
        this.addState(PZ.ZOMBIE_STATE.TIED);

        var ice = new IceTrap(time);
        ice.setPosition(this._shadow.getPosition());
        this.addChild(ice, 1);

        if (this._isIceTied == false) {
            this.getActionManager().pauseTarget(this);
            this._isIceTied = true;
        } else {
            this.unschedule(this.iceRecover);
        }
        this.scheduleOnce(this.iceRecover, time);
    },
    iceRecover:function () {
        if (!(this.getState() & PZ.ZOMBIE_STATE.FREEZED)) {
            this.setColor(cc.color(255, 255, 255));
        }
        this.getActionManager().resumeTarget(this);
        this._isIceTied = false;
        this.removeState(PZ.ZOMBIE_STATE.TIED)
    },
    checkStage:function () {
        //override me
    },
    lostHead:function () {
        //override me
    }
});

var NormalZombie = Zombie.extend({
    checkStage:function () {
        for (var i = 1; i < this._stageList.length; ) {
            if (this._stageList[0].ACTION == PZ.ZOMBIE_STAGE.NO_HEAD
                || this._stageList[0].ACTION == PZ.ZOMBIE_STAGE.FLAG_NO_HEAD) {
                if (!this._isNoHead) {
                    this.lostHead();
                }
            }
            if (this._HP <= this._stageList[0].HP && this._HP > this._stageList[1].HP) {
                break;
            } else {
                this._stageList.shift();
                this._changeFlag = true;
            }
        }
    },
    lostHead:function () {
        this._isNoHead = true;
        var head = new Head();
        head.setPosition(cc.pAdd(this.getPosition(), cc.p(80, 0)));
        this.getParent().addChild(head);
    }
});

var NewspaperZombie = Zombie.extend({
    _lostPaper:false,
    ctor:function (row) {
        this._super(row, ZombieType.NewspaperZombie);
        this.setAnchorPoint(cc.p(0.5, 0.4));
        this._lostPaper = false;
    },
    checkStage:function () {
        for (var i = 1; i < this._stageList.length; ) {
            if (this._stageList[0].ACTION == PZ.ZOMBIE_STAGE.PAPER_NO_HEAD_SLOW) {
                if (!this._isNoHead) {
                    this.lostHead();
                }
            }
            if (this._lostPaper) {
                if (this._stageList[0].ACTION == PZ.ZOMBIE_STAGE.PAPER_SLOW) {
                    this._stageList[0] = {HP:this._stageList[0].HP, ACTION:PZ.ZOMBIE_STAGE.PAPER_FAST};
                } else if (this._stageList[0].ACTION == PZ.ZOMBIE_STAGE.PAPER_NO_HEAD_SLOW) {
                    this._stageList[0] = {HP:this._stageList[0].HP, ACTION:PZ.ZOMBIE_STAGE.PAPER_NO_HEAD_FAST};
                }
            }
            if (this._HP <= this._stageList[0].HP && this._HP > this._stageList[1].HP) {
                break;
            } else {
                this._stageList.shift();
                this._changeFlag = true;
            }
        }
    },
    lostHead:function () {
        this._isNoHead = true;
        var head = new PaperHead();
        head.setPosition(cc.pAdd(this.getPosition(), cc.p(40, 0)));
        this.getParent().addChild(head);
    },
    hurt:function (value) {
        if (this._lostPaper) {
            this._HP -= value * 1.5;
        } else {
            this._HP -= value;
        }
        var action1 = cc.FadeTo.create(0.05, 120);
        var action2 = cc.FadeIn.create(0.05, 255);
        this.runAction(cc.Sequence.create(action1, action2));

        if (!this._lostPaper && (this._stageList[0].ACTION == PZ.ZOMBIE_STAGE.PAPER_SLOW
            || this._stageList[0].ACTION == PZ.ZOMBIE_STAGE.PAPER_SLOW_ATTACK)) {
            this._lostPaper = Math.random() > 0.1;
            if (this._lostPaper) {
                var oldv = this._velocity;
                var action = new PaperLostPaperAction();
                this.stopAllActions();
                this.runAction(cc.Sequence.create(
                    cc.CallFunc.create(function (sender) {
                        sender._velocity = 0;
                    }, this),
                    action,
                    cc.CallFunc.create(function (sender) {
                        sender._velocity = oldv * 2.5;
                        sender._changeFlag = true;
                    }, this)
                ));
                this._attack *= 2;
            }
        }
    },
    bombDie:function () {
        this.setPosition(cc.pAdd(this.getPosition(), cc.p(-25, -10)));
        this._super();
    }
});

var PoleZombie = Zombie.extend({
    ctor:function (row) {
        this._super(row, ZombieType.PoleZombie);
        this.setAnchorPoint(cc.p(0.5, 0.4));
        this._shadow.setPosition(cc.p(240, 20));
    },
    checkStage:function () {
        for (var i = 1; i < this._stageList.length; ) {
            if (this._stageList[0].ACTION == PZ.ZOMBIE_STAGE.POLE_NO_HEAD) {
                if (!this._isNoHead) {
                    this.lostHead();
                }
            }
            if (this._HP <= this._stageList[0].HP && this._HP > this._stageList[1].HP) {
                break;
            } else {
                this._stageList.shift();
                this._changeFlag = true;
            }
        }
    },
    lostHead:function () {
        this._isNoHead = true;
        this._velocity /= 2;
        var head = new PoleHead();
        head.setPosition(cc.pAdd(this.getPosition(), cc.p(20, 0)));
        this.getParent().addChild(head);
    },
    searchPlant:function (dt) {
        if (this._target == null) {
            this.unschedule(this.attack);
            this.setPosition(cc.p(this.getPositionX() - dt * this._velocity, this.getPositionY()));
            for (var i = 0; i < PZ.CONTAINER.PLANTS[this.getRow() - 1].length; ++i) {
                this._target = PZ.CONTAINER.PLANTS[this.getRow() - 1][i];
                if (this._target && this._target.isLive()
                    && Math.abs(this.getPositionX() - this._target.getPositionX()) < this._distance) {
                    if (this._stageList[0].ACTION == PZ.ZOMBIE_STAGE.POLE_FAST) {
                        if (this._target.getContentSize().height <= 115) {
                            var action = new PoleJumpAction();
                            this.stopAllActions();
                            this.runAction(cc.Sequence.create(
                                action,
                                cc.CallFunc.create(function (sender) {
                                    sender._stageList[0] = {HP:sender._stageList[0].HP, ACTION:PZ.ZOMBIE_STAGE.POLE_SLOW};
                                    sender._changeFlag = true;
                                    sender._velocity /= 2;
                                    sender._target = null;
                                }, this)
                            ));
                            break;
                        } else {
                            this._stageList[0] = {HP:this._stageList[0].HP, ACTION:PZ.ZOMBIE_STAGE.POLE_SLOW};
                            this._changeFlag = true;
                            this._velocity /= 2;
                            this._target = null;
                        }
                    } else {
                        this.addState(PZ.ZOMBIE_STATE.ATTACK);
                        this._changeFlag = true;
                        this.schedule(this.attack, 1);
                        break;
                    }
                } else {
                    this._target = null;
                }
            }
        }
    },
    bombDie:function () {
        this.setPosition(cc.pAdd(this.getPosition(), cc.p(38, -25)));
        this._shadow.setPosition(cc.pAdd(this._shadow.getPosition(), cc.p(-130, -10)));
        this._super();
    }
});


text:
require 'test_helper'

module PortfolioEngine
  class PortfolioTest < ActiveSupport::TestCase
    # test "the truth" do
    #   assert true
    # end
  end
end