text:
"""Extracts timings from the given session.
"""

import os
import sys

import pandas as pd
#import matplotlib.pyplot as plt
import radical.pilot.utils as rpu
import radical.utils as ru

__author__ = "Matteo Turilli"
__copyright__ = "Copyright 2015, The AIMES Project"
__license__ = "MIT"
__credits__ = ["Andre Merzky"]

# -----------------------------------------------------------------------------
#
def usage(msg=None, noexit=False):

    if msg:
        print "\n      Error: %s" % msg

    print """
    usage   : %s <sid> [<timing>] [<n_pilots>]
    example : %s 5490ba7174df926284f8ef48 [Tx] [3]

    arguments
        <sid>        : session id
        [<timing>]   : optional -- type of timing
        [<n_pilots>] : optional -- number of pilots in the session required to
                                   have run at least a unit

    The tool extracts timings from the given session. By default, the tool
    output all the available timings. If a timing is specified, only that
    timing is outputed. Valid timings are:

        - Tx  : time spent from when the first Compute Unit has been scheduled
                for execution on an active pilot to the time when the last
                Compute Unit has finished.

        - Th  : time spent from the start of the session to when the first
                Compute Unit has been executed. Th includes the following
                events:

                0.  creating session;
                1.  creating RP managers;
                2.  describing the pilots;
                3.  describing the units;
                4.  submitting the pilots to the target resources;
                5.  pilot(s) queuing time on the remote resource;
                6.  [staging data, in case of early binding];
                7.  pilot becoming active - i.e. agent bootstrap;
                8.  [staging data, for queuing time < staging time in case of
                    early binding; always for late binding];
                9.  scheduling CUs.

        - TTC : total time to completion of the whole session. TTC includes
                the following events:

                0.  creating session;
                1.  creating RP managers;
                2.  describing the pilots;
                3.  describing the units;
                4.  submitting the pilots to the target resources;
                5.  pilot(s) queuing time on the remote resource;
                6.  [staging data, in case of early binding];
                7.  pilot becoming active - i.e. agent bootstrap;
                8.  [staging data, for queuing time < staging time in case of
                    early binding; always for late binding];
                9.  scheduling CUs;
                10. Executing CUs;
                11. [Staging data out]
                12. [Canceling pilots]
                13. Deleting pilot and unit managers
                14. Closing session

        - Tc  : aggregated time-core available, the sum of #cores * pilot
                duration. Note that pilot duration is different from pilot
                walltime. Walltime = max duration, duration the time during
                which the pilot has been effectively active. Tc includes the
                following events:

                0.  pilot(s) become ACTIVE.
                1.  pilot(s) become DONE/CANCEL.

        - T?  : aggregated time spent staging data in (in the code as Ti).

        - T!  : aggregated time spent staging data out (in the code as To).

        - Ts  : aggregated time spent staging data.

    """ % (sys.argv[0], sys.argv[0])

    if msg:
        sys.exit(1)

    if not noexit:
        sys.exit(0)

# -----------------------------------------------------------------------------
#
def collapse_ranges(ranges):
    """
    given be a set of ranges (as a set of pairs of floats [start, end] with
    'start <= end'. This algorithm will then collapse that set into the
    smallest possible set of ranges which cover the same, but not more nor
    less, of the domain (floats).

    We first sort the ranges by their starting point. We then start with the
    range with the smallest starting point [start_1, end_1], and compare to the
    next following range [start_2, end_2], where we now know that start_1 <=
    start_2. We have now two cases:

    a) when start_2 <= end_1, then the ranges overlap, and we collapse them
       into range_1: range_1 = [start_1, max[end_1, end_2]

    b) when start_2 > end_2, then ranges don't overlap. Importantly, none of
       the other later ranges can ever overlap range_1. So we move range_1 to
       the set of final ranges, and restart the algorithm with range_2 being
       the smallest one.

    Termination condition is if only one range is left -- it is also moved to
    the list of final ranges then, and that list is returned.
    """

    final = []

    # sort ranges into a copy list
    _ranges = sorted (ranges, key=lambda x: x[0])
#    print _ranges
    START = 0
    END = 1

    base = _ranges[0] # smallest range

    for _range in _ranges[1:]:

        if _range[START] <= base[END]:

            # ranges overlap -- extend the base
            base[END] = max(base[END], _range[END])

        else:

            # ranges don't overlap -- move base to final, and current _range
            # becomes the new base
            final.append(base)
            base = _range

    # termination: push last base to final
    final.append(base)
    return final

#------------------------------------------------------------------------------
#
def get_Toverlap(df, start_state, stop_state):
    '''
    Helper function to create the list of lists from which to calculate the
    overlap of the elements of a DataFrame between the two boundaries passed as
    arguments.
    '''

    overlap = 0
    ranges = []
    tmp = 0.0

#    print start_state, df[start_state].max()
#    print stop_state, df[stop_state].max()
    for index, row in df.iterrows():
        if not pd.isnull(row[start_state]) and not pd.isnull(row[stop_state]):
            ranges.append([row[start_state], row[stop_state]])

    '''
    There have been instances where the individual time arrays in ranges
    appeared out of order. The error was originally suspected to be found
    in only large number of course and lead to negative numbers, but this
    occurs more often than not. Further investigation is required to
    understand how timings are record. The below fix is temporary and
    experimental - Ming
    '''

    for rng in ranges:
       if rng[0] > rng[1]:
            tmp = rng[0]
            rng[0] = rng[1]
            rng[1] = tmp

    for crange in collapse_ranges(ranges):
        overlap += crange[1] - crange[0]
#        print overlap, type(crange[1])

    return overlap

#------------------------------------------------------------------------------
#
def roundup(x, y):
    return x if x % y == 0 else x + y - x % y

#------------------------------------------------------------------------------
#
def plot_overlaps(sf, uf, pilots, pdir):
    '''
    Plot a diagram showing the duration for each state on a single timeline.
    '''

    colors = ['#64B5CD', '#8DAFFD', '#B8CFF8', '#EEEFFF']

    sid = sf.iloc[0]['sid']
    npilots = int(sf.iloc[0]['n_pilots'])
    nunits = int(sf.iloc[0]['n_units'])
    binding = sf.iloc[0]['binding']
    time_distr = sf.iloc[0]['time_distr']

    pdir = pdir+'/'+binding+'_'+time_distr

    title = "Execution Process Session %s" % sid

    stbinding = "Binding: %s; " % binding
    stpilot = "Pilots: %s/%s; " % (len(pilots), npilots)
    stunits = "Units: %s/%s; " %  (len(uf), nunits)

    if time_distr == 'gauss':
        sttdistr = "Time distribution: semi-Gaussian."
    else:
        sttdistr = "Time distribution: %s." % time_distr

    subtitle = stpilot + stunits + stbinding + sttdistr

    ofile = "%s/plot-overlap_pilots-%s_units-%s_sid-%s.pdf" % (
        pdir, npilots, nunits, sid)

    plt.figure(figsize=(17, 10))

    # xlen = roundup(int(sf.iloc[0]['finished']),
    #                10**(len(str(int(sf.iloc[0]['finished'])))-2))
    xlen = roundup(int(sf.iloc[0]['finished']), 10)
    ylen = roundup(len(uf), 10**(len(str(len(uf)))-1))

    plt.axis([0,xlen, 0,ylen])

    plt.ylabel('Number of CUs')
    plt.xlabel('Time (s)')

    plt.suptitle(title, fontsize=14, fontweight='bold')
    plt.title(subtitle)

    # Radical.pilot scheduling overhead (??)
    plt.hlines(uf.index.get_values(),
               uf['ExecutingPending'],
               uf['Scheduling'],
               label='PO_sched',
               color='#000000',
               linewidth=2)

    # Radical.pilot scheduling overhead (??)
    plt.hlines(uf.index.get_values(),
               uf['Scheduling'],
               uf['Executing'],
               color='#000000',
               linewidth=2)

    # Radical.pilot wait for executing CU. Setup time + queuing time.
    plt.hlines(uf.index.get_values(),
               uf['New'],
               uf['PendingInputStaging'],
               label='Tw',
               color='#DDDCDB',
               linewidth=10)

    # Queue time for each pilot
    for idx in pilots.index.get_values():
        print pilots.index.get_values()
        c = colors[idx]
        plt.hlines(uf[uf['pid'] == pilots['pid'][idx]].index.get_values(),
                   pilots['PendingLaunch'][idx],
                   pilots['Active'][idx],
                   label="Tq%s" % idx,
                   color=c,
                   linewidth=8)

    # Getting ready to stage data in.
    plt.hlines(uf.index.get_values(),
               uf['PendingInputStaging'],
               uf['StagingInput'],
               label='Ti/To',
               color='#DC5E4B',
               linewidth=4)

    # Ti staging data in.
    plt.hlines(uf.index.get_values(),
               uf['StagingInput'],
               uf['ExecutingPending'],
               color='#DC5E4B',
               linewidth=4)

    # CU execution.
    plt.hlines(uf.index.get_values(),
               uf['Executing'],
               uf['PendingOutputStaging'],
               label='Tx',
               color='#AFDD8A',
               linewidth=2)

    # Getting ready to stage data out.
    plt.hlines(uf.index.get_values(),
               uf['PendingOutputStaging'],
               uf['StagingOutput'],
               color='#DC5E4B',
               linewidth=1)

    # Staging data out.
    plt.hlines(uf.index.get_values(),
               uf['StagingOutput'],
               uf['Done'],
               color='#DC5E4B',
               linewidth=1)

    # Legend outside the diagram
    plt.legend(bbox_to_anchor=(1.01, 1), loc=2, borderaxespad=0.)
    #plt.legend()

    plt.savefig(ofile)

# -----------------------------------------------------------------------------
#
if __name__ == '__main__':

    session = None
    q_pilots = None
    timing = None
    timings = {}
    #pdir = os.environ['PLOT_DIR']

    cachedir = os.getcwd()
    dburl = 'mongodb://mingtaiha:mingtaiha@ds053838.mongolab.com:53838/hicomb'
    mongo, db, dbname, cname, pname = ru.mongodb_connect(str(dburl))

    if len(sys.argv) <= 1:
        usage("insufficient arguments -- need session ID")

    if len(sys.argv) > 4:
        usage("too many arguments -- no more than 3")

    if len(sys.argv[1]) < 20:
        usage("illegal session token -- valid e.g. 54b1c5d523769c2f1b55dffd")
    else:
        session = sys.argv[1]

    if len(sys.argv) > 2:
        timing = sys.argv[2]

    if len(sys.argv) > 3:
        q_pilots = int(sys.argv[3])

#    print session
    s_frame, p_frame, u_frame = rpu.get_session_frames(session, dburl, cachedir)

    #print p_frame['n_units'][0]

    # Add metadata to the session DF
    s_frame['binding'] = os.environ['BINDING']
    s_frame['time_distr'] = os.environ['TIME_DISTR']

    # Drop failed CUs
    units = u_frame[u_frame.Done.notnull()]

    # print units.ix[units['Scheduling'].idxmin()]['Scheduling']
    u_first = units.ix[units['Scheduling'].idxmin()]['Scheduling']

    # u_last = units.ix[units['finished'].idxmax()]['finished']
    u_last = units.ix[units['Done']].idxmax()['Done']

    pilots = p_frame[p_frame['n_units'] > 0]
    cores = pilots['cores'].sum()

    # Calculate timings by overlap
#    PO_setup = get_Toverlap(units, 'New',                  'PendingInputStaging')
#    Ti_trsfr = get_Toverlap(units, 'PendingInputStaging',  'StagingInput')
    #PO_setup = get_Toverlap(units, 'New',                  'StagingInput')
    #Ti_trsfr = get_Toverlap(units, 'PendingInputStaging',  'StagingInput')
#    Ti_setup = get_Toverlap(units, 'StagingInput',         'ExecutingPending')
#    PO_exec  = get_Toverlap(units, 'ExecutingPending',     'Scheduling')
#    Tx_sched = get_Toverlap(units, 'Scheduling',           'Executing')
#    Tx_exec  = get_Toverlap(units, 'Executing',            'PendingOutputStaging')
#    To_setup = get_Toverlap(units, 'PendingOutputStaging', 'StagingOutput')
#    To_trsfr = get_Toverlap(units, 'StagingOutput',        'Done')

    # TODO: PendingOutputStaging is not populated by the dataframe module so
    # the overhead of the staging out is mistakenly aggegated into Tx.
    # Tx_exec  = get_Toverlap(units, 'Executing', 'PendingOutputStaging')
    # To_setup = get_Toverlap(units, 'PendingOutputStaging', 'StagingOutput')

    # NOTE: This TTC includes the overlapping among timings - Tx, Ts, Th, ...
    # The difference between TTC and the sum of the timings needs to be
    # normalized. A trivial normalization is to distributed the overalap
    # equally among all the states.

#    print s_frame
#    print p_frame
#    print u_frame.iloc[-1]
#    print Tx_sched, Tx_exec

#    timings['TTC'] = s_frame['finished'][0]

#    timings['T_New'] = get_Toverlap(units, 'New', 'Scheduling')
#    timings['T_USch'] = get_Toverlap(units, 'Scheduling', 'PendingInputStaging')
#    timings['T_USIP'] = get_Toverlap(units, 'PendingInputStaging', 'StagingInput')
#    timings['Tq'] = get_Toverlap(units, 'StagingInput', 'AgentStagingInputPending')
#    timings['T_ASIP'] = get_Toverlap(units, 'AgentStagingInputPending', 'AgentStagingInput')
#    timings['T_ASI'] = get_Toverlap(units, 'AgentStagingInput', 'ExecutingPending')
#    timings['T_EP'] = get_Toverlap(units, 'ExecutingPending', 'Executing')
#    timings['Te'] = get_Toverlap(units, 'Executing', 'AgentStagingOutputPending')
#    timings['T_ASOP'] = get_Toverlap(units, 'AgentStagingOutputPending', 'AgentStagingOutput')
#    timings['T_ASO'] = get_Toverlap(units, 'AgentStagingOutput', 'PendingOutputStaging')
#    timings['T_USOP'] = get_Toverlap(units, 'PendingOutputStaging', 'StagingOutput')
#    timings['T_USO'] = get_Toverlap(units, 'StagingOutput', 'Done')

#    print p_frame.columns
#    print units.columns

    timings['TTC'] = s_frame['finished'][0]
    timings['Tq'] = get_Toverlap(p_frame, 'PendingActive', 'Active')
    timings['Ti'] = get_Toverlap(units, 'AgentStagingInputPending', 'AgentStagingInput') - timings['Tq']
    timings['To'] = get_Toverlap(units, 'AgentStagingOutputPending', 'PendingOutputStaging')
    timings['Tx'] = get_Toverlap(units, 'Executing', 'AgentStagingOutputPending')
    timings['Ts'] = timings['Ti'] + timings['To']

#
#   The following code was used to investigate the state diagram of RP 0.40. This has since been resolved
#

    '''
    pilot_timings = []
    units_timings = []
    pilot_stages = ['New', 'Launching', 'PendingActive', 'Active']
    units_stages = ['New', 'Scheduling', 'PendingInputStaging', 'StagingInput', 'AgentStagingInputPending', 'AgentStagingInput', \
                'ExecutingPending', 'Executing', 'AgentStagingOutputPending', 'AgentStagingOutput', 'PendingOutputStaging', 'StagingOutput', 'Done']

    for pilot_stage in pilot_stages:
        pilot_timings.append([str(pilot_stage), p_frame[pilot_stage].min(), p_frame[pilot_stage].max()])

    for unit_stage in units_stages:
        units_timings.append([unit_stage, units[unit_stage].min(), units[unit_stage].max()])

    import csv

    pilot_name = session + "_pilots.csv"
    unit_name = session + "_units.csv"

    print pilot_timings
    print units_timings

    with open(pilot_name, "wb") as f:
        writer = csv.writer(f)
        writer.writerows(pilot_timings)

    with open(unit_name, "wb") as f:
        writer = csv.writer(f)
        writer.writerows(units_timings)
    '''

#    timings['Th'] = units.ix[units['Scheduling'].idxmin()]['Scheduling']
#    timings['Tc'] = (pilots['finished'] - pilots['started']).sum() / len(pilots)

#    timings['Tx'] = Tx_sched + Tx_exec
#    timings['Tx'] = Tx_exec

    #timings['Ti'] = Ti_setup + Ti_trsfr
    #timings['Ti'] = Ti_setup
#    timings['Ti'] = get_Toverlap(units, 'PendingInputStaging',  'ExecutingPending')

    #timings['To'] = To_setup + To_trsfr
#    timings['To'] = get_Toverlap(units, 'PendingOutputStaging',  'Done')

#    timings['Ts'] = timings['Ti'] + timings['To']

    # TODO: Once PandingOutputStaging will be available, calculate To by sum.
    #timings['To'] = To_setup + To_trsfr

    # NOTE: this measure the average staging time for each CU, not the total
    # amount of time spent doing staging during a run. As such, these values
    # cannot be used in a comparison with the TTC of the run. For that
    # comparison, the total overlap of the staging times for each CU need to be
    # calculated.
    #timings['Tx'] = u_last - u_first
    #timings['To'] = (units['Done'] - units['StagingOutput']).sum() / len(units)
    #timings['Ti'] = (units['ExecutingPending'] - units['StagingInput']).sum() / len(units)
    #timings['Ts'] = timings['Ti'] + timings['To']

    # TODO: calculate the intersection between Ti and Tc for early binding when
    # the two timings are indipendent.
    #PO = PO_setup + PO_exec
    #Tq = p_frame['Active'].sum() - p_frame['PendingLaunch'].sum()

    # Write a plot for the session with the state overlaps
    # plot_overlaps(s_frame, units, pilots, pdir)

    #print timings['Ti']
    #print timings['To']
    #print timings['Tx']

    if timing:

        if not q_pilots:
            print timings[timing]

        elif q_pilots == len(pilots):
            print timings[timing]

    else:

        ts = ["%s:%s" % (k, v) for k, v in timings.iteritems()]
        out = ",".join(str(e) for e in ts)
        out += ";p%s" % len(pilots)

        if not q_pilots:
            print out

        elif q_pilots == len(pilots):
            print out


text:
/**
 * Checks whether the order request has a matching
 * menu and password.
 */

module.exports = function(req, res, next) {

    var password = req.param('password');
    var orderId = req.param('id');
    var menuId = req.param('menu');

    if (menuId) {
        Menu
        .findOne(menuId)
        .exec(function(err, menu) {
            if (!menu) return res.notFound('No menu with this id exists.');
            if (menu.password && menu.password != password) return res.forbidden('The password for this menu was incorrect.');
            next();
        });
    } else if (orderId) {
        Order
        .findOne(orderId)
        .populate('menu')
        .exec(function(err, order) {
            if (!order) return res.notFound('No order with this id exists.');
            if (order.menu.password && order.menu.password != password) return res.forbidden('The password for this menu was incorrect.');
            next();
        });
    } else {
        next();
    }

};

redpajama_set_name: RedPajamaGithub


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

<title>IndexSummaryManagerMBean</title>
<meta name="date" content="2015-05-16">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.apache.cassandra.io.sstable

Interface IndexSummaryManagerMBean

All Known Implementing Classes:

IndexSummaryManager

public interface IndexSummaryManagerMBean

Method Summary

Methods

Modifier and Type
Method and Description

double
getAverageIndexInterval()

java.util.Map<java.lang.String,java.lang.Integer>
getIndexIntervals()

Returns a map of SSTable filenames to their current effective index interval.

long
getMemoryPoolCapacityInMB()

double
getMemoryPoolSizeInMB()

Returns the current actual off-heap memory usage of the index summaries for all non-compacting sstables.

int
getResizeIntervalInMinutes()

void
redistributeSummaries()

void
setMemoryPoolCapacityInMB(long memoryPoolCapacityInMB)

void
setResizeIntervalInMinutes(int resizeIntervalInMinutes)

Method Detail

getMemoryPoolCapacityInMB

long getMemoryPoolCapacityInMB()

setMemoryPoolCapacityInMB

void setMemoryPoolCapacityInMB(long memoryPoolCapacityInMB)

getMemoryPoolSizeInMB

double getMemoryPoolSizeInMB()

Returns the current actual off-heap memory usage of the index summaries for all non-compacting sstables.

Returns:

The amount of memory used in MB.

getIndexIntervals

java.util.Map<java.lang.String,java.lang.Integer> getIndexIntervals()

Returns a map of SSTable filenames to their current effective index interval.

getAverageIndexInterval

double getAverageIndexInterval()

redistributeSummaries

void redistributeSummaries()
                           throws java.io.IOException

Throws:

java.io.IOException

getResizeIntervalInMinutes

int getResizeIntervalInMinutes()

setResizeIntervalInMinutes

void setResizeIntervalInMinutes(int resizeIntervalInMinutes)

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
Instructions on how to update the [clang-format binaries](clang_format.md) that
come with a checkout of Chromium.

## Prerequisites

You'll need a Windows machine, a Linux machine, and a Mac; all capable of
building clang-format. You'll also need permissions to upload to the appropriate
google storage bucket. Chromium infrastructure team members have this, and
others can be granted the permission based on need. Talk to ncarter or hinoka
about getting access.

## Pick a head svn revision

Consult http://llvm.org/svn/llvm-project/ for the current head revision. This
will be the CLANG_REV you'll use later to check out each platform to a
consistent state.

## Build a release-mode clang-format on each platform

Follow the official instructions here:
http://clang.llvm.org/get_started.html.

Windows step-by-step:

```shell
# [double check you have the tools you need]
where cmake.exe  # You need to install this.

# In chromium/src
tools\win\setenv amd64_x86
set CLANG_REV=56ac9d30d35632969baa39829ebc8465ed5937ef  # You must change this value (see above)
rmdir /S /Q llvm-project
git clone https://github.com/llvm/llvm-project
cd llvm-project
git checkout %CLANG_REV%
mkdir build
cd build
set CC=..\..\third_party\llvm-build\Release+Asserts\bin\clang-cl.exe
set CXX=..\..\third_party\llvm-build\Release+Asserts\bin\clang-cl.exe
set CFLAGS=-m32
set CXXFLAGS=-m32
cmake -G Ninja ..\llvm -DCMAKE_BUILD_TYPE=Release -DLLVM_USE_CRT_RELEASE=MT ^
    -DLLVM_ENABLE_ASSERTIONS=NO -DLLVM_ENABLE_THREADS=NO ^
    -DLLVM_ENABLE_PROJECTS=clang
ninja clang-format
bin\clang-format.exe --version
```

Mac & Linux step-by-step:

```shell
# Check out.
export CLANG_REV=56ac9d30d35632969baa39829ebc8465ed5937ef   # You must change this value (see above)
git clone https://github.com/llvm/llvm-project
cd llvm-project
git checkout $CLANG_REV
mkdir build
cd build

# On Mac, do the following:
MACOSX_DEPLOYMENT_TARGET=10.9 cmake -G Ninja \
    -DCMAKE_BUILD_TYPE=Release \
    -DLLVM_ENABLE_PROJECTS=clang \
    -DLLVM_ENABLE_ASSERTIONS=NO \
    -DLLVM_ENABLE_TERMINFO=OFF \
    -DLLVM_ENABLE_THREADS=NO \
    -DLLVM_ENABLE_ZLIB=OFF \
    '-DCMAKE_OSX_ARCHITECTURES=arm64;x86_64' \
    ../llvm/

# On Linux, do the following:
# Note the relative paths that point to your local Chromium checkout.
# TODO(thakis): Remove DLLVM_ENABLE_Z3_SOLVER in the next roll. At the pinned
# revision, Z3 detection does not work with a sysroot, but at LLVM trunk it's
# already fixed.
cmake -G Ninja \
    -DCMAKE_BUILD_TYPE=Release \
    -DLLVM_ENABLE_PROJECTS=clang \
    -DLLVM_ENABLE_ASSERTIONS=NO \
    -DLLVM_ENABLE_TERMINFO=OFF \
    -DLLVM_ENABLE_THREADS=NO \
    -DLLVM_ENABLE_ZLIB=OFF \
    -DLLVM_ENABLE_Z3_SOLVER=NO \
    -DCMAKE_C_COMPILER=$HOME/src/chrome/src/third_party/llvm-build/Release+Asserts/bin/clang \
    -DCMAKE_CXX_COMPILER=$HOME/src/chrome/src/third_party/llvm-build/Release+Asserts/bin/clang++ \
    -DCMAKE_ASM_COMPILER=$HOME/src/chrome/src/third_party/llvm-build/Release+Asserts/bin/clang \
    -DCMAKE_CXX_STANDARD_LIBRARIES="-static-libgcc -static-libstdc++" \
    -DCMAKE_SYSROOT=$HOME/src/chrome/src/build/linux/debian_sid_amd64-sysroot \
    ../llvm/

# Finally, build the actual clang-format binary with Ninja
ninja clang-format
strip bin/clang-format

```

Platform specific notes:

*   Windows: Visual Studio 2013 only.
*   Linux: so far (as of January 2014) we've just included a 64-bit binary. It's
    important to disable threading, else clang-format will depend on
    libatomic.so.1 which doesn't exist on Precise.
*   Mac: Remember to set `MACOSX_DEPLOYMENT_TARGET` when building! If you get
    configure warnings, you may need to install XCode 5 and avoid a goma
    environment.

## Upload each binary to google storage

Copy the binaries into your chromium checkout (under
`src/buildtools/(win|linux64|mac)/clang-format(.exe?)`). For each binary, you'll
need to run `upload_to_google_storage.py` according to the instructions in
[README.txt](https://chromium.googlesource.com/chromium/src/+/main/buildtools/clang_format/README.txt).
This will upload the binary into a publicly accessible google storage bucket,
and update `.sha1` file in your Chrome checkout. You'll check in the `.sha1`
file (but NOT the clang-format binary) into source control. In order to be able
to upload, you'll need write permission to the bucket -- see the prerequisites.

## Copy the helper scripts and update README.chromium

There are some auxiliary scripts that ought to be kept updated in lockstep with
the clang-format binary. These get copied into
`buildtools/clang_format/script` in your Chromium checkout.

The `README.chromium` file ought to be updated with version and date info.

## Upload a CL according to the following template

    Update clang-format binaries and scripts for all platforms.

    I followed these instructions:
    https://chromium.googlesource.com/chromium/src/+/main/docs/updating_clang_format_binaries.md

    The binaries were built at clang revision ####### on ####DATETIME####.

    Bug:

The change should **always** include new `.sha1` files for each platform (we
want to keep these in lockstep), should **never** include `clang-format`
binaries directly. The change should **always** update `README.chromium`

clang-format binaries should weigh in at 1.5MB or less. Watch out for size
regressions.


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="br.com.kosawalabs.apprecommendation">

    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity
            android:name=".presentation.list.AppListActivity"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".presentation.detail.AppDetailActivity"
            android:label="@string/title_app_detail"
            android:parentActivityName=".presentation.list.AppListActivity"
            android:theme="@style/AppTheme.NoActionBar">
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value="br.com.kosawalabs.apprecommendation.presentation.list.AppListActivity" />
        </activity>
        <activity
            android:name=".presentation.login.LoginActivity"
            android:label="@string/title_activity_login"
            android:parentActivityName=".presentation.list.AppListActivity"
            android:theme="@style/AppTheme.NoActionBar">
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value="br.com.kosawalabs.apprecommendation.presentation.list.AppListActivity" />
        </activity>

        <service
            android:name=".service.UploadMyAppsIService"
            android:exported="false" />
    </application>

</manifest>


text:
'use strict';

function log(message, line) {
  console.warn(`${message},${line}`);
}

/**
 * Logger method that takes in YUIDoc warnings array and checks those warnings
 * against special features that we support. This allows us to use special tags
 * for Ember apps, and still support logging for incorrect tags, but suppress
 * warnings for unknown tags we have added
 * @class logger
 * @constructor
 * @param {Object} options Contains logger options and data to handle
 * @param {Array} options.warnings      YUIDoc generated warnings array of type: `{ message, line }`
 * @param {Array} options.whiteListTags Tags whitelisted for support in Ember Fountainhead
 */
module.exports = function logger(options) {
  let warnings = options.warnings || [];
  let whiteListTags = options.whiteListTags || [];

  warnings.forEach(warning => {

    // Check if warning is for an unkown tag, and if it is, check if the tag is
    // white listed
    if (warning.message.includes('unknown tag')) {
      let tag = /unknown tag: (.*)/.exec(warning.message);

      // If a tag wasn't found, we don't know what this is so just log it
      if (!tag.length) {
        return log(warning.message, warning.line);
      }

      // If the tag is white listed, don't log it
      if (whiteListTags.includes(tag[1])) { return; }

      // Unknown tag that isn't whitelisted, log it
      return log(warning.message, warning.line);
    }

    // End of the line, log the message
    log(warning.message, warning.line);
  });
};


text:
package main

import (
	"os"
	"os/exec"
	"testing"
)

func TestCliAddTask(t *testing.T) {
	withCliSetup(t, func() {
		cmd := exec.Command("go", "run", "t.go", "foo")
		err := cmd.Run()
		if err != nil {
			t.Fatal(err)
		}
		listCmd := exec.Command("go", "run", "t.go")
		out, err := listCmd.Output()
		if err != nil {
			t.Fatal(err)
		}
		outString := string(out)
		expected := "0 - foo\n"
		if outString != expected {
			t.Fatalf("Expected output to be '%s', got '%s'", expected, outString)
		}
	})
}

func TestCliFinishTask(t *testing.T) {
	withCliSetup(t, func() {
		cmd := exec.Command("go", "run", "t.go", "foo")
		err := cmd.Run()
		if err != nil {
			t.Fatal(err)
		}
		finishCmd := exec.Command("go", "run", "t.go", "-f", "0")
		err = finishCmd.Run()
		if err != nil {
			t.Fatal(err)
		}
		listCmd := exec.Command("go", "run", "t.go")
		out, err := listCmd.Output()
		if err != nil {
			t.Fatal(err)
		}
		outString := string(out)
		if outString != "" {
			t.Fatalf("Expected output to be '', got '%s'", outString)
		}
	})
}

func TestCliEditTask(t *testing.T) {
	withCliSetup(t, func() {
		cmd := exec.Command("go", "run", "t.go", "foo")
		err := cmd.Run()
		if err != nil {
			t.Fatal(err)
		}
		editCmd := exec.Command("go", "run", "t.go", "-e", "0", "bar")
		err = editCmd.Run()
		if err != nil {
			t.Fatal(err)
		}
		listCmd := exec.Command("go", "run", "t.go")
		out, err := listCmd.Output()
		if err != nil {
			t.Fatal(err)
		}
		outString := string(out)
		expected := "0 - bar\n"
		if outString != expected {
			t.Fatalf("Expected output to be '%s', got '%s'", expected, outString)
		}
	})
}

func withCliSetup(t *testing.T, testFunc func()) {
	origTaskFilePath := os.Getenv("T_TASKS_FILE")
	err := os.Setenv("T_TASKS_FILE", "/tmp/tasks")
	if err != nil {
		t.Fatal(err)
	}
	defer func() {
		os.Remove("/tmp/tasks")
		os.Setenv("T_TASKS_FILE", origTaskFilePath)
	}()
	testFunc()
}

func TestAddTask(t *testing.T) {
	tasklist := TaskList{}
	tasklist.Add("foo")
	if len(tasklist.tasks) != 1 {
		t.Fatalf("Expected list to have one element, got %d", len(tasklist.tasks))
	}

	actualTaskDescription := tasklist.tasks[0].description
	if actualTaskDescription != "foo" {
		t.Fatalf("expected tasklist to contain 'foo', got '%v'", actualTaskDescription)
	}
}

func TestListTasks(t *testing.T) {
	tasklist := TaskList{}
	tasks := tasklist.List()

	if len(tasks) != 0 {
		t.Fatalf("Expected tasklist to contain no element, got %d", len(tasks))
	}

	tasklist.Add("Foo")
	tasks = tasklist.List()

	if len(tasks) != 1 {
		t.Fatalf("Expected tasklist to have one element, got %d", len(tasks))
	}
}

func TestFinishTask(t *testing.T) {
	tasklist := TaskList{}
	tasklist.Add("foo")

	if len(tasklist.tasks) != 1 {
		t.Fatalf("Expected tasklist to contain one element, got %d", len(tasklist.tasks))
	}

	tasklist.Finish(0)

	if len(tasklist.tasks) != 0 {
		t.Fatalf("Expected tasklist to contain no element, got %d", len(tasklist.tasks))
	}
}

func TestEditTask(t *testing.T) {
	tasklist := TaskList{}
	tasklist.Add("foo")

	if len(tasklist.tasks) != 1 {
		t.Fatalf("Expected tasklist to contain one element, got %d", len(tasklist.tasks))
	}
	actualTaskDescription := tasklist.tasks[0].description
	if actualTaskDescription != "foo" {
		t.Fatalf("expected tasklist to contain 'foo', got '%v'", actualTaskDescription)
	}

	tasklist.Edit(0, "bar")

	actualTaskDescription = tasklist.tasks[0].description
	if actualTaskDescription != "bar" {
		t.Fatalf("expected tasklist to contain 'bar', got '%v'", actualTaskDescription)
	}
}


text:
  <md-progress-linear md-mode="indeterminate"></md-progress-linear>
  {{vm.loadingMessage}}

    <md-list flex layout-fill class="list-item-table">
      <md-list-item dir-paginate="sla in vm.serviceLevelAgreements |orderBy:vm.paginationData.sort |filter:vm.filter|itemsPerPage:vm.paginationData.rowsPerPage"
                    pagination-id="vm.paginationId" ng-click="vm.onEditSla(sla)" current-page="vm.currentPage">

            {{sla.name}}
            {{sla.description}}

            {{sla.feedNames}}
            Related Feeds

        <md-divider ng-if="!$last"></md-divider>
      </md-list-item>
      <md-list-item ng-show="vm.loading == false && vm.serviceLevelAgreements.length ==0">
        No Service Level Agreements
      </md-list-item>
      <md-divider></md-divider>

      <md-list-item layout-align="end center" layout-row class="pagination-list-item" ng-show="vm.serviceLevelAgreements.length > 0">
        <dir-pagination-controls pagination-id="vm.paginationId"
                                 auto-hide="false"
                                 max-size="5"
                                 direction-links="true"
                                 boundary-links="false"
                                 template-url="js/common/dir-pagination/dirPagination.tpl.html"
                                 on-page-change="vm.onPaginationChange(newPageNumber)"
                                 label="Rows per page"
                                 rows-per-page="vm.paginationData.rowsPerPage"
                                 rows-per-page-options="vm.paginationData.rowsPerPageOptions"
                                 class="pagination-row">
        </dir-pagination-controls>
      </md-list-item>
    </md-list>

    <md-table-container ng-show="vm.serviceLevelAgreements.length >0">

          Name
          Description
          Related Feeds

            {{sla.name}}

            {{sla.description}}

            {{sla.feedNames}}

    </md-table-container>

    <md-table-pagination md-limit="vm.paginationData.rowsPerPage" md-page="vm.currentPage" md-total="{{vm.serviceLevelAgreements.length}}" md-on-paginate="vm.onPaginationChange"
                         md-limit-options="[5,10,20,50,'ALL']"></md-table-pagination>

  <ng-include src="'js/feed-mgr/sla/service-level-agreement-form.html'"></ng-include>


text:
#pragma once
#include <aws/directconnect/DirectConnect_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>

namespace Aws
{
namespace DirectConnect
{
namespace Model
{
  enum class LoaContentType
  {
    NOT_SET,
    application_pdf
  };

namespace LoaContentTypeMapper
{
AWS_DIRECTCONNECT_API LoaContentType GetLoaContentTypeForName(const Aws::String& name);

AWS_DIRECTCONNECT_API Aws::String GetNameForLoaContentType(LoaContentType value);
} // namespace LoaContentTypeMapper
} // namespace Model
} // namespace DirectConnect
} // namespace Aws


text:
package com.bitdubai.fermat_wpd_plugin.layer.middleware.wallet_settings.developer.bitdubai.version_1.exceptions;

import com.bitdubai.fermat_api.FermatException;

/**
 * Created by natalia on 21/07/15.
 */
public class CantLoadSettingsFileException extends FermatException {

    public static final String DEFAULT_MESSAGE = "ERROR READ REQUESTED SETTINGS XML: ";

    public CantLoadSettingsFileException(String message, Exception cause, String context, String possibleReason) {
        super(message, cause, context, possibleReason);
    }
}


text:
'use strict';

/**
 * Module dependencies
 */
var imagesPolicy = require('../policies/images.server.policy'),
  images = require('../controllers/images.server.controller');

module.exports = function(app) {
  // Images Routes
  app.route('/api/images').all(imagesPolicy.isAllowed)
    .get(images.list)
    .post(images.create);

  app.route('/api/images/:imageId').all(imagesPolicy.isAllowed)
    .get(images.read)
    .put(images.update)
    .delete(images.delete);

  // Finish by binding the Image middleware
  app.param('imageId', images.imageByID);
};


text:
  # if true return array
#Else we need to pad the array with either nil or our specified value
  # number times
    # pad with value
    # this will be when we indicate destructiveness
  # return the array

# 1. Initial Solution
def pad!(array, min_size, value = nil) #destructive
  if array.count >= min_size
    return array
  else
    (min_size - array.count).times do
      array << value
    end
    return array
  end
end

def pad(array, min_size, value = nil) #non-destructive
  new_array = Array.new(array)
  if array.count >= min_size
    return new_array
  else
    (min_size - array.count).times do
      new_array << value
    end
  return new_array
  end
end

# 3. Refactored Solution
def pad!(array, min_size, value = nil) #destructive
    (min_size - array.count).times do
      array << value
    end
    return array
end

def pad(array, min_size, value = nil) #non-destructive
  new_array = Array.new(array)
    (min_size - array.count).times do
      new_array << value
    end
  return new_array
end

# 4. Reflection
#Were you successful in breaking the problem down into small steps?
# I think we were.  We identified what we needed to occur and what steps were involved.

#Once you had written your pseudocode, were you able to easily translate it into code? What difficulties and successes did you have?
# The pseudocode led pretty easily to what we wanted.  It gave us a good guideline for our steps

#Was your initial solution successful at passing the tests? If so, why do you think that is? If not, what were the errors you encountered and what did you do to resolve them?
# We had an error with our non-destructive code.  We did not create a new variable for our array which led to this issue.

#When you refactored, did you find any existing methods in Ruby to clean up your code?
# Not sure if this was meant to be, but because you cannot do something negative times, we were able to completely
# remove our if and else statements

#How readable is your solution? Did you and your pair choose descriptive variable names?
# I think our solution is pretty simple and readable.  We only added one new variable and its clearly labelled.

#What is the difference between destructive and non-destructive methods in your own words?
# In a destructive method, you are changing or altering the original element in some way, while non-destructive methods keep the original element the same and either create or alter another element


text:
package main

// this file exists simply for this comment so that binaries that reference this package will end up running
// the below generation at build time
//go:generate go run -tags=integration assets_generate.go


text:
package org.motechproject.testing.utils;

import org.joda.time.DateTime;
import org.joda.time.LocalDate;
import org.joda.time.LocalTime;
import org.junit.After;
import org.motechproject.commons.date.util.DateTimeSourceUtil;
import org.motechproject.commons.date.util.datetime.DateTimeSource;
import org.motechproject.commons.date.util.datetime.DefaultDateTimeSource;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class BaseUnitTest {
    static final DateTimeSource DATE_TIME_SOURCE = new DefaultDateTimeSource();

    protected void mockCurrentDate(DateTime currentDateTime) {
        DateTimeSourceUtil.setSourceInstance(new MockDateTimeSource(currentDateTime));
    }

    protected void mockCurrentDate(LocalDate currentDate) {
        DateTimeSourceUtil.setSourceInstance(new MockDateTimeSource(currentDate));
    }

    protected DateTime date(int year, int monthOfYear, int dayOfMonth) {
        return new DateTime(year, monthOfYear, dayOfMonth, 0, 0);
    }

    protected Date date(String date) {
        try {
            return new SimpleDateFormat("dd-MM-yyyy hh:mm:ss").parse(date);
        } catch (ParseException e) {
            throw new IllegalArgumentException(e);
        }
    }

    protected DateTime dateTime(int year, int monthOfYear, int dayOfMonth, LocalTime localTime) {
        return new DateTime(year, monthOfYear, dayOfMonth, localTime.getHourOfDay(), localTime.getMinuteOfHour());
    }

    protected DateTime dateTime(LocalDate localDate, LocalTime localTime) {
        return new DateTime(localDate.getYear(), localDate.getMonthOfYear(), localDate.getDayOfMonth(), localTime.getHourOfDay(), localTime.getMinuteOfHour());
    }

    protected void resetDateTimeSource() {
        DateTimeSourceUtil.setSourceInstance(DATE_TIME_SOURCE);
    }

    @After
    public void tearDown() {
        resetDateTimeSource();
    }

}


text:
package net.tortuga.gui.screens;

import net.tortuga.gui.panels.PanelSplash;
import net.tortuga.sounds.Loops;
import net.tortuga.textures.Textures;
import net.tortuga.util.RenderUtils;

import com.porcupine.color.RGB;
import com.porcupine.coord.Rect;

/**
 * Splash screen
 *
 * @author Ondřej Hruška (MightyPork)
 */
public class ScreenSplash extends Screen {

	@Override
	public void initScreen()
	{
		Loops.playIntro();

		setRootPanel(new PanelSplash(this));
	}

	@Override
	public void render2D(double delta)
	{
		Rect quad = new Rect(0, 0, app.getSize().x, app.getSize().y);
		Rect quad2 = new Rect(0, 0, app.getSize().x, app.getSize().y);

		RenderUtils.quadTextured(quad, quad2, Textures.steel_small_dk, new RGB(0x999999));
	}

	@Override
	public boolean isWeatherEnabled()
	{
		return false;
	}

}


text:
function(str)
{
	return encodeURIComponent(str);
}


text:
package cz.muni.fi.xtovarn.heimdall.commons;

public interface Startable {
	void start();
	void stop();
}


text:
class Room {
  constructor(x, y, width, height, doorX = null, doorY = null) {
    this.x = x;
    this.y = y;
    this.width = width;
    this.height = height;
    this.door = {
      x: doorX,
      y: doorY
    };
    this.minSize = 6;
    this.leftChild = null;
    this.rightChild = null;
  }

  split() {
    if (this.leftChild === null && this.rightChild === null) {
      if ((this.width > (this.minSize * 2)) && (this.height > (this.minSize * 2))) {
        let leftX = this.x;
        let leftY = this.y;
        let rightX;
        let rightY;
        let doorX;
        let doorY;
        let leftWidth;
        let leftHeight;
        let rightWidth;
        let rightHeight;
        let splitSize;
        let doorPosition = Math.floor(Math.random() * 10) % 2;

        // The split should always be bigger than the minSize.
        // The split should be between 1/4 and 3/4 of the original size.
        if (this.width > this.height) {
          splitSize = Math.floor((this.width / 4) + (Math.random() * this.width / 2));
          splitSize = (splitSize < this.minSize) ? this.minSize : splitSize;

          rightX = this.x + splitSize;
          rightY = this.y;

          doorX = rightX;
          doorY = rightY + Math.floor(this.minSize / 2) + (doorPosition * (this.height - this.minSize));

          leftWidth = splitSize;
          leftHeight = this.height;

          rightWidth = this.width - splitSize;
          rightHeight = this.height;
        } else {
          splitSize = Math.floor((this.height / 4) + (Math.random() * this.height / 2));
          splitSize = (splitSize < this.minSize) ? this.minSize : splitSize;

          rightX = this.x;
          rightY = this.y + splitSize;

          doorX = rightX + Math.floor(this.minSize / 2) + (doorPosition * (this.width - this.minSize));
          doorY = rightY;

          leftWidth = this.width;
          leftHeight = splitSize;

          rightWidth = this.width;
          rightHeight = this.height - splitSize;
        }

        // create the rooms
        this.leftChild = new Room(leftX, leftY, leftWidth, leftHeight, doorX, doorY);
        this.rightChild = new Room(rightX, rightY, rightWidth, rightHeight, doorX, doorY);

        this.leftChild.split();
        this.rightChild.split();
      }
    }
  }

  traverse() {
    let nodeArray = new Array();
    nodeArray.push(this);
    if (this.leftChild !== null) {
      nodeArray = nodeArray.concat(this.leftChild.traverse());
    }
    if (this.rightChild !== null) {
      nodeArray = nodeArray.concat(this.rightChild.traverse());
    }
    return nodeArray;
  }

  // Mostly for visual dubugging;
  svg() {
    let dungeonRooms = this.traverse();

    dungeonRooms = dungeonRooms.map(room => `<rect x="${room.x}" y="${room.y}" width="${room.width}" height="${room.height}" stroke="black" stroke-width="2" fill="none"/>`);

    dungeonRooms.unshift('<rect x="-10" y="-10" width="100" height="100" stroke="blue" stroke-width="2" fill="none"/>');
    dungeonRooms.unshift('<svg width="250" height="250" viewBox="-10 -10 100 100" xmlns="http://www.w3.org/2000/svg">');
    dungeonRooms.push('<rect x="0" y="0" width="51" height="51" stroke="blue" stroke-width="2" fill="none"/>');
    dungeonRooms.push('</svg>');

    return dungeonRooms.join('\n');
  }
}

// Debug/testing code
/*
let dungeonRoom = new Room(0, 0, 50, 50);
dungeonRoom.split();
let svg = dungeonRoom.svg();
console.log(svg);
*/

module.exports = Room;


text:
          EDIT_INDICATORS

            Widget title
            <input id="indicatorTitle" name="textinput" type="text" ng-model="data.title" placeholder="placeholder" class="input-xlarge editor-text-input">

{{indic.title}}

                        Title
                        <input id="indicatorTitle" name="textinput" type="text" ng-model="indic.sensorSet.propertyType.title" placeholder="placeholder" class="input-xlarge editor-text-input">

                        Visual
                        <select id="selectIndicatorVisual" ng-model="indic.visual" class="form-control tt-input editor-text-input" style="display:inline-block"
                        ng-options="types.id as types.title for (key, types) in vm.indicatorVisuals">

                        </select>

                    Fill color
                    <spectrum-colorpicker format="'hex'" on-change="vm.colorUpdated(color, indic)" data-ng-model="indic.color" options="{ cancelText: 'Annuleren', chooseText: 'Kiezen'}"></spectrum-colorpicker>

                        Feature
                        <select id="selectIndicatorFeature" ng-model="indic.featureTypeName" class="form-control tt-input editor-text-input" style="display:inline-block"
                                ng-options="ft as ft for (ft, type) in vm.$layerService.featureTypes">

                        </select>

                        Property
                        <select id="selectIndicatorProperty" ng-model="vm.propertyTypes" class="form-control tt-input editor-text-input" style="display:inline-block"
                                ng-options="pt as pt.title for pt in vm.$layerService.featureTypes[indic.featureTypeName].propertyTypeData" ng-change="vm.updateIndicator(indic)" multiple>

                        </select>


text:
/**
 * The inital size of BitSet.
 * @readonly
 * @static
 */
var INITAL_SIZE = 2;
/**
 * The bit size of a single word, which is uint32.
 * @readonly
 * @static
 */
var BITS_PER_WORD = 32;
/**
 * The bit size of a byte, which is 8 bits.
 * @readonly
 * @static
 */
var BITS_PER_BYTE = 8;

/**
 * Implements an array of bits that grows by itself. Each bit is a boolean,
 * and its index is non-negative integer.
 * Basically it's Javascript implementation of Java's BitSet.
 * @constructor
 * @param [value] - Initial value for the BitSet.
 */
function BitSet(value) {
  if(value instanceof BitSet) {
    this._words = new Uint32Array(value._words);
  } else if(value != null) {
    this._words = new Uint32Array(value);
  } else {
    this._words = new Uint32Array(INITAL_SIZE);
  }
}

/**
 * Reallocates BitSet to expand to the requested bit size.
 * @private
 * @param bitSize {Number} - the requested bit size.
 */
BitSet.prototype._reallocate = function(bitSize) {
  while(this._words.length < ((bitSize / BITS_PER_WORD)|0)) {
    var newWords = new Uint32Array(this._words.length * 2);
    newWords.set(this._words);
    this._words = newWords;
  }
}

/**
 * Returns BitSet's allocated size in bits.
 * @returns {Number} allocated size in bits.
 */
BitSet.prototype.size = function() {
  return this._words.byteLength * BITS_PER_BYTE;
}

/**
 * Sets specified bit to false.
 * @param pos {Number} - The bit position to set to false.
 * @see {@link BitSet#set}
 */
BitSet.prototype.clear = function(pos) {
  this.set(pos, false);
}

/**
 * Sets specified range of bits to false.
 * @param from {Number} - The start bit position.
 * @param to {Number} - The end bit position.
 * @see {@link BitSet#setRange}
 */
BitSet.prototype.clearRange = function(from, to) {
  this.setRange(from, to, false);
}

/**
 * Sets all bits to false.
 * @see {@link BitSet#setAll}
 */
BitSet.prototype.clearAll = function() {
  this.setAll(false);
}

/**
 * Sets specified bit.
 * @param pos {Number} - The bit position to set.
 * @param set {Boolean} - The value to set.
 */
BitSet.prototype.set = function(pos, set) {
  pos |= 0;
  this._reallocate(pos);
  var wordPos = pos / BITS_PER_WORD | 0;
  var shiftPos = (pos % BITS_PER_WORD);
  if(set) {
    this._words[wordPos] |= 1 << shiftPos;
  } else {
    this._words[wordPos] &= ~(1 << shiftPos);
  }
}

/**
 * Sets specified range of bits.
 * @param from {Number} - The start bit position.
 * @param to {Number} - The end bit position.
 * @param set {Boolean} - The value to set.
 */
BitSet.prototype.setRange = function(from, to, set) {
  for(var i = from; i <= to; ++i) {
    this.set(i, set);
  }
}

/**
 * Sets all bits.
 * @param set {Boolean} - The value to set.
 */
BitSet.prototype.setAll = function(set) {
  this.setRange(0, this.size()-1, set);
}

/**
 * Returns the value of specified bit.
 * @param pos {Number} - The bit position.
 * @returns {Boolean} Whether if the bit is set or not.
 */
BitSet.prototype.get = function(pos) {
  pos |= 0;
  this._reallocate(pos);
  var wordPos = pos / BITS_PER_WORD | 0;
  var shiftPos = (pos % BITS_PER_WORD);
  return (this._words[wordPos] & (1 << shiftPos)) > 0;
}

// logic functions

// aka intersection

/**
 * Performs AND logical operation on two BitSet.
 * That means it will be set to 1 if both are 1, 0 otherwise.
 * The result will be applied to this BitSet.
 * @param set {BitSet} - The other BitSet.
 */
BitSet.prototype.and = function(set) {
  if(set == null) {
    this.clearAll();
    return;
  }
  var intersectSize = Math.min(this._words.length, set._words.length)|0;
  var unionSize = Math.max(this._words.length, set._words.length)|0;
  this._reallocate(unionSize * BITS_PER_WORD);
  for(var i = 0; i < unionSize; ++i) {
    if(i > intersectSize) {
      this._words[i] = 0;
    } else {
      this._words[i] &= set._words[i];
    }
  }
}

// aka union

/**
 * Performs OR logical operation on two BitSet.
 * That means it will be set to 1 if one of them is 1, 0 if both are 0.
 * The result will be applied to this BitSet.
 * @param set {BitSet} - The other BitSet.
 */
BitSet.prototype.or = function(set) {
  if(set == null) {
    return;
  }
  var intersectSize = Math.min(this._words.length, set._words.length)|0;
  var unionSize = Math.max(this._words.length, set._words.length)|0;
  this._reallocate(unionSize * BITS_PER_WORD);
  for(var i = 0; i < unionSize; ++i) {
    if(i > intersectSize) {
      if(this._words.length < set._words.length) {
        this._words[i] = set._words[i];
      }
    } else {
      this._words[i] |= set._words[i];
    }
  }
}

// ???

/**
 * Performs XOR logical operation on two BitSet.
 * That means it will be set to 1 if the bits are different, 0 if they're same.
 * The result will be applied to this BitSet.
 * @param set {BitSet} - The other BitSet.
 */
BitSet.prototype.xor = function(set) {
  if(set == null) {
    return;
  }
  var intersectSize = Math.min(this._words.length, set._words.length)|0;
  var unionSize = Math.max(this._words.length, set._words.length)|0;
  this._reallocate(unionSize * BITS_PER_WORD);
  for(var i = 0; i < unionSize; ++i) {
    if(i > intersectSize) {
      if(this._words.length < set._words.length) {
        this._words[i] = set._words[i];
      }
    } else {
      this._words[i] ^= set._words[i];
    }
  }
}

/**
 * Performs NOT logical operation on the BitSet.
 * That means it will be set to 1 if bit is 0, 0 otherwise.
 * The result will be applied to this BitSet.
 */
BitSet.prototype.not = function() {
  for(var i = 0; i < this._words.length; ++i) {
    this._words[i] = ~this._words[i];
  }
}

// compare functions

/**
 * Checkes whether the BitSet is filled with 0.
 * This function will return false if the BitSet has any bit that is set to 1.
 * @returns {Boolean} Whether if the BitSet is empty.
 */
BitSet.prototype.isEmpty = function() {
  for(var i = 0; i < this._words.length; ++i) {
    if(this._words[i]) return false;
  }
  return true;
}

/**
 * Checks if two BitSet has a same bit to set to 1.
 * This function will return true if they have matching part, false otherwise.
 * @param set - The other BitSet.
 * @returns {Boolean} Whether if two BitSet intersects.
 */
BitSet.prototype.intersects = function(set) {
  if(set == null) {
    return false;
  }
  var intersectSize = Math.min(this._words.length, set._words.length)|0;
  for(var i = 0; i < intersectSize; ++i) {
    if(this._words[i] & set._words[i]) return true;
  }
  return false;
}

// this -> set

/**
 * Checks if this BitSet contains all the bits from the other BitSet.
 * This function will return true if , false otherwise.
 * @param set - The other BitSet.
 * @returns {Boolean} Whether if two BitSet intersects.
 */
BitSet.prototype.contains = function(set) {
  if(set == null) {
    return false;
  }
  var intersectSize = Math.min(this._words.length, set._words.length)|0;
  for(var i = 0; i < intersectSize; ++i) {
    if((this._words[i] & set._words[i]) != set._words[i]) return false;
  }
  return true;
}

/**
 * Checks if two BitSet is same.
 * This function will return true if they are same, false otherwise.
 * @param set - The other BitSet.
 * @returns {Boolean} Whether if two BitSet equals.
 */
BitSet.prototype.equals = function(set) {
  if(set == null || !(set instanceof BitSet)) {
    return false;
  }
  var intersectSize = Math.min(this._words.length, set._words.length)|0;
  var unionSize = Math.max(this._words.length, set._words.length)|0;
  for(var i = 0; i < unionSize; ++i) {
    if(i > intersectSize) {
      if(this._words.length < set._words.length) {
        if(set._words[i]) return false;
      } else {
        if(this._words[i]) return false;
      }
    } else {
      if((this._words[i] ^ set._words[i])) return false;
    }
  }
  return true;
}

/**
 * Changes the BitSet to String form.
 * @param {Number} [redix=2] - The redix to use.
 * @returns {String} The stringified BitSet.
 */
BitSet.prototype.toString = function(redix) {
  var map = [];
  for(var i = 0; i < this._words.length; ++i) {
    var value = this._words[i];
    map.push(value.toString(redix || 2));
  }
  return map.reverse().join(' ');
}

if(typeof module !== 'undefined') {
  module.exports = BitSet;
}


text:
typedef struct IDirect3DDevice9 *LPDIRECT3DDEVICE9, *PDIRECT3DDEVICE9;
typedef struct IDirect3DVertexBuffer9 *LPDIRECT3DVERTEXBUFFER9, *PDIRECT3DVERTEXBUFFER9;
typedef struct IDirect3DIndexBuffer9 *LPDIRECT3DINDEXBUFFER9, *PDIRECT3DINDEXBUFFER9;
typedef struct IDirect3DTexture9 *LPDIRECT3DTEXTURE9, *PDIRECT3DTEXTURE9;
typedef struct ID3DXMesh *LPD3DXMESH;
typedef struct HWND__ *HWND;
typedef struct IDirect3D9 IDirect3D9;

namespace d3d9 {
	// custom deleter for unique_ptr
	template<class _Ty>
	struct d3d9_deleter
	{
		void operator()(_Ty *_Ptr) const _NOEXCEPT
		{
			_Ptr->Release();
		}
	};

	template<class _Ty>
	using unique_ptr = std::unique_ptr<_Ty, d3d9_deleter<_Ty>>;
}


text:
module Carto
  class UserDBService

      # Also default schema for new users
      SCHEMA_PUBLIC = 'public'
      SCHEMA_CARTODB = 'cartodb'
      SCHEMA_IMPORTER = 'cdb_importer'
      SCHEMA_CDB_DATASERVICES_API = 'cdb_dataservices_client'

    def initialize(user)
      @user = user
    end

    def rebuild_quota_trigger
      # TODO: Implement/clone from Sequel model
    end

    def build_search_path(user_schema = nil, quote_user_schema = true)
      user_schema ||= @user.database_schema
      UserDBService.build_search_path(user_schema, quote_user_schema)
    end

    # Centralized method to provide the (ordered) search_path
    def self.build_search_path(user_schema, quote_user_schema = true)
      #TODO Add SCHEMA_CDB_GEOCODER when we open the geocoder API to all the people
      quote_char = quote_user_schema ? "\"" : ""
      "#{quote_char}#{user_schema}#{quote_char}, #{SCHEMA_CARTODB}, #{SCHEMA_CDB_DATASERVICES_API}, #{SCHEMA_PUBLIC}"
    end

    def load_cartodb_functions
      #TODO: Implement
    end

  end
end


text:
<project name="jorbis-pitchfork" basedir="." default="all">

	<!--
		run "ant jar" to create the needed jar
		To sign it you'll need a selfsigned certificate, see seperate
		comment about that
	-->
	<property name="source" value="src"/>
	<property name="build" value="build"/>
	<property name="classes" value="${build}/classes"/>
	<property name="jarfile" value="jorbis-pitchfork.jar"/>

	<target name="clean">
	    <delete dir="${build}"/>
	</target>

	<target name="compile">
		<mkdir dir="${classes}"/>
		<javac srcdir="${source}" destdir="${classes}"/>
	</target>

	<target name="jar" depends="compile">

		<jar destfile="jorbis-pitchfork.jar" basedir="${classes}">
			<manifest>
				<attribute name="Main-Class" value="JorbisPlayer"/>
			</manifest>
		</jar>
	</target>

	<!-- To create your own certificate:
		keytool -genkey -alias pitchfork -validity 3650
		keytool -selfcert -alias pitchfork -validity 3650
	-->
	<target name="signjar" depends="jar">
		<signjar storepass="secret" jar="${jarfile}" alias="pitchfork">
		</signjar>
	</target>

	<target name="all" depends="clean,compile,jar,signjar">
	</target>

</project>


text:
var mongodb = require('mongodb');
var fs = require('fs');
var breezeMongo = require('breeze-mongodb');
var metadata;

var host = 'localhost';
var port = 27017;
var dbName = 'zza';
var serverBase = 'Zza.ExpressServer/';
var dbServer = new mongodb.Server(host, port, { auto_reconnect: true});
var db = new mongodb.Db(dbName, dbServer, {
    strict:true,
    w: 1,
    safe: true
});
db.open(function () {/* noop */ });

exports.getMetadata = function(req, res, next) {
    if (!metadata){ getMetadataFromScriptFile();  }
    res.send(metadata);

    function getMetadataFromScriptFile(){
        var filename = serverBase + "public/app/metadata.js";
        if (!fs.existsSync(filename)) {
            next(new Error("Unable to locate metadata file: " + filename));
        }
        var metadataSrc = fs.readFileSync(filename, 'utf8');

        // Depend upon metadata.js in expected form:
        //   begins "var zza=zza||{};zza.metadata=" ...then \n ... then { ... and
        //   ends with "};"
        metadata = metadataSrc.substring(
            metadataSrc.indexOf('\n{')-1, // start with '{' following a newline
            metadataSrc.lastIndexOf('}')+1); // end with last '}'
    }
}

exports.get = function (req, res, next) {

    var slug = req.params.slug;
    var slugLc = slug.toLowerCase(); // we only use lower case for named queries
    if (namedQuery[slugLc]) {
        namedQuery[slugLc](req, res, next);
    } else {
        var err = {statusCode: 404, message: "Unable to locate query for " + slug};
        next(err) ;
        return;
    }
};

exports.getProducts = function(req, res, next) {
    var query = new breezeMongo.MongoQuery(req.query);
    // add your own filters here
    // Case of collection name matters, e.g. "Product", not "product"
    query.execute(db, "Product", processResults(res, next));
}

// if you don't want to use a Mongo query
function executeQuery(db, collectionName, query, fn) {
    var that = this;
    db.collection(collectionName, {strict: true} , function (err, collection) {
        if (err) {
            err = { statusCode: 404, message: "Unable to locate: " + collectionName, error: err };
            fn(err, null);
            return;
        }

        var src = collection.find(query.filter || {}, query.select || {}, query.options || {});
        src.toArray(function (err, results) {
            results == results || [];
            if (query.resultEntityType) {
                results.forEach(function(r) { r.$type = query.resultEntityType} )
            }
            fn(err, results || []);
        });

    });

};

/* Named queries */
var namedQuery = {
    // always all lower case!
    customers: makeVanillaCollectionQuery('Customer'),
    orders: makeVanillaCollectionQuery('Order'),
    orderstatuses: makeVanillaCollectionQuery('OrderStatus'),
    products: makeVanillaCollectionQuery('Product'),
    productoptions: makeVanillaCollectionQuery('ProductOption'),
    productsizes: makeVanillaCollectionQuery('ProductSize'),

    lookups: lookups
};

function makeVanillaCollectionQuery(collectionName) {
    return function(req, res, next) {
        var query = new breezeMongo.MongoQuery(req.query);
        query.execute(db,collectionName, processResults(res, next));
    } ;
}

function lookups(req, res, next) {
    var lookups = {};
    var queryCountDown = 0;
    var done = processResults(res, next);

    getAll('OrderStatus','OrderStatus');
    getAll('Product','Product');
    getAll('ProductOption','ProductOption');
    getAll('ProductSize','ProductSize');

    function getAll(collectionName, entityType) {
        db.collection(collectionName, {strict: true} , function (err, collection) {
            if (err) {
                err = { statusCode: 404, message: "Unable to locate: " + collectionName, error: err };
                done(err, null);
                return;
            }
            queryCountDown += 1;
            src = collection.find().toArray(function (err, results) {
                queryCountDown -= 1;
                if (err) {
                    done(err,null);
                    return;
                }
                //Todo: explain why we add $type
                results.forEach(function(r) {r.$type = entityType});
                lookups[collectionName]=results;

                if (queryCountDown === 0) {
                    done(null, lookups);
                }
            });
        });
    }

};

function processResults(res, next) {

    return function(err, results) {
        if (err) {
            next(err);
        } else {
            // Prevent browser from caching results of API data requests
            // Todo: Is this always the right policy? Never right? Or only for certain resources?
            res.setHeader('Cache-Control', 'no-cache, private, no-store, must-revalidate, max-stale=0, post-check=0, pre-check=0');
            res.setHeader("Content-Type:", "application/json");
            res.send(results);
        }
    }
}

/*** Save Changes ***/

exports.saveChanges = function(req, res, next) {
    var saveHandler = new breezeMongo.MongoSaveHandler(db, req.body, processResults(res, next));
    saveHandler.beforeSaveEntity = beforeSaveEntity;
    saveHandler.beforeSaveEntities = beforeSaveEntities;
    saveHandler.save();
};

function beforeSaveEntity(entity) {
    /* logic here */
    return true;
}

function beforeSaveEntities(callback) {
    /* logic here */
    callback();
}


text:
/**
 * @author Francesco
 */

// this sets the background color of the master UIView (when there are no windows/tab groups on it)
///Titanium.UI.setBackgroundColor('#000');
//Titanium.UI.setBackgroundImage('/images/bgImage.png');

var css = Ti.API.WxsCss;

//Parent window = WcsDescribeCoverage.js
//reference the current window
var win = Titanium.UI.currentWindow;

/*if(OS_IOS){
	var btnBack = Ti.UI.createButton({
		//title: 'back'
		title: L('NavButton_back')
	});
	win.leftNavButton = btnBack;
	btnBack.addEventListener('click', function() {
		win.close();
	});
};*/

//Misaurazione dello schermo
var pWidth = Ti.Platform.displayCaps.platformWidth;
var pHeight = Ti.Platform.displayCaps.platformHeight;

var xmlData = Ti.XML;
xmlData = win.xmlData;

//create the tableView
var tblCoverageEnvelope = Titanium.UI.createTableView({
	/*width : pWidth - 20,
	height : pHeight - 110,
	top : 20,
	left : 10,
	backgroundColor : '#B0C4DE',
	borderRadius : 12,
	borderColor : '#AFEEEE',
	borderWidth : 2,
	minRowHeight : 90,*/
	top : 0,
	backgroundColor : css.bcTvColor,
	bottom : 0,
	separatorColor : css.separatorColor
});

var str = "";

var sectionSpatialEnvelope = Ti.UI.createTableViewSection({
	//headerTitle : 'Spatial Envelope'
	headerTitle : L('WcsCoverageEnvelope_section1_title')
});
//create a table row
var row = Titanium.UI.createTableViewRow({
	height : Ti.UI.SIZE,
	hasChild : false,
	backgroundColor : css.bcTvRowColor,
	className : 'spatialEnvelope-row'
});
//title row
var titleRow = Titanium.UI.createLabel({
	//text : 'SrsName',
	text : L('WcsCoverageEnvelope_row1_title'),
	font : {
		fontSize : css.titleFontSize,
		fontWeight : 'bold'
	},
	color : css.titleColor,
	left : 10,
	top : 5,
	height : css.titleHeight,
	right : "10dp"
});
//description row
var descriptionRow = Titanium.UI.createLabel({
	text : xmlData.documentElement.getElementsByTagName("gml:Envelope").item(0).getAttribute("srsName"),
	font : {
		fontSize : css.descriptionFontSize,
		fontWeight : 'normal'
	},
	color : css.descriptionColor,
	left : 10,
	top : "25dp",
	bottom : 5,
	right : "10dp", //width : row.width - 20,
	height : Ti.UI.SIZE
});
row.add(titleRow);
row.add(descriptionRow);
sectionSpatialEnvelope.add(row);

//create a table row
var row = Titanium.UI.createTableViewRow({
	height : Ti.UI.SIZE,
	hasChild : false,
	backgroundColor : css.bcTvRowColor,
	className : 'spatialEnvelope-row'
});
//title row
var titleRow = Titanium.UI.createLabel({
	//text : 'SrsDimension',
	text : L('WcsCoverageEnvelope_row2_title'),
	font : {
		fontSize : css.titleFontSize,
		fontWeight : 'bold'
	},
	color : css.titleColor,
	left : 10,
	top : 5,
	height : css.titleHeight,
	right : "10dp"
});
//description row
var descriptionRow = Titanium.UI.createLabel({
	text : xmlData.documentElement.getElementsByTagName("gml:Envelope").item(0).getAttribute("srsDimension"),
	font : {
		fontSize : css.descriptionFontSize,
		fontWeight : 'normal'
	},
	color : css.descriptionColor,
	left : 10,
	top : "25dp",
	bottom : 5,
	right : "10dp", //width : row.width - 20,
	height : Ti.UI.SIZE
});
row.add(titleRow);
row.add(descriptionRow);
sectionSpatialEnvelope.add(row);

//create a table row
var row = Titanium.UI.createTableViewRow({
	height : Ti.UI.SIZE,
	hasChild : false,
	backgroundColor : css.bcTvRowColor,
	className : 'spatialEnvelope-row'
});
//title row
var titleRow = Titanium.UI.createLabel({
	//text : 'Axis labels',
	text : L('WcsCoverageEnvelope_row3_title'),
	font : {
		fontSize : css.titleFontSize,
		fontWeight : 'bold'
	},
	color : css.titleColor,
	left : 10,
	top : 5,
	height : css.titleHeight,
	right : "10dp"
});
str = xmlData.documentElement.getElementsByTagName("gml:Envelope").item(0).getAttribute("axisLabels");
str = str.replace(/ /g, "\n");
//description row
var descriptionRow = Titanium.UI.createLabel({
	text : str,
	font : {
		fontSize : css.descriptionFontSize,
		fontWeight : 'normal'
	},
	color : css.descriptionColor,
	left : 10,
	top : "25dp",
	bottom : 5,
	right : "10dp", //width : row.width - 20,
	height : Ti.UI.SIZE
});
row.add(titleRow);
row.add(descriptionRow);
sectionSpatialEnvelope.add(row);

//create a table row
var row = Titanium.UI.createTableViewRow({
	height : Ti.UI.SIZE,
	hasChild : false,
	backgroundColor : css.bcTvRowColor,
	className : 'spatialEnvelope-row'
});
//title row
var titleRow = Titanium.UI.createLabel({
	//text : 'Axis UOMs',
	text : L('WcsCoverageEnvelope_row4_title'),
	font : {
		fontSize : css.titleFontSize,
		fontWeight : 'bold'
	},
	color : css.titleColor,
	left : 10,
	top : 5,
	height : css.titleHeight,
	right : "10dp"
});
str = xmlData.documentElement.getElementsByTagName("gml:Envelope").item(0).getAttribute("uomLabels");
str = str.replace(/ /g, "\n");
//description row
var descriptionRow = Titanium.UI.createLabel({
	text : str,
	font : {
		fontSize : css.descriptionFontSize,
		fontWeight : 'normal'
	},
	color : css.descriptionColor,
	left : 10,
	top : "25dp",
	bottom : 5,
	right : "10dp", //width : row.width - 20,
	height : Ti.UI.SIZE
});
row.add(titleRow);
row.add(descriptionRow);
sectionSpatialEnvelope.add(row);

//create a table row
var row = Titanium.UI.createTableViewRow({
	height : Ti.UI.SIZE,
	hasChild : false,
	backgroundColor : css.bcTvRowColor,
	className : 'spatialEnvelope-row'
});
//title row
var titleRow = Titanium.UI.createLabel({
	//text : 'Lower corner',
	text : L('WcsCoverageEnvelope_row5_title'),
	font : {
		fontSize : css.titleFontSize,
		fontWeight : 'bold'
	},
	color : css.titleColor,
	left : 10,
	top : 5,
	height : css.titleHeight,
	right : "10dp"
});
str = xmlData.documentElement.getElementsByTagName("gml:Envelope").item(0).getElementsByTagName("gml:lowerCorner").item(0).textContent;
var numbersArray = [];
numbersArray = str.split(" ");
str = "";
for (var i = 0; i < numbersArray.length; i++) {
	str += parseFloat(numbersArray[i]).toFixed(6) + "\n";
};
str = str.substr(0, str.length - 1);
//str = str.replace(" ","\n");
//description row
var descriptionRow = Titanium.UI.createLabel({
	text : str,
	font : {
		fontSize : css.descriptionFontSize,
		fontWeight : 'normal'
	},
	color : css.descriptionColor,
	left : 10,
	top : "25dp",
	bottom : 5,
	right : "10dp", //width : row.width - 20,
	height : Ti.UI.SIZE
});
row.add(titleRow);
row.add(descriptionRow);
sectionSpatialEnvelope.add(row);

//create a table row
var row = Titanium.UI.createTableViewRow({
	height : Ti.UI.SIZE,
	hasChild : false,
	backgroundColor : css.bcTvRowColor,
	className : 'spatialEnvelope-row'
});
//title row
var titleRow = Titanium.UI.createLabel({
	//text : 'Upper corner',
	text : L('WcsCoverageEnvelope_row6_title'),
	font : {
		fontSize : css.titleFontSize,
		fontWeight : 'bold'
	},
	color : css.titleColor,
	left : 10,
	top : 5,
	height : css.titleHeight,
	right : "10dp"
});
str = xmlData.documentElement.getElementsByTagName("gml:Envelope").item(0).getElementsByTagName("gml:upperCorner").item(0).textContent;
//str = str.replace(" ", "\n");
var numbersArray = [];
numbersArray = str.split(" ");
str = "";
for (var i = 0; i < numbersArray.length; i++) {
	str += parseFloat(numbersArray[i]).toFixed(6) + "\n";
};
str = str.substr(0, str.length - 1);

//description row
var descriptionRow = Titanium.UI.createLabel({
	text : str,
	font : {
		fontSize : css.descriptionFontSize,
		fontWeight : 'normal'
	},
	color : css.descriptionColor,
	left : 10,
	top : "25dp",
	bottom : 5,
	right : "10dp", //width : row.width - 20,
	height : Ti.UI.SIZE
});
row.add(titleRow);
row.add(descriptionRow);
sectionSpatialEnvelope.add(row);

//finally, set the data property of the tableView to our sections
tblCoverageEnvelope.data = [sectionSpatialEnvelope];

win.add(tblCoverageEnvelope);

//Questo evento serve a rimuovere la tabella, che altrimenti rimarrebbe come sfondo, creando righe sovrapposte
win.addEventListener('blur', removeTable);
function removeTable(e) {
	win.remove(tblCoverageEnvelope);
};


text:
@interface GastronomyListViewController : UITableViewController

@property (weak, nonatomic) IBOutlet UIBarButtonItem *sidebarButton;

@end


text:
extern "C"{
	namespace accutl{
		//:::::::::::::: Type defines ::::::::::::::::::::://

		///Region of interest
		using ROI = struct{
			int tlx; //Top-left x-coordinate
			int tly; //Top-left y-coordinate
			int w; //roi width
			int h; //roi height
		};

		using HIST = std::vector<int>; ///Histogram as a vector of int

		using Mode = enum { MODE_NEAREST, MODE_BILINEAR, MODE_BICUBIC, MODE_FAST_BICUBIC, MODE_CATROM }; ///Resize modes

		//:::::::::::::: Memory Functions ::::::::::::::::::://

		///Wrapper for cudaMalloc()
		int GPUMemAlloc(void** device_ptr, size_t size_byte);

		///Wrapper for cudaFree()
		int GPUMemFree(void* device_ptr);

		///Wrapper for cudaMemcpy(), device-to-device
		int GPUMemcpy_DD(void* d_dst, void* d_src, size_t size_byte);

		///Wrapper for cudaMemcpy(), device-to-host
		int GPUMemcpy_DH(void* h_dst, void* d_src, size_t size_byte);

		///Wrapper for cudaMemcpy(), host-to-device
		int GPUMemcpy_HD(void* d_dst, void* h_src, size_t size_byte);

		///Wrapper for cudaDeviceReset()
		int GPUEndSession();

		//:::::::::::::: Type Conversion ::::::::::::::::::://

		int F32Packed_Planar(float* d_packed, float* d_Y, float* d_U, float* d_V, const int width_px, const int height_px);

		int F32Planar_Packed(float* d_packed, float* d_Y, float* d_U, float* d_V, const int width_px, const int height_px);

		int YC48H_F32DPlanar(float* d_dstY, float* d_dstU, float* d_dstV, PIXEL_YC* h_src, const int width_px, const int height_px, const int src_stride_px);

		int YC48H_F32DPacked(float* d_dst, PIXEL_YC* h_src, const int width_px, const int height_px, const int src_stride_px);

		int F32D_YC48H(PIXEL_YC* h_dst, const int dst_stride_px, float* d_srcY, float* d_srcU, float* d_srcV, const int width_px, const int height_px);

		//:::::::::::::: Statistical Functions ::::::::::::::://
		int Sum_F32(float* d_src, const int width_px, const int height_px, float* result);
		int Sum_F32ROI(float* d_src, const int width_px, const int height_px, const accutl::ROI &roi, float* result);

		int Min_F32(float* d_src, const int width_px, const int height_px, float* result);
		int Min_F32ROI(float* d_src, const int width_px, const int height_px, const accutl::ROI &roi, float* result);

		int Max_F32(float* d_src, const int width_px, const int height_px, float* result);
		int Max_F32ROI(float* d_src, const int width_px, const int height_px, const accutl::ROI &roi, float* result);

		int Histogram_F32C1(float* d_src, const int width_px, const int height_px, const float low_limit, const float high_limit, const int bin_count, accutl::HIST &result);
		int Histogram_F32C3(float* d_src, const int width_px, const int height_px,
			float low_limit[3], float high_limit[3], int bin_count[3],
			accutl::HIST &channel0, accutl::HIST &channel1, accutl::HIST &channel2);

		//::::::::::::::: Transformation Functions :::::::::::::::://
		int Transpose_F32(float* d_src, const int src_w, const int src_h, float* d_dst);

		int Saxpy_F32(float* d_src, const int pixel_count, const float offset, const float multiplier, float* d_dst);
		int Saxpy_F32i(float* d_src, const int pixel_count, const float offset, const float multiplier);

		int ColorTwist_F32C3(float* d_src, const int pixel_count, float matrix[9], float* d_dst);
		int ColorTwist_F32C3i(float* d_src, const int pixel_count, float matrix[9], float* d_dst);

		int Resize_F32(float *d_src, float *output, int width, int height, float scale, accutl::Mode filter_mode, float data_range);

		//AUEXTC __declspec(dllexport) int Convolute_F32(float* d_src, const int src_w, const int src_h, std::vector<float> &matrix, float* d_dst);
	}
}


text:
package com.cdc.androidsamples.base;

/**
 * @author zhenghanrong on 2017/11/11.
 */

public class Constants
{
    public static int num;

}


text:
#import <Foundation/Foundation.h>

/**
 * Marks the start of an asynchronous unit test.
 */
// NOTE: since the CI uses Xcode 5, we cannot depend on XCTestExpectation.
// Use dispatch_semaphore instead.
//
// #define ASYNC_TEST_START XCTestExpectation *expectation = [self expectationWithDescription:[NSString stringWithUTF8String:__FUNCTION__]];
#define ASYNC_TEST_START dispatch_semaphore_t sen_semaphore = dispatch_semaphore_create(0);

/**
 * Marks the end of an asynchronous unit test.
 */
// #define ASYNC_TEST_END [self waitForExpectationsWithTimeout:10 handler:nil];
#define ASYNC_TEST_END \
    while (dispatch_semaphore_wait(sen_semaphore, DISPATCH_TIME_NOW)) \
        [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:10]];

/**
 * Signals the completion of an asynchronous unit test.
 */
// #define ASYNC_TEST_SIGNAL [expectation fulfill];
#define ASYNC_TEST_SIGNAL dispatch_semaphore_signal(sen_semaphore);

/**
 * Fails an asynchronous unit test, additionally signaling its completion.
 */
// #define ASYNC_TEST_FAILURE_BLOCK \
//     ^(NSError *error) { \
//         XCTFail(@"Test failed: %@", error.description); \
//         [expectation fulfill]; \
//     }
#define ASYNC_TEST_FAILURE_BLOCK \
    ^(NSError *error) { \
        XCTFail(@"Test failed: %@", error.description); \
        ASYNC_TEST_SIGNAL \
    }


text:
/*package com.app.tbd;

import com.app.tbd.AppModule;

public final class Modules {
    public static Object[] list(String apiKey) {
        return new Object[] {
                new AppModule(apiKey),
                //new DebugAppModule()
        };
    }

    private Modules() {
        // No instances.
    }
}*/


text:
#pragma once
#include <aws/kinesis-video-signaling/KinesisVideoSignalingChannels_EXPORTS.h>
#include <aws/kinesis-video-signaling/KinesisVideoSignalingChannelsRequest.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/kinesis-video-signaling/model/Service.h>
#include <utility>

namespace Aws
{
namespace KinesisVideoSignalingChannels
{
namespace Model
{

  /**
   */
  class AWS_KINESISVIDEOSIGNALINGCHANNELS_API GetIceServerConfigRequest : public KinesisVideoSignalingChannelsRequest
  {
  public:
    GetIceServerConfigRequest();

    // Service request name is the Operation name which will send this request out,
    // each operation should has unique request name, so that we can get operation's name from this request.
    // Note: this is not true for response, multiple operations may have the same response name,
    // so we can not get operation's name from response.
    inline virtual const char* GetServiceRequestName() const override { return "GetIceServerConfig"; }

    Aws::String SerializePayload() const override;

    /**
     *
The ARN of the signaling channel to be used for the peer-to-peer connection
     * between configured peers.

     */
    inline const Aws::String& GetChannelARN() const{ return m_channelARN; }

    /**
     *
The ARN of the signaling channel to be used for the peer-to-peer connection
     * between configured peers.

     */
    inline bool ChannelARNHasBeenSet() const { return m_channelARNHasBeenSet; }

    /**
     *
The ARN of the signaling channel to be used for the peer-to-peer connection
     * between configured peers.

     */
    inline void SetChannelARN(const Aws::String& value) { m_channelARNHasBeenSet = true; m_channelARN = value; }

    /**
     *
The ARN of the signaling channel to be used for the peer-to-peer connection
     * between configured peers.

     */
    inline void SetChannelARN(Aws::String&& value) { m_channelARNHasBeenSet = true; m_channelARN = std::move(value); }

    /**
     *
The ARN of the signaling channel to be used for the peer-to-peer connection
     * between configured peers.

     */
    inline void SetChannelARN(const char* value) { m_channelARNHasBeenSet = true; m_channelARN.assign(value); }

    /**
     *
The ARN of the signaling channel to be used for the peer-to-peer connection
     * between configured peers.

     */
    inline GetIceServerConfigRequest& WithChannelARN(const Aws::String& value) { SetChannelARN(value); return *this;}

    /**
     *
The ARN of the signaling channel to be used for the peer-to-peer connection
     * between configured peers.

     */
    inline GetIceServerConfigRequest& WithChannelARN(Aws::String&& value) { SetChannelARN(std::move(value)); return *this;}

    /**
     *
The ARN of the signaling channel to be used for the peer-to-peer connection
     * between configured peers.

     */
    inline GetIceServerConfigRequest& WithChannelARN(const char* value) { SetChannelARN(value); return *this;}

    /**
     *
Unique identifier for the viewer. Must be unique within the signaling
     * channel.

     */
    inline const Aws::String& GetClientId() const{ return m_clientId; }

    /**
     *
Unique identifier for the viewer. Must be unique within the signaling
     * channel.

     */
    inline bool ClientIdHasBeenSet() const { return m_clientIdHasBeenSet; }

    /**
     *
Unique identifier for the viewer. Must be unique within the signaling
     * channel.

     */
    inline void SetClientId(const Aws::String& value) { m_clientIdHasBeenSet = true; m_clientId = value; }

    /**
     *
Unique identifier for the viewer. Must be unique within the signaling
     * channel.

     */
    inline void SetClientId(Aws::String&& value) { m_clientIdHasBeenSet = true; m_clientId = std::move(value); }

    /**
     *
Unique identifier for the viewer. Must be unique within the signaling
     * channel.

     */
    inline void SetClientId(const char* value) { m_clientIdHasBeenSet = true; m_clientId.assign(value); }

    /**
     *
Unique identifier for the viewer. Must be unique within the signaling
     * channel.

     */
    inline GetIceServerConfigRequest& WithClientId(const Aws::String& value) { SetClientId(value); return *this;}

    /**
     *
Unique identifier for the viewer. Must be unique within the signaling
     * channel.

     */
    inline GetIceServerConfigRequest& WithClientId(Aws::String&& value) { SetClientId(std::move(value)); return *this;}

    /**
     *
Unique identifier for the viewer. Must be unique within the signaling
     * channel.

     */
    inline GetIceServerConfigRequest& WithClientId(const char* value) { SetClientId(value); return *this;}

    /**
     *
Specifies the desired service. Currently, TURN is the only valid
     * value.

     */
    inline const Service& GetService() const{ return m_service; }

    /**
     *
Specifies the desired service. Currently, TURN is the only valid
     * value.

     */
    inline bool ServiceHasBeenSet() const { return m_serviceHasBeenSet; }

    /**
     *
Specifies the desired service. Currently, TURN is the only valid
     * value.

     */
    inline void SetService(const Service& value) { m_serviceHasBeenSet = true; m_service = value; }

    /**
     *
Specifies the desired service. Currently, TURN is the only valid
     * value.

     */
    inline void SetService(Service&& value) { m_serviceHasBeenSet = true; m_service = std::move(value); }

    /**
     *
Specifies the desired service. Currently, TURN is the only valid
     * value.

     */
    inline GetIceServerConfigRequest& WithService(const Service& value) { SetService(value); return *this;}

    /**
     *
Specifies the desired service. Currently, TURN is the only valid
     * value.

     */
    inline GetIceServerConfigRequest& WithService(Service&& value) { SetService(std::move(value)); return *this;}

    /**
     *
An optional user ID to be associated with the credentials.

     */
    inline const Aws::String& GetUsername() const{ return m_username; }

    /**
     *
An optional user ID to be associated with the credentials.

     */
    inline bool UsernameHasBeenSet() const { return m_usernameHasBeenSet; }

    /**
     *
An optional user ID to be associated with the credentials.

     */
    inline void SetUsername(const Aws::String& value) { m_usernameHasBeenSet = true; m_username = value; }

    /**
     *
An optional user ID to be associated with the credentials.

     */
    inline void SetUsername(Aws::String&& value) { m_usernameHasBeenSet = true; m_username = std::move(value); }

    /**
     *
An optional user ID to be associated with the credentials.

     */
    inline void SetUsername(const char* value) { m_usernameHasBeenSet = true; m_username.assign(value); }

    /**
     *
An optional user ID to be associated with the credentials.

     */
    inline GetIceServerConfigRequest& WithUsername(const Aws::String& value) { SetUsername(value); return *this;}

    /**
     *
An optional user ID to be associated with the credentials.

     */
    inline GetIceServerConfigRequest& WithUsername(Aws::String&& value) { SetUsername(std::move(value)); return *this;}

    /**
     *
An optional user ID to be associated with the credentials.

     */
    inline GetIceServerConfigRequest& WithUsername(const char* value) { SetUsername(value); return *this;}

  private:

    Aws::String m_channelARN;
    bool m_channelARNHasBeenSet = false;

    Aws::String m_clientId;
    bool m_clientIdHasBeenSet = false;

    Service m_service;
    bool m_serviceHasBeenSet = false;

    Aws::String m_username;
    bool m_usernameHasBeenSet = false;
  };

} // namespace Model
} // namespace KinesisVideoSignalingChannels
} // namespace Aws


text:
/* eslint no-mixed-operators: 0 */
import React, { Component } from 'react'
import PropTypes from 'prop-types'
import { injectIntl, intlShape } from 'react-intl'
import { getKeyByValue } from 'utils'
import P from 'components/P'
import ColorPicker from './ColorPicker'
import ToggleDropDown from './ToggleDropdown'
import messages from './messages'
import styles from './styles'
import BoxOptions from './BoxOptions'

class PeopleAppearanceOptions extends Component {
  static propTypes = {
    skin: PropTypes.string,
    hair: PropTypes.string,
    intl: intlShape.isRequired,
    onSkinChange: PropTypes.func.isRequired,
    onHairChange: PropTypes.func.isRequired,
    onActive: PropTypes.func.isRequired,
    active: PropTypes.bool.isRequired,
    showOptions: PropTypes.bool.isRequired,
    onOptionsShow: PropTypes.func.isRequired
  }

  // bgColor means isInputChecked
  handleActive = (active) => this.props.onActive(active)

  handleOptionsShow = () => this.props.onOptionsShow(!this.props.showOptions)

  handleSkinChange = (color) => {
    const skin = getKeyByValue(this.skin, color.toUpperCase())
    this.props.onSkinChange(skin)
  }

  handleHairChange = (color) => {
    const hair = getKeyByValue(this.hair, color.toUpperCase())
    this.props.onHairChange(hair)
  }

  skin = {
    white: '#F5E5DE',
    black: '#A65C17',
    assian: '#F4ECAD',
    mulatto: '#E3AB72',
    aztec: '#CF9D7C'
  }

  hair = {
    brown: '#A65E26',
    blonde: '#FDD700',
    red: '#ED4120',
    black: '#020100',
    gray: '#EFEFEF',
    darkGray: '#AAABAB',
    darkBrown: '#6A2703'
  }

  render() {
    const { intl, skin, active, showOptions, hair } = this.props
    const { formatMessage } = intl
    const marginBottom = showOptions ? '200px' : 'auto'
    return (

        <ToggleDropDown
          toggled={active}
          onToggle={this.handleActive}
          label={formatMessage(messages.peopleAppearance)}
          style={styles.toggle}
          showOptions={showOptions}
          onClick={this.handleOptionsShow}
        />
        {showOptions ? (
          <BoxOptions>

{formatMessage(messages.skinColor)}

            <ColorPicker
              color={this.skin[skin]}
              colors={Object.values(this.skin)}
              onChooseColor={this.handleSkinChange}
              enableMoreColors={false}
            />

{formatMessage(messages.hairColor)}

            <ColorPicker
              color={this.hair[hair]}
              colors={Object.values(this.hair)}
              onChooseColor={this.handleHairChange}
              enableMoreColors={false}
              width={310}
            />
          </BoxOptions>
        ) : (
          ''
        )}

    )
  }
}

export default injectIntl(PeopleAppearanceOptions)


text:
	  <address style="color:#fff;">
        Millionaire Labs

        151 Charles Street West

        Kitchener, Ontario Canada N2G 1H6
      </address>

      <address style="color:#fff;">
        Email Us

        first.last@example.com
      </address>


text:
package com.swfarm.biz.ebay.web;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

import com.swfarm.biz.ebay.bo.EbayAccount;
import com.swfarm.biz.ebay.bo.EbayReturn;
import com.swfarm.biz.ebay.bo.EbayReturnDetail;
import com.swfarm.biz.ebay.job.SynchronizeEbayReturnsTask;
import com.swfarm.biz.ebay.srv.EbayService;
import com.swfarm.pub.utils.DateUtils;

public class SynchronizeEbayReturnsController extends AbstractController {
	private static final Logger logger = Logger
			.getLogger(SynchronizeEbayReturnsController.class);

	private EbayService ebayService;

	public void setEbayService(EbayService ebayService) {
		this.ebayService = ebayService;
	}

	protected ModelAndView handleRequestInternal(HttpServletRequest req,
			HttpServletResponse res) throws Exception {
		// 收集页面参数
		Map<String, String> dataMap = new HashMap<String, String>();

		SynchronizeEbayReturnsTask task = new SynchronizeEbayReturnsTask();
		// 开始时间和结束时间
		String endDateStr = req.getParameter("endDate");
		dataMap.put("endDate", endDateStr);

		Date endDate = null;
		if (StringUtils.isNotEmpty(endDateStr)) {
			String endHourStr = StringUtils.defaultIfEmpty(
					req.getParameter("endHour"), "00");
			dataMap.put("endHour", endHourStr);

			String endMinuteStr = StringUtils.defaultIfEmpty(
					req.getParameter("endMinute"), "00");
			dataMap.put("endMinute", endMinuteStr);

			String endTimeStr = endDateStr + " " + endHourStr + ":"
					+ endMinuteStr + ":00";
			if (logger.isDebugEnabled()) {
				logger.debug("endTimeStr:" + endTimeStr);
			}
			endDate = DateUtils.stringToDate(endTimeStr, "yyyy/MM/dd HH:mm:SS");
		}

		String startDateStr = req.getParameter("startDate");
		dataMap.put("startDate", startDateStr);

		Date startDate = null;
		if (StringUtils.isNotEmpty(startDateStr)) {
			String startHourStr = StringUtils.defaultIfEmpty(
					req.getParameter("startHour"), "00");
			dataMap.put("startHour", startHourStr);

			String startMinuteStr = StringUtils.defaultIfEmpty(
					req.getParameter("startMinute"), "00");
			dataMap.put("startMinute", startMinuteStr);

			String startTimeStr = startDateStr + " " + startHourStr + ":"
					+ startMinuteStr + ":00";
			if (logger.isDebugEnabled()) {
				logger.debug("startTimeStr:" + startTimeStr);
			}
			startDate = DateUtils.stringToDate(startTimeStr,
					"yyyy/MM/dd HH:mm:SS");
		}

		String[] accountNumbers = req.getParameterValues("accountNumber");
		if (accountNumbers != null && accountNumbers.length > 0) {
			List<String> accounts = new ArrayList<String>();
			for (int i = 0; i < accountNumbers.length; i++) {
				if (StringUtils.isNotEmpty(accountNumbers[i])) {
					accounts.add(accountNumbers[i]);
				}
			}
			if (CollectionUtils.isNotEmpty(accounts)) {
				task.setAccounts(accounts);
			}
		}
		String returnId = req.getParameter("returnId");
		logger.warn("returnId:"+returnId);
		if (StringUtils.isNotEmpty(returnId)) {
			EbayReturn ebayReturn = this.ebayService.findEbayReturn(returnId);
			if (ebayReturn != null) {
				String account = ebayReturn.getSellerLoginName();
				EbayAccount ebayAccount = this.ebayService.findEbayAccountByName(account);
				if (ebayAccount != null) {
					EbayReturnDetail detail = this.ebayService.retrieveEbayReturnDetail(returnId, ebayAccount);
					if (detail != null && detail.getReturnId() != null) {
						Boolean isReplied = false;
						EbayReturnDetail ebayReturnDetail = this.ebayService.
								findEbayReturnDetail(detail.getReturnId());
						if (ebayReturnDetail != null) {
							if (detail.getResponseHistories().size() == ebayReturnDetail
									.getResponseHistories().size()) {
								isReplied = ebayReturnDetail.getIsReplied();
							}
							this.ebayService.deleteEbayReturnDetail(ebayReturnDetail);
						}
						detail.setIsReplied(isReplied);
						this.ebayService.saveEbayReturnDetail(detail);
						ebayReturn.setState(detail.getState());
						ebayReturn.setStatus(detail.getStatus());
						ebayReturn.setIsReplied(detail.getIsReplied());
						this.ebayService.saveEbayReturn(ebayReturn);
					} else {
						this.ebayService.deleteEbayReturn(ebayReturn);
					}
				}
			}
			return new ModelAndView("redirect:/ebay/search_ebayreturns.shtml");
		}
		try {
			task.setEbayService(ebayService);
			task.synchronizeEbayReturns(startDate, endDate);
		} catch (Exception e) {
			logger.warn("异常:" + e.getMessage());
		}
		return new ModelAndView("redirect:/ebay/search_ebayreturns.shtml");
	}
}


text: require "dynamo"


text:
package org.rzo.netty.ahessian.crypto;

public class StreamCipherFactory
{

	public static StreamCipher createCipher(String algorithm)
	{
		if ("RC4".equals(algorithm))
			return new RC4Cipher();
		else if ("Salsa20".equals(algorithm))
			return new Salsa20();
		else
			return null;
	}

}


text:
require_relative 'config/boot'

module Loghouse
  TIME_ZONE = ENV.fetch('TIME_ZONE') { 'Europe/Moscow' }

  class UnauthenticatedError < StandardError; end

  # rubocop:disable Metrics/ClassLength
  class Application < Sinatra::Base
    configure do
      use Rack::MethodOverride
      register Sinatra::RespondWith

      enable :logging
    end

    before do
      Time.zone          = TIME_ZONE
      Chronic.time_class = Time.zone
      User.current       = self.class.development? ? 'admin' : user_from_header
      @tab_queries       = LoghouseQuery.all.first(10)

      if request.path_info.match(/.csv$/)
        request.accept.unshift('text/csv')
        request.path_info = request.path_info.gsub(/.csv$/,'')
      end
    end

    get '/' do
      redirect '/query'
    end

    get '/query', provides: [:html, :csv] do
      @query =  if params[:query_id]
                  @tab = params[:query_id]
                  LoghouseQuery.find!(params[:query_id])
                else
                  query_from_params
                end

      begin
        @query.validate!(name: false)
      rescue LoghouseQuery::BadFormat => e
        @error = "Bad query format: #{e}"
      rescue LoghouseQuery::BadTimeFormat => e
        @error = "Bad time format: #{e}"
      end

      respond_to do |f|
        f.html do
          @query.paginate(newer_than: params[:newer_than], older_than: params[:older_than], per_page: params[:per_page])

          if request.xhr?
            erb :_result, layout: false
          else
            erb :index
          end
        end

        f.csv { @query.csv_result(params[:shown_keys]) }
      end
    end

    # Queries management
    before '/queries*' do
      @tab = :queries
    end

    get '/queries' do
      @queries = LoghouseQuery.all

      erb :'queries/index'
    end

    get '/queries/new' do
      @query = query_from_params
      erb :'queries/new'
    end

    post '/queries' do
      @query = query_from_params

      begin
        @query.save!

        return redirect '/queries'
      rescue LoghouseQuery::BadFormat => e
        @error = "Bad query format: #{e}"
      rescue LoghouseQuery::BadTimeFormat => e
        @error = "Bad time format: #{e}"
      rescue LoghouseQuery::Storable::NotValid => e
        @error = "Validation failed: #{e}"
      end

      erb :'queries/new'
    end

    get '/queries/:query_id/edit' do
      @query = LoghouseQuery.find!(params[:query_id])

      erb :'queries/edit'
    end

    put '/queries/update_order' do
      new_order = JSON.parse(params[:new_order])
      LoghouseQuery.update_order!(new_order)

      content_type :json
      { status: :ok }.to_json
    end

    put '/queries/:query_id' do
      @query = LoghouseQuery.find!(params[:query_id])
      begin
        @query.update!(query_from_params.attributes)

        return redirect '/queries'
      rescue LoghouseQuery::BadFormat => e
        @error = "Bad query format: #{e}"
      rescue LoghouseQuery::BadTimeFormat => e
        @error = "Bad time format: #{e}"
      rescue LoghouseQuery::Storable::NotValid => e
        @error = "Validation failed: #{e}"
      end

      erb :'queries/edit'
    end

    delete '/queries/:query_id' do
      query = LoghouseQuery.find!(params[:query_id])
      query.destroy!

      ''
    end

    delete '/queries' do
      LoghouseQuery.create_table!(true)

      ''
    end

    error UnauthenticatedError do |e|
      @status = 401
      @message = "Not Authenticated"

      render_error
    end

    error User::PermissionsNotFound do |e|
      @status = 403
      @message = e.message

      render_error
    end

    error do |e|
      @status = 500
      @message = 'Internal Server Error'

      render_error
    end

    helpers do
      def h(text)
        Rack::Utils.escape_html(text)
      end

      def follow?
        params[:follow] == 'on'
      end

      def version
        @version ||= ENV.fetch('GIT_REV') { `git rev-parse HEAD` }.to_s[0..7]
      end
    end

    private

    def query_from_params
      LoghouseQuery.new(name: params[:name], query: params[:query].to_s.strip, namespaces: params[:namespaces])
                   .time_params(format: params[:time_format], from: params[:time_from], to: params[:time_to],
                                seek_to: params[:seek_to])

    end

    def user_from_header
      auth_header = env['HTTP_AUTHORIZATION']

      raise UnauthenticatedError if auth_header.blank?

      Base64.decode64(auth_header.gsub(/Basic /, '')).split(':').first
    end

    def render_error
      status @status
      erb :error, layout: false
    end
  end
end