text:
[![npm version](https://badge.fury.io/js/react-keydown.svg)](https://badge.fury.io/js/react-keydown)
[![dependencies](https://david-dm.org/glortho/react-keydown.svg)](https://david-dm.org/glortho/react-keydown.svg)

Use react-keydown as a higher-order component or decorator to pass keydown
events to the wrapped component, or call methods directly via designated keys. Good
for implementing keyboard navigation or other shortcuts.

Key advantages:

* **Declarative syntax**: Components say what keys they will respond to.
* **Intuitive DX**: Decorate a class or method to bind it to specified keys.
* **Scoping**: Designate the scope of your bindings by decorating/wrapping components. Only those components and their children will receive the designated key events, and then only when they appear to be active.
* **Modifier keys**: Support for standard modifier key combinations.
* **Lightweight**: 2kb compressed and gzipped, and only attaches a single keydown listener to document, no matter how many keybindings you specify.
* **Cross-browser**: Works in all browsers except IE 8 and below.

Consult the [API & Reference Documentation](https://github.com/jedverity/react-keydown/wiki/API-&-Reference) or continue reading below for quick start.

**NOTE**: react-keydown doesn't use decorators itself, but to use the `@keydown` pattern in your application you will need a transpiler like Babel and a decorator transform plugin like this: https://github.com/loganfsmyth/babel-plugin-transform-decorators-legacy.

## Install

```
npm install --save react-keydown
```

## Use

The default build of react-keydown uses the CommonJS module system. For
AMD or other support, use the [umd-specific
branch](https://github.com/jedverity/react-keydown/tree/master-umd) instead.

### For methods: Decorate with keys that should trigger method

```javascript
import React from 'react';
import keydown from 'react-keydown';

class MyComponent extends React.Component {

  @keydown( 'enter' ) // or specify `which` code directly, in this case 13
  submit( event ) {
    // do something, or not, with the keydown event, maybe event.preventDefault()
    MyApi.post( this.state );
  }
}
```

Note: Since the only context we have for keydown events is the component, decorated methods receive the event as their sole argument and the component instance as context.

#### Specify multiple keys that should trigger the method

```javascript
import keydown, { Keys } from 'react-keydown';

const { ENTER, TAB } = Keys; // optionally get key codes from Keys lib to check against later

@keydown( ENTER, TAB, 'ctrl+z' ) // could also be an array
autocomplete( event ) {
  if ( event.which === ENTER ) { ... }
  MyApi.get( this.state );
}
```

### For classes: Pass keydown events into your component

```javascript
@keydown
class MyComponent extends React.Component {
  componentWillReceiveProps( { keydown } ) {
    if ( keydown.event ) {
      // inspect the keydown event and decide what to do
      console.log( keydown.event.which );
    }
  }

  render() {
    return (
      <div>keydown events will only get passed down after this DOM node mounts or is clicked on</div>
    );
  }
}

export default MyComponent;
```

#### Monitor only key codes `which` you care about:

```javascript
const KEYS = [ 'shift+up', 'shift+down', 'enter', 'j', 'k', 'h', 'l' ];

@keydown( KEYS )
class MyComponent extends React.Component {
  ...
}
```

#### Use the `@keydownScoped` shortcut

When using the class decorator/higher-order component, decorate methods with `@keydownScoped` to identify the `keydown.event` prop as it comes in and bind certain values to methods:

```javascript
import keydown, { keydownScoped } from 'react-keydown';

@keydown( 'enter' ) // optional to specify a key here. if called with just @keydown, all key events will get passed down
class MyComponent extends React.Component {
  render() {
    return <MyOtherComponent {...this.props} />;
  }
}

class MyOtherComponent extends React.Component {
  ...
  @keydownScoped( 'enter' ) // inspects nextProps.keydown.event in componentWillReceiveProps behind the scenes
  submit() {
    // submit
  }
}
```

This is a convenience method, but also lets you specify a larger view context where this key binding should be active. Sometimes the component where the binding is declared is too small on its own.

This can also be a good way to set up app-wide shortcuts. Wrap your root component with `@keydown` and then use  `@keydownScoped` or manually inspect the `keydown.event` props in the child components where those bindings are relevant.

### Handling all keys

In some cases you might want to handle all keys on your own. For that, you can specify the following:

```
import keydown, { ALL_KEYS } from 'react-keydown'

@keydown( ALL_KEYS )
handleKeys(ev) {
  // handle keys here
}
```

### Handling all printable keys

Another useful feature is handling all printable characters.

```
import keydown, { ALL_PRINTABLE_KEYS } from 'react-keydown'

@keydown( ALL_PRINTABLE_KEYS )
beginEdit(ev) {
  // Start editing
}
```

### Caveat: Input, textarea, and select elements

By default, bindings will not work when these fields have focus, in order not to interfere with user input and shortcuts related to these controls. You can override this in two ways:

1. Give your shortcut a `ctrl` modifier.

2. Since v1.6.0, there is experimental support for adding an `onKeyDown` binding to the element, specifying a method decorated with `@keydown` as the handler. For example:

```javascript
class MyClass extends React.Component {

  @keydown( 'a' )
  myMethod( event ) {
    console.log( event ); // should log only on 'a' keystroke, whether input is focused or not
  }

  render() {
    return <input onKeyDown={ this.myMethod } />;
  }
}
```

In the second case you could make multiple inputs work this way by spreading `{ onKeyDown: this.myMethod }` into them, or by making this a reusable input component that takes the method as a prop (or composes multiple methods passed in as props).

## Demo

Go to the [live
demo](http://glortho.github.io/react-keydown/example/index.html) or:

```
$ open example/public/index.html
```

Note that this is very much a work in progress!

## Test

```
$ npm test
```

## Notes, disclaimers, and tips

* The decorator pattern `@keydown` currently requires transpilation by
  the [Babel legacy decorators transform](https://github.com/loganfsmyth/babel-plugin-transform-decorators-legacy) or the equivalent.
* Components that have a [React 16 fragment](https://reactjs.org/docs/fragments.html) at their root may not be activated properly when clicked. See [this issue](https://github.com/glortho/react-keydown/issues/80) for more detail.
* The default build outputs CommonJS modules and native ES modules. For AMD or other support, use the
  [umd-specific
  branch](https://github.com/glortho/react-keydown/tree/master-umd) instead.
* This lib has only been tested using ES2015 classes and class methods. Some method decoration
  functionality may work on other types of object methods.
* Duplicate keybindings for components that are mounted at the same time will
  not both fire. The more recently mounted component, or the one that has been
  focused or clicked most recently, will win. If you do want both to fire,
  decorate a common ancestor class with `@keydown( ... )` and then use
  `@keydownScoped( ... )` in the child components (or just inspect
  `nextProps.keydown.event` in both).
* Since the only context we have for keydown events is the component, decorated
  methods receive the event as their sole argument and the component instance as
  context.
* The method decorators wrap React lifecycle methods in order to work
  as seamlessly and efficiently as possible. The class decorator does not do
  this, functioning instead as a higher-order component.

## Questions

Why is this so limited, only working on `keydown` and such?

> I published this out of my particular need on a project. If anyone else ever
arrives here and needs something else let me know via issues or a pull request.


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

package com.google.devtools.build.lib.skylarkbuildapi.cpp;

import com.google.devtools.build.lib.cmdline.Label;
import com.google.devtools.build.lib.skylarkbuildapi.FileApi;
import com.google.devtools.build.lib.syntax.EvalException;
import com.google.devtools.build.lib.syntax.Sequence;
import com.google.devtools.build.lib.syntax.StarlarkSemantics;
import com.google.devtools.build.lib.syntax.StarlarkValue;
import net.starlark.java.annot.StarlarkBuiltin;
import net.starlark.java.annot.StarlarkDocumentationCategory;
import net.starlark.java.annot.StarlarkMethod;

/** Either libraries, flags or other files that may be passed to the linker as inputs. */
@StarlarkBuiltin(
    name = "LinkerInput",
    category = StarlarkDocumentationCategory.BUILTIN,
    doc = "Either libraries, flags or other files that may be passed to the linker as inputs.")
public interface LinkerInputApi<
        LibraryToLinkT extends LibraryToLinkApi<FileT>, FileT extends FileApi>
    extends StarlarkValue {
  @StarlarkMethod(
      name = "owner",
      doc = "Returns the owner of this LinkerInput.",
      structField = true)
  Label getStarlarkOwner() throws EvalException;

  @StarlarkMethod(
      name = "user_link_flags",
      doc = "Returns the list of user link flags passed as strings.",
      structField = true)
  Sequence<String> getStarlarkUserLinkFlags();

  @StarlarkMethod(
      name = "libraries",
      doc =
          "Returns the depset of LibraryToLink. May return a list but this is "
              + "deprecated. See #8118.",
      structField = true,
      useStarlarkSemantics = true)
  Sequence<LibraryToLinkT> getStarlarkLibrariesToLink(StarlarkSemantics semantics);

  @StarlarkMethod(
      name = "additional_inputs",
      doc = "Returns the depset of additional inputs, e.g.: linker scripts.",
      structField = true)
  Sequence<FileT> getStarlarkNonCodeInputs();
}

redpajama_set_name: RedPajamaGithub


text:
package org.sleuthkit.autopsy.directorytree;

import java.awt.event.ActionListener;

/**
 * This is the form / panel to show the Volume Details.
 */
@SuppressWarnings("PMD.SingularField") // UI widgets cause lots of false positives
class VolumeDetailsPanel extends javax.swing.JPanel {

    /**
     * Creates new form VolumeDetailPanel
     */
    VolumeDetailsPanel() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        flagsValue = new javax.swing.JLabel();
        descValue = new javax.swing.JLabel();
        lengthValue = new javax.swing.JLabel();
        startValue = new javax.swing.JLabel();
        startLabel = new javax.swing.JLabel();
        lengthLabel = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();
        volumeIDLabel = new javax.swing.JLabel();
        volumeIDValue = new javax.swing.JLabel();
        descLabel = new javax.swing.JLabel();
        flagsLabel = new javax.swing.JLabel();
        OKButton = new javax.swing.JButton();

        flagsValue.setFont(flagsValue.getFont().deriveFont(flagsValue.getFont().getStyle() & ~java.awt.Font.BOLD, 11));
        flagsValue.setText(org.openide.util.NbBundle.getMessage(VolumeDetailsPanel.class, "VolumeDetailsPanel.flagsValue.text")); // NOI18N

        descValue.setFont(descValue.getFont().deriveFont(descValue.getFont().getStyle() & ~java.awt.Font.BOLD, 11));
        descValue.setText(org.openide.util.NbBundle.getMessage(VolumeDetailsPanel.class, "VolumeDetailsPanel.descValue.text")); // NOI18N

        lengthValue.setFont(lengthValue.getFont().deriveFont(lengthValue.getFont().getStyle() & ~java.awt.Font.BOLD, 11));
        lengthValue.setText(org.openide.util.NbBundle.getMessage(VolumeDetailsPanel.class, "VolumeDetailsPanel.lengthValue.text")); // NOI18N

        startValue.setFont(startValue.getFont().deriveFont(startValue.getFont().getStyle() & ~java.awt.Font.BOLD, 11));
        startValue.setText(org.openide.util.NbBundle.getMessage(VolumeDetailsPanel.class, "VolumeDetailsPanel.startValue.text")); // NOI18N

        startLabel.setFont(startLabel.getFont().deriveFont(startLabel.getFont().getStyle() & ~java.awt.Font.BOLD, 11));
        startLabel.setText(org.openide.util.NbBundle.getMessage(VolumeDetailsPanel.class, "VolumeDetailsPanel.startLabel.text")); // NOI18N

        lengthLabel.setFont(lengthLabel.getFont().deriveFont(lengthLabel.getFont().getStyle() & ~java.awt.Font.BOLD, 11));
        lengthLabel.setText(org.openide.util.NbBundle.getMessage(VolumeDetailsPanel.class, "VolumeDetailsPanel.lengthLabel.text")); // NOI18N

        jLabel1.setFont(jLabel1.getFont().deriveFont(jLabel1.getFont().getStyle() | java.awt.Font.BOLD, 18));
        jLabel1.setText(org.openide.util.NbBundle.getMessage(VolumeDetailsPanel.class, "VolumeDetailsPanel.jLabel1.text")); // NOI18N

        volumeIDLabel.setFont(volumeIDLabel.getFont().deriveFont(volumeIDLabel.getFont().getStyle() & ~java.awt.Font.BOLD, 11));
        volumeIDLabel.setText(org.openide.util.NbBundle.getMessage(VolumeDetailsPanel.class, "VolumeDetailsPanel.volumeIDLabel.text")); // NOI18N

        volumeIDValue.setFont(volumeIDValue.getFont().deriveFont(volumeIDValue.getFont().getStyle() & ~java.awt.Font.BOLD, 11));
        volumeIDValue.setText(org.openide.util.NbBundle.getMessage(VolumeDetailsPanel.class, "VolumeDetailsPanel.volumeIDValue.text")); // NOI18N

        descLabel.setFont(descLabel.getFont().deriveFont(descLabel.getFont().getStyle() & ~java.awt.Font.BOLD, 11));
        descLabel.setText(org.openide.util.NbBundle.getMessage(VolumeDetailsPanel.class, "VolumeDetailsPanel.descLabel.text")); // NOI18N

        flagsLabel.setFont(flagsLabel.getFont().deriveFont(flagsLabel.getFont().getStyle() & ~java.awt.Font.BOLD, 11));
        flagsLabel.setText(org.openide.util.NbBundle.getMessage(VolumeDetailsPanel.class, "VolumeDetailsPanel.flagsLabel.text")); // NOI18N

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(112, 112, 112)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(startLabel)
                            .addComponent(volumeIDLabel)
                            .addComponent(lengthLabel)
                            .addComponent(descLabel)
                            .addComponent(flagsLabel))
                        .addGap(18, 18, 18)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(flagsValue)
                            .addComponent(descValue)
                            .addComponent(lengthValue)
                            .addComponent(startValue)
                            .addComponent(volumeIDValue)))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(59, 59, 59)
                        .addComponent(jLabel1)))
                .addContainerGap(58, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addGap(11, 11, 11)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(volumeIDLabel)
                    .addComponent(volumeIDValue))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(startLabel)
                    .addComponent(startValue))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lengthLabel)
                    .addComponent(lengthValue))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(descLabel)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(flagsLabel)
                            .addComponent(flagsValue)))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(descValue)
                        .addGap(25, 25, 25)))
                .addContainerGap(29, Short.MAX_VALUE))
        );

        OKButton.setFont(OKButton.getFont().deriveFont(OKButton.getFont().getStyle() & ~java.awt.Font.BOLD, 11));
        OKButton.setText(org.openide.util.NbBundle.getMessage(VolumeDetailsPanel.class, "VolumeDetailsPanel.OKButton.text")); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addContainerGap())
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(OKButton, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(145, 145, 145))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGap(18, 18, 18)
                .addComponent(OKButton, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
    }// </editor-fold>//GEN-END:initComponents

    public void setVolumeIDValue(String arg) {
        volumeIDValue.setText(arg);
    }

    public void setStartValue(String arg) {
        startValue.setText(arg);
    }

    public void setLengthValue(String arg) {
        lengthValue.setText(arg);
    }

    public void setDescValue(String arg) {
        descValue.setText(arg);
    }

    public void setFlagsValue(String arg) {
        flagsValue.setText(arg);
    }

    public void setOKButtonActionListener(ActionListener e) {
        OKButton.addActionListener(e);
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton OKButton;
    private javax.swing.JLabel descLabel;
    private javax.swing.JLabel descValue;
    private javax.swing.JLabel flagsLabel;
    private javax.swing.JLabel flagsValue;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JLabel lengthLabel;
    private javax.swing.JLabel lengthValue;
    private javax.swing.JLabel startLabel;
    private javax.swing.JLabel startValue;
    private javax.swing.JLabel volumeIDLabel;
    private javax.swing.JLabel volumeIDValue;
    // End of variables declaration//GEN-END:variables

}


text:
Learn
=====
.. automodule:: zounds.learn
.. currentmodule:: zounds.learn

PyTorch Modules
---------------
.. autoclass:: FilterBank
.. autoclass:: SincLayer

The Basics
----------
.. autoclass:: PreprocessingPipeline

.. autoclass:: Pipeline

.. autoclass:: Preprocessor
    :members:

.. autoclass:: PreprocessResult

.. autoclass:: PipelineResult

Custom Losses
-------------
.. autoclass:: PerceptualLoss

Data Preparation
----------------
.. autoclass:: UnitNorm
.. autoclass:: MuLawCompressed
.. autoclass:: MeanStdNormalization
.. autoclass:: InstanceScaling
.. autoclass:: Weighted

Sampling
--------
.. autoclass:: ShuffledSamples

Machine Learning Models
-----------------------
.. autoclass:: KMeans
.. autoclass:: SklearnModel
.. autoclass:: PyTorchNetwork
.. autoclass:: PyTorchGan
.. autoclass:: PyTorchAutoEncoder
.. autoclass:: SupervisedTrainer
.. autoclass:: TripletEmbeddingTrainer
.. autoclass:: WassersteinGanTrainer

Hashing
-------
.. autoclass:: SimHash

Learned Models in Audio Processing Graphs
-----------------------------------------
.. autoclass:: Learned
    :members:


text:
import * as path from 'path'
import {ipcMain, app, Menu, Tray} from 'electron'

let appIcon: Electron.Tray|null = null

ipcMain.on('put-in-tray', function (event) {
  const iconName: string = process.platform === 'win32' ? 'windows-icon.png' : 'iconTemplate.png'
  const iconPath: string = path.join(__dirname, iconName)
  appIcon = new Tray(iconPath)
  const contextMenu: Electron.Menu = Menu.buildFromTemplate([{
    label: 'Remove',
    click: function (): void {
      event.sender.send('tray-removed')
    }
  }])
  appIcon.setToolTip('Electron Demo in the tray.')
  appIcon.setContextMenu(contextMenu)
})

ipcMain.on('remove-tray', function (): void {
  appIcon.destroy()
})

app.on('window-all-closed', function (): void {
  if (appIcon) appIcon.destroy()
})


text:
from py4j.java_gateway import java_import
from .utils import datetime_to_nanos
import numpy as np
import pandas as pd

class DateTimeIndex(object):
    """
    A DateTimeIndex maintains a bi-directional mapping between integers and an ordered collection of
    date-times. Multiple date-times may correspond to the same integer, implying multiple samples
    at the same date-time.

    To avoid confusion between the meaning of "index" as it appears in "DateTimeIndex" and "index"
    as a location in an array, in the context of this class, we use "location", or "loc", to refer
    to the latter.
    """

    def __init__(self, jdt_index):
        self._jdt_index = jdt_index

    def __len__(self):
        """Returns the number of timestamps included in the index."""
        return self._jdt_index.size()

    def _zdt_to_nanos(self, zdt):
        """Extracts nanoseconds from a ZonedDateTime"""
        instant = zdt.toInstant()
        return instant.getNano() + instant.getEpochSecond() * 1000000000

    def first(self):
        """Returns the earliest timestamp in the index, as a Pandas Timestamp."""
        return pd.Timestamp(self._zdt_to_nanos(self._jdt_index.first()))

    def last(self):
        """Returns the latest timestamp in the index, as a Pandas Timestamp."""
        return pd.Timestamp(self._zdt_to_nanos(self._jdt_index.last()))

    def datetime_at_loc(self, loc):
        """Returns the timestamp at the given integer location as a Pandas Timestamp."""
        return pd.Timestamp(self._zdt_to_nanos(self._jdt_index.dateTimeAtLoc(loc)))

    def __getitem__(self, val):
        # TODO: throw an error if the step size is defined
        if isinstance(val, slice):
            start = datetime_to_nanos(val.start)
            stop = datetime_to_nanos(val.stop)
            jdt_index = self._jdt_index.slice(start, stop)
            return DateTimeIndex(jdt_index)
        else:
            return self._jdt_index.locAtDateTime(datetime_to_nanos(val))

    def islice(self, start, end):
        """
        Returns a new DateTimeIndex, containing a subslice of the timestamps in this index,
        as specified by the given integer start and end locations.

        Parameters
        ----------
        start : int
            The location of the start of the range, inclusive.
        end : int
            The location of the end of the range, exclusive.
        """
        jdt_index = self._jdt_index.islice(start, end)
        return DateTimeIndex(jdt_index=jdt_index)

    def to_pandas_index(self):
        """Returns a pandas.DatetimeIndex representing the same date-times"""
        # TODO: we can probably speed this up for uniform indices
        arr = self._jdt_index.toNanosArray()
        return pd.DatetimeIndex(arr)

    def __eq__(self, other):
        return self._jdt_index.equals(other._jdt_index)

    def __ne__(self, other):
        return not self.__eq__(other)

    def __repr__(self):
        return self._jdt_index.toString()

class _Frequency(object):
    def __eq__(self, other):
        return self._jfreq.equals(other._jfreq)

    def __ne__(self, other):
       return not self.__eq__(other)

class DayFrequency(_Frequency):
    """
    A frequency that can be used for a uniform DateTimeIndex, where the period is given in days.
    """

    def __init__(self, days, sc):
        self._jfreq = sc._jvm.com.cloudera.sparkts.DayFrequency(days)

    def days(self):
        return self._jfreq.days()

class HourFrequency(_Frequency):
    """
    A frequency that can be used for a uniform DateTimeIndex, where the period is given in hours.
    """

    def __init__(self, hours, sc):
        self._jfreq = sc._jvm.com.cloudera.sparkts.HourFrequency(hours)

    def hours(self):
        return self_jfreq.hours()

class BusinessDayFrequency(object):
    """
    A frequency that can be used for a uniform DateTimeIndex, where the period is given in
    business days.
    """

    def __init__(self, bdays, sc):
        self._jfreq = sc._jvm.com.cloudera.sparkts.BusinessDayFrequency(bdays)

    def __eq__(self, other):
         return self._jfreq.equals(other._jfreq)

    def __ne__(self, other):
        return not self.__eq__(other)

def uniform(start, end=None, periods=None, freq=None, sc=None):
    """
    Instantiates a uniform DateTimeIndex.

    Either end or periods must be specified.

    Parameters
    ----------
        start : string, long (nanos from epoch), or Pandas Timestamp
        end : string, long (nanos from epoch), or Pandas Timestamp
        periods : int
        freq : a frequency object
        sc : SparkContext
    """
    dtmodule = sc._jvm.com.cloudera.sparkts.__getattr__('DateTimeIndex$').__getattr__('MODULE$')
    if freq is None:
        raise ValueError("Missing frequency")
    elif end is None and periods == None:
        raise ValueError("Need an end date or number of periods")
    elif end is not None:
        return DateTimeIndex(dtmodule.uniformFromInterval( \
            datetime_to_nanos(start), datetime_to_nanos(end), freq._jfreq))
    else:
        return DateTimeIndex(dtmodule.uniform( \
            datetime_to_nanos(start), periods, freq._jfreq))

def irregular(timestamps, sc):
    """
    Instantiates an irregular DateTimeIndex.

    Parameters
    ----------
        timestamps : a Pandas DateTimeIndex, or an array of strings, longs (nanos from epoch), Pandas
            Timestamps
        sc : SparkContext
    """
    dtmodule = sc._jvm.com.cloudera.sparkts.__getattr__('DateTimeIndex$').__getattr__('MODULE$')
    arr = sc._gateway.new_array(sc._jvm.long, len(timestamps))
    for i in xrange(len(timestamps)):
        arr[i] = datetime_to_nanos(timestamps[i])
    return DateTimeIndex(dtmodule.irregular(arr))


text:
/*
Package forget provides an in-memory cache for arbitrary, binary data.

Caching

The cache identifies items by their keys. It stores them with individual expiration time (TTL). The associated
content is stored in binary format.  Storing a new item with the same key, overrides the previous one. A cached
item can be retrieved or deleted with its key. As a special use case, it is possible to store only keys, where
the useful information is whether a key exists or not. If a new item doesn't fit in the free space, the least
recently used item is evicted (LRU).

Keyspaces

Keyspaces, when used (see NewCacheSpaces()), allow some optimization of the LRU eviction mechanism. Items that
are more expensive to produce but less frequently accessed than others, can be stored in different keyspaces.
When eviction is required, the cache tries to evict enough items from the same keyspace as the one currently
being filled. When using keyspaces, the same key can appear in different keyspaces pointing to different items.

Memory

The cache allocates all the used memory on start. To support parallel access, it splits the allocated memory
into segments. There are typically as many segments as the maximum of NumCPU() and GOMAXPROCS(). The maximum
size of a stored item is the total cache size divided by the number of segments.

The segments are split into chunks. One cached item can span over multiple chunks, but the chunks cannot be
shared between the items. This means that the cache is almost never fully utilized. The chunk size is an
initialization option, it typically should be a 'couple of times' smaller than the expected size of the 'bulk'
of the cached items.

The cache counts the size of the item keys in the used space, but there is some lookup metadata that is not
counted: ~24 bytes for each chunk and ~120 bytes for each item.

IO

The associated data of the keys can be accessed for read, seek and write through the standard Go interfaces. As
a shortcut, the data can be retrieved or set as a single byte slice, too. When using the IO interfaces, the item
data can be accessed concurrently, and reading from an item can be started before the write has finished. When
the reader reaches a point that was not yet filled by the writer, it blocks, and continues only when more data
was written, or returns with EOF once the write has finished.

While writing an item, chunks are continuously assigned to the item from the free range of the allocated memory.
If there are no free chunks, the cache evicts enough of the least recently used items. The cache doesn't evict
those items that are currently being read by an unclosed reader. Similarly, when deleting an item or overwriting
one, if it has active readers associated with it, the item is only marked for delete, but the active readers can
finish reading from it.

Monitoring

The cache provides statistics about its internal state, including metrics like item count, effective and used
size, active readers and writers. When configured, it also provides change notifications. Depending on the
configured notification mask, it can send events about: cache hit/miss, evictions, allocation failures, etc.
*/
package forget


text:
<?php
namespace spec\rtensfido;

use spec\rtens\fido\fixture\ComposerFixture;
use spec\rtens\fido\fixture\FileFixture;
use watoki\scrut\Specification;

/**
 * @property ComposerFixture $fix <-
 * @property FileFixture file <-
 */
class FromRepositoryTest extends Specification {

    function testCloneRepository() {
        $this->fix->givenTheComposerJson('{
            "extra":{
                "fido-fetch": {
                    "some repo": {
                        "source":"https://example.com/some/repo.git"
                    }
                }
            }
        }');
        $this->fix->whenIRunComposerWithThePlugin();
        $this->file->thenThereShouldBeADirectory('assets/vendor');
        $this->fix->then_ShouldBeExecuted("git clone --no-checkout 'https://example.com/some/repo.git' 'vendor/fido/repo_git-7cd3d7da4878bedbcfde6f9a52615632'");
        $this->fix->then_ShouldBeExecuted("git checkout 'master'");

        $this->fix->thenTheOutputShouldContain('Installing fido/repo_git-7cd3d7da4878bedbcfde6f9a52615632 (1.0)');
        $this->fix->thenTheOutputShouldContain('Cloning master');
    }

    function testSpecifyTag() {
        $this->fix->givenTheComposerJson('{
            "extra":{
                "fido-fetch": {
                    "some repo": {
                        "source":"https://example.com/some/repo.git",
                        "reference":"v1.1"
                    }
                }
            }
        }');
        $this->fix->whenIRunComposerWithThePlugin();
        $this->fix->thenTheOutputShouldContain('Cloning v1.1');
    }

    function testUpdateRepository() {
        $this->fix->givenTheComposerJson('{
            "extra":{
                "fido-fetch": {
                    "some repo": {
                        "source":"https://example.com/some/repo.git"
                    }
                }
            }
        }');
        $this->fix->whenIRunComposerWithThePlugin();
        $this->file->givenTheDirectory('vendor/fido/repo_git-7cd3d7da4878bedbcfde6f9a52615632/.git');
        $this->fix->givenTheComposerJson('{
            "extra":{
                "fido-fetch": {
                    "some repo": {
                        "source":"https://example.com/some/repo.git",
                        "reference": "1.1"
                    }
                }
            }
        }');
        $this->fix->whenIRunComposerWithThePlugin();
        $this->fix->then_ShouldBeExecuted('git fetch composer');
        $this->fix->then_ShouldBeExecuted('git fetch --tags composer');
        $this->fix->then_ShouldBeExecuted("git checkout '1.1'");

        $this->fix->thenTheOutputShouldContain('Updating fido/repo_git-7cd3d7da4878bedbcfde6f9a52615632 (1.0 => 1.1)');
        $this->fix->thenTheOutputShouldContain('Checking out 1.1');
    }

    function testSpecifyTargetFolder() {
        $this->fix->givenTheComposerJson('{
            "extra":{
                "fido-fetch": {
                    "some repo": {
                        "source":"https://example.com/some/repo.git",
                        "target":"my/target"
                    }
                }
            }
        }');
        $this->fix->whenIRunComposerWithThePlugin();
        $this->fix->thenTheOutputShouldContain('vendor/fido/repo_git-7cd3d7da4878bedbcfde6f9a52615632 -> assets/vendor/my/target');
    }

    function testSourceAsKey() {
        $this->fix->givenTheComposerJson('{
            "extra":{
                "fido-fetch": {
                    "https://example.com/some/repo.git":{}
                }
            }
        }');
        $this->fix->whenIRunComposerWithThePlugin();
        $this->fix->thenTheOutputShouldContain('Installing fido/repo_git-7cd3d7da4878bedbcfde6f9a52615632 (1.0)');
    }

    function testTagAsValue() {
        $this->fix->givenTheComposerJson('{
            "extra":{
                "fido-fetch": {
                    "https://example.com/some/repo.git":"v1.3"
                }
            }
        }');
        $this->fix->whenIRunComposerWithThePlugin();
        $this->fix->thenTheOutputShouldContain('Cloning v1.3');
    }

    function testSpecifyType() {
        $this->fix->givenTheComposerJson('{
            "extra":{
                "fido-fetch": {
                    "some repo": {
                        "source":"https://example.com/some/repo",
                        "type":"git"
                    }
                }
            }
        }');
        $this->fix->whenIRunComposerWithThePlugin();
        $this->fix->thenTheOutputShouldContain('Installing fido/repo-85c6fea5a41a6e5852f7a986453fee60 (1.0)');
    }

    function testInRequire() {
        $this->fix->givenTheComposerJson('{
            "require": {
                "fido-fetch:https://example.com/some/repo.git":"v1.3"
            }
        }');
        $this->fix->whenIRunComposerWithThePlugin();
        $this->fix->thenTheOutputShouldContain('Installing fido/repo_git-7cd3d7da4878bedbcfde6f9a52615632 (v1.3)');
    }

}


text:
.file-upload label {
  line-height: 22px;
  display: block;
}

.file-upload input[name='uploadfile'] {
  position: absolute;
  visibility: hidden;
  width: 0;
}


text:
package com.bq.corbel.lib.token.reader;

import com.bq.corbel.lib.token.TokenInfo;

/**
 * @author Alexander De Leon
 *
 */
public interface TokenReader {

	TokenInfo getInfo();

	long getExpireTime();

	String getSignature();

	String getToken();

}


text:
const webpack = require('webpack');
const paths = require('./paths');
const HtmlWebpackPlugin = require('html-webpack-plugin');

const publicPath = '/'

module.exports = {
  mode: 'development',
  entry: [
    paths.appContainerJs
  ],
  devtool: 'cheap-module-source-map',
  output: {
    filename: 'bundle.js',
    publicPath: publicPath,
  },
  module: {
    rules: [
      {
        test: /\.js.flow$/, // assuming the files are named .js.flow
        enforce: 'pre',
        use: ['remove-flow-types-loader']
      },
      {
        test: /\.(js|mjs|jsx|ts|tsx)$/,
        enforce: 'pre',
        use: [
          require.resolve('babel-loader')
        ],
        include: [
          paths.appSrc,
          paths.appContainerJs
        ]
      },
      // Avoid "require is not defined" errors
      // (found in graphql@0.13.2)
      {
        test: /\.mjs$/,
        include: /node_modules/,
        type: "javascript/auto",
      },
      {
        test: /\.css$/,
        loader: 'style-loader!css-loader'
      }
    ]
  },
  plugins: [
    // Generates an `index.html` file with the <script> injected.
    new HtmlWebpackPlugin(
      {
        inject: true,
        template: paths.appHtml,
      }
    ),
    new webpack.HotModuleReplacementPlugin()
  ],
  devServer: {
    // Enable gzip compression of generated files.
    compress: true,
    // Enable hot reloading server. It will provide /sockjs-node/ endpoint
    // for the WebpackDevServer client so it can learn when the files were
    // updated. The WebpackDevServer client is included as an entry point
    // in the Webpack development configuration. Note that only changes
    // to CSS are currently hot reloaded. JS changes will refresh the browser.
    hot: true,
    port: process.env.PORT || 3000,
    // It is important to tell WebpackDevServer to use the same "root" path
    // as we specified in the config. In development, we always serve from /.
    publicPath: publicPath,
    stats: {
      all: false,
      // Show the url we're serving at
      wds: true,
      // Config for minimal console.log mess.
      assets: false,
      colors: true,
      version: false,
      hash: false,
      timings: false,
      chunks: false,
      chunkModules: false,
    },
  },
};


text:
import CValidation from './c-validation'

export default CValidation


text:
'use strict';

var Lib = require('../../lib');

var hasColumns = require('../heatmap/has_columns');
var handleXYZDefaults = require('../heatmap/xyz_defaults');
var handleStyleDefaults = require('../contour/style_defaults');
var attributes = require('./attributes');

module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
    function coerce(attr, dflt) {
        return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
    }

    var len = handleXYZDefaults(traceIn, traceOut, coerce);
    if(!len) {
        traceOut.visible = false;
        return;
    }

    coerce('text');
    coerce('connectgaps', hasColumns(traceOut));

    var contourStart = Lib.coerce2(traceIn, traceOut, attributes, 'contours.start'),
        contourEnd = Lib.coerce2(traceIn, traceOut, attributes, 'contours.end'),
        autocontour = coerce('autocontour', !(contourStart && contourEnd));

    if(autocontour) coerce('ncontours');
    else coerce('contours.size');

    handleStyleDefaults(traceIn, traceOut, coerce, layout);
};


text:
<?

function GetCategories() {
    global $pdo;
  $Categories = [];
  foreach($pdo->query('SELECT * FROM tipos_productos') as $Category)
  {
       $Categories[$Category['tipo_producto_id']] = $Category;
  }
  return $Categories;
}

function GetActions() {
    global $pdo;
  $Categories = [];
  foreach($pdo->query('SELECT * FROM tipo_acciones') as $Category)
  {
       $Categories[$Category['tipo_acciones_id']] = $Category;
  }
  return $Categories;
}

function addCategory($CategoryName) {
	if ($CategoryName !="") {
	$pdo->exec('INSERT INTO `tipos_productos`(`tipo_producto_display`) VALUES ("'.$CategoryName.'")');
	}
}

function GetProducts($criteria) {
  global $pdo;
  $Products = [];
  $sql = "";
  if ($criteria != "") {
    $sql = 'SELECT * FROM producto WHERE titulo LIKE "%'.$criteria.'%" OR direccion = "'.$criteria.'"';
  } else  {
    $sql = 'SELECT * FROM producto';
  }
  foreach($pdo->query($sql) as $Product)
  {
      foreach ($Product as $key => $value) {
        if (AssociateID($value, $key)) {
        $Product[$key."_Display"] = AssociateID($value, $key);
        }
      }
       $Products[$Product['id']] = $Product;
  }

  return $Products;
}

function GetProduct($id) {
global $pdo;
$UCompany = $_SESSION["User"]["company_id"];
$sql = 'SELECT * FROM productos WHERE id = "'.$id.'"';
foreach($pdo->query($sql) as $Product)
  {
    return $Product;
  }
}

function OutOfStock($pid, $q) {
  global $pdo;
	$UCompany = $_SESSION["User"]["company_id"];
	$pdo->exec('UPDATE producto SET cantidad = cantidad -'.$q.' WHERE id = "'.$pid.'"');
}
?>


text:
package org.apache.ignite.ml.util.generators.primitives.vector;

import org.apache.ignite.ml.math.primitives.vector.Vector;
import org.junit.Test;

import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;

/**
 * Tests for {@link ParametricVectorGenerator}.
 */
public class ParametricVectorGeneratorTest {
    /** */
    @Test
    public void testGet() {
        Vector vec = new ParametricVectorGenerator(
            () -> 2.,
            t -> t,
            t -> 2 * t,
            t -> 3 * t,
            t -> 100.
        ).get();

        assertEquals(4, vec.size());
        assertArrayEquals(new double[] {2., 4., 6., 100.}, vec.asArray(), 1e-7);
    }

    /** */
    @Test(expected = IllegalArgumentException.class)
    public void testIllegalArguments() {
        new ParametricVectorGenerator(() -> 2.).get();
    }
}


text:
package com.genesys.workspace.events;

public interface ErrorEventListener {
    void handleEventError(EventError msg);
}


text:
<?php

/**
 * CodeFaqs 2013
 *
 * @author Marc Morera
 * @author Miguel Angel Rios
 */

namespace CodeFaqs\FrontBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

class CodeFaqsFrontBundle extends Bundle
{
}


text:
The `python-acoustics` module is a Python module with useful tools for acousticians.

**Disclaimer**: This module is still heavily in development, and might break what you're working on.

## Installation

Currently there are no packages available.

The recommended method to install is to clone this repository

`git clone git@github.com:python-acoustics/python-acoustics.git`

and install this package in development mode

`python setup.py develop`

This way one can easily update to the latest version using

`git pull`

and running again

`python setup.py develop`

## Examples

Several examples can be found in the `examples` folder.

## Documentation

Documentation can be found [here](http://python-acoustics.github.io/python-acoustics/).

## License

`python-acoustics` is distributed under the BSD 3-clause license. See LICENSE for more information.

## Contributing

Contributors are always welcome.


text:
    <widget title="Some Title" subtitle="Positioned to the right of the image" title-position="right">

    </widget>
    <widget title="Some Title" subtitle="Positioned to the left of the image" title-position="left">

    </widget>


text:
package me.sharpjaws.sharpSK.hooks.Towny;

import java.util.ArrayList;

import javax.annotation.Nullable;

import org.bukkit.event.Event;

import com.palmergames.bukkit.towny.object.Nation;
import com.palmergames.bukkit.towny.object.TownyUniverse;

import ch.njol.skript.lang.Expression;
import ch.njol.skript.lang.SkriptParser;
import ch.njol.skript.lang.util.SimpleExpression;
import ch.njol.util.Kleenean;

public class ExprTownyAllNations extends SimpleExpression<String> {

	@Override
	public Class<? extends String> getReturnType() {
		return String.class;
	}

	@SuppressWarnings("unchecked")
	@Override
	public boolean init(Expression<?>[] expr, int matchedPattern, Kleenean paramKleenean,
			SkriptParser.ParseResult Result) {
		return true;
	}

	@Override
	public String toString(@Nullable Event e, boolean paramBoolean) {
		return "[towny] (all|the) nations";
	}

	@Override
	@Nullable
	protected String[] get(Event e) {

		ArrayList<String> narr = new ArrayList<String>();
		for (Nation a1 : TownyUniverse.getDataSource().getNations()) {

			narr.add(a1.getName());
		}

		return narr.toArray(new String[narr.size()]);

	}

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

}


text:
package au.org.aurin.wif.io.parsers;

import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import au.org.aurin.wif.exception.validate.WifInvalidInputException;
import au.org.aurin.wif.model.WifProject;
import au.org.aurin.wif.model.allocation.AllocationLU;
import au.org.aurin.wif.model.demand.DemandConfig;
import au.org.aurin.wif.model.demand.DemographicData;
import au.org.aurin.wif.model.demand.DemographicTrend;
import au.org.aurin.wif.model.demand.EmploymentDemographicData;
import au.org.aurin.wif.model.demand.EmploymentEntry;
import au.org.aurin.wif.model.demand.EmploymentPastTrendInfo;
import au.org.aurin.wif.model.demand.EmploymentSector;
import au.org.aurin.wif.model.demand.info.EmploymentCurrentData;
import au.org.aurin.wif.model.demand.info.ResidentialCurrentData;
import au.org.aurin.wif.repo.impl.CouchAllocationLUDao;

/**
 * The Class DemandSetupCouchParser.
 */
@Component
public class DemandSetupCouchParser {

  /** The Constant LOGGER. */
  private static final Logger LOGGER = LoggerFactory
      .getLogger(DemandSetupCouchParser.class);

  /** The allocation lu dao. */
  @Autowired
  private CouchAllocationLUDao allocationLUDao;

  /** The project parser. */
  @Autowired
  private ProjectCouchParser projectParser;

  /**
   * Parses the.
   *
   * @param demandConfig
   *          the demand config
   * @param project
   *          the project
   * @return the demand config
   * @throws WifInvalidInputException
   *           the wif invalid input exception
   */
  public DemandConfig parse(DemandConfig demandConfig, WifProject project)
      throws WifInvalidInputException {

    LOGGER.debug("Parsing {} demandConfig ", demandConfig.getId());
    demandConfig = parseSectors(demandConfig);
    project.setDemandConfig(demandConfig);
    // Parse residential datas
    if (demandConfig.getCurrentDemographic() != null) {

      final Set<ResidentialCurrentData> residentialDatas = demandConfig
          .getCurrentDemographic().getResidentialCurrentData();
      // ali delete later if condition
      if (residentialDatas != null) // by ali
      {
        for (final ResidentialCurrentData data : residentialDatas) {
          final AllocationLU allocationLU = allocationLUDao.findAllocationLUById(data
              .getResidentialLUId());
          data.setResidentialLU(allocationLU);
        }
      }// end if
      // Parse employment datas
      final Set<EmploymentCurrentData> employmentDatas = demandConfig
          .getCurrentDemographic().getEmploymentCurrentDatas();
      if (employmentDatas != null) {
        for (final EmploymentCurrentData data : employmentDatas) {
          data.setSector(project.getSectorByLabel(data.getSectorLabel()));
        }
      }
      demandConfig = parsePastEmployment(demandConfig, project);
    }
    // Parse trends
    if (demandConfig.getDemographicTrends() != null) {
      final Set<DemographicTrend> trends = demandConfig.getDemographicTrends();
      for (final DemographicTrend demographicTrend : trends) {
        LOGGER.trace("Parsing trends: {}", demographicTrend.getLabel());

        final Set<DemographicData> demographicData = demographicTrend
            .getDemographicData();
        for (final DemographicData data : demographicData) {
          LOGGER.trace("Parsing data for projection: {}",
              data.getProjectionLabel());
          data.setProjection(demandConfig.getProjectionByLabel(data
              .getProjectionLabel()));
          if (data instanceof EmploymentDemographicData) {
            final EmploymentDemographicData empData = ((EmploymentDemographicData) data);
            empData.setSector(demandConfig.getSectorByLabel(empData
                .getSectorLabel()));
          }
        }
      }
    }
    project.setDemandConfig(demandConfig);
    if (demandConfig.getSectors() != null) {
      project = parseALUSectors(demandConfig, project);
    }
    demandConfig.setWifProject(project);
    return demandConfig;
  }

  /**
   * Parses the alu sectors.
   *
   * @param demandConfig
   *          the demand config
   * @param project
   *          the project
   * @return the wif project
   * @throws WifInvalidInputException
   *           the wif invalid input exception
   */
  public WifProject parseALUSectors(final DemandConfig demandConfig,
      final WifProject project) throws WifInvalidInputException {
    if ((project.getSectors() != null) && (project.getSectors().size() > 0)) {

      final Set<AllocationLU> allocationLandUses = project.getAllocationLandUses();
      for (final AllocationLU allocationLU : allocationLandUses) {
        if (!allocationLU.isResidentialLU()) {
          final Set<String> sectorsLabel = allocationLU.getSectorsLabel();
          if (sectorsLabel != null) {
            LOGGER.trace("For ALU: {}, parsing the following {} sectors",
                allocationLU.getLabel(), sectorsLabel.size());

            for (final String label : sectorsLabel) {
              final EmploymentSector sector = project.getSectorByLabel(label);
              LOGGER.trace("Adding sector: {}", sector.getLabel());
              allocationLU.addEmploymentSector(sector);
            }
          } else {
            LOGGER.trace("For ALU: {}, there are not defined sectors",
                allocationLU.getLabel());
          }
        }
      }
    }
    return project;
  }

  /**
   * Parses the past employment.
   *
   * @param demandConfig
   *          the demand config
   * @param project
   *          the project
   * @return the demand config
   * @throws WifInvalidInputException
   *           the wif invalid input exception
   */
  public DemandConfig parsePastEmployment(final DemandConfig demandConfig,
      final WifProject project) throws WifInvalidInputException {
    // Parse past employment datas
    if (demandConfig.getEmploymentPastTrendInfos() != null) {
      for (final EmploymentPastTrendInfo data : demandConfig
          .getEmploymentPastTrendInfos()) {
        for (final EmploymentEntry entry : data.getEmploymentEntries()) {
          entry.setSector((project.getSectorByLabel(entry.getSectorLabel())));
        }
      }
    }
    return demandConfig;
  }

  /**
   * Parses the sectors.
   *
   * @param demandConfig
   *          the demand config
   * @return the demand config
   */
  public DemandConfig parseSectors(final DemandConfig demandConfig) {
    final Set<EmploymentSector> sectors = demandConfig.getSectors();
    LOGGER.trace("Parsing {} sectors...", sectors.size());
    for (final EmploymentSector sector : sectors) {
      LOGGER.trace("sector label: {}", sector.getLabel());
      LOGGER.trace("parsing the following sector: " + sector.getLabel());
      if (sector.getAssociatedALUsMap() != null) {
        LOGGER.trace("++++++ sector label: {} has {} associated ALU's...",
            sector.getLabel(), sector.getAssociatedALUsMap().size());
        sector.setAssociatedLUs(projectParser.parseAllocationLUs(sector
            .getAssociatedALUsMap()));
      }
    }
    return demandConfig;
  }

}


text:
void staticMemoryWrite(Adafruit_FRAM_I2C* staticMemory, int& address, const void* value, size_t size) {
  int endAddress = address + size;

  byte* ptr = (byte*)value;
  for (int i=0;address<endAddress;address++, i++) {
    staticMemory->write8(address, ptr[i]);
  }
}

void staticMemoryRead(Adafruit_FRAM_I2C* staticMemory, int& address, void* value, size_t size) {
  int endAddress = address + size;
  byte* ptr = (byte*)value;
  for (int i=0;address<endAddress;address++, i++) {
    byte b = staticMemory->read8(address);
    ptr[i] = b;
  }
}


text:
package api

import (
	"encoding/json"
	"fmt"
	"net/http"
	"sort"
	"strconv"
	"strings"

	"github.com/gorilla/mux"
	"github.com/traefik/traefik/v2/pkg/config/runtime"
	"github.com/traefik/traefik/v2/pkg/log"
)

type udpRouterRepresentation struct {
	*runtime.UDPRouterInfo
	Name     string `json:"name,omitempty"`
	Provider string `json:"provider,omitempty"`
}

func newUDPRouterRepresentation(name string, rt *runtime.UDPRouterInfo) udpRouterRepresentation {
	return udpRouterRepresentation{
		UDPRouterInfo: rt,
		Name:          name,
		Provider:      getProviderName(name),
	}
}

type udpServiceRepresentation struct {
	*runtime.UDPServiceInfo
	Name     string `json:"name,omitempty"`
	Provider string `json:"provider,omitempty"`
	Type     string `json:"type,omitempty"`
}

func newUDPServiceRepresentation(name string, si *runtime.UDPServiceInfo) udpServiceRepresentation {
	return udpServiceRepresentation{
		UDPServiceInfo: si,
		Name:           name,
		Provider:       getProviderName(name),
		Type:           strings.ToLower(extractType(si.UDPService)),
	}
}

func (h Handler) getUDPRouters(rw http.ResponseWriter, request *http.Request) {
	results := make([]udpRouterRepresentation, 0, len(h.runtimeConfiguration.UDPRouters))

	criterion := newSearchCriterion(request.URL.Query())

	for name, rt := range h.runtimeConfiguration.UDPRouters {
		if keepUDPRouter(name, rt, criterion) {
			results = append(results, newUDPRouterRepresentation(name, rt))
		}
	}

	sort.Slice(results, func(i, j int) bool {
		return results[i].Name < results[j].Name
	})

	rw.Header().Set("Content-Type", "application/json")

	pageInfo, err := pagination(request, len(results))
	if err != nil {
		writeError(rw, err.Error(), http.StatusBadRequest)
		return
	}

	rw.Header().Set(nextPageHeader, strconv.Itoa(pageInfo.nextPage))

	err = json.NewEncoder(rw).Encode(results[pageInfo.startIndex:pageInfo.endIndex])
	if err != nil {
		log.FromContext(request.Context()).Error(err)
		writeError(rw, err.Error(), http.StatusInternalServerError)
	}
}

func (h Handler) getUDPRouter(rw http.ResponseWriter, request *http.Request) {
	routerID := mux.Vars(request)["routerID"]

	rw.Header().Set("Content-Type", "application/json")

	router, ok := h.runtimeConfiguration.UDPRouters[routerID]
	if !ok {
		writeError(rw, fmt.Sprintf("router not found: %s", routerID), http.StatusNotFound)
		return
	}

	result := newUDPRouterRepresentation(routerID, router)

	err := json.NewEncoder(rw).Encode(result)
	if err != nil {
		log.FromContext(request.Context()).Error(err)
		writeError(rw, err.Error(), http.StatusInternalServerError)
	}
}

func (h Handler) getUDPServices(rw http.ResponseWriter, request *http.Request) {
	results := make([]udpServiceRepresentation, 0, len(h.runtimeConfiguration.UDPServices))

	criterion := newSearchCriterion(request.URL.Query())

	for name, si := range h.runtimeConfiguration.UDPServices {
		if keepUDPService(name, si, criterion) {
			results = append(results, newUDPServiceRepresentation(name, si))
		}
	}

	sort.Slice(results, func(i, j int) bool {
		return results[i].Name < results[j].Name
	})

	rw.Header().Set("Content-Type", "application/json")

	pageInfo, err := pagination(request, len(results))
	if err != nil {
		writeError(rw, err.Error(), http.StatusBadRequest)
		return
	}

	rw.Header().Set(nextPageHeader, strconv.Itoa(pageInfo.nextPage))

	err = json.NewEncoder(rw).Encode(results[pageInfo.startIndex:pageInfo.endIndex])
	if err != nil {
		log.FromContext(request.Context()).Error(err)
		writeError(rw, err.Error(), http.StatusInternalServerError)
	}
}

func (h Handler) getUDPService(rw http.ResponseWriter, request *http.Request) {
	serviceID := mux.Vars(request)["serviceID"]

	rw.Header().Set("Content-Type", "application/json")

	service, ok := h.runtimeConfiguration.UDPServices[serviceID]
	if !ok {
		writeError(rw, fmt.Sprintf("service not found: %s", serviceID), http.StatusNotFound)
		return
	}

	result := newUDPServiceRepresentation(serviceID, service)

	err := json.NewEncoder(rw).Encode(result)
	if err != nil {
		log.FromContext(request.Context()).Error(err)
		writeError(rw, err.Error(), http.StatusInternalServerError)
	}
}

func keepUDPRouter(name string, item *runtime.UDPRouterInfo, criterion *searchCriterion) bool {
	if criterion == nil {
		return true
	}

	return criterion.withStatus(item.Status) && criterion.searchIn(name)
}

func keepUDPService(name string, item *runtime.UDPServiceInfo, criterion *searchCriterion) bool {
	if criterion == nil {
		return true
	}

	return criterion.withStatus(item.Status) && criterion.searchIn(name)
}


text:
var createKey = require('private-parts').createKey;

/**
 * Store the associations between constructors and their classes.
 */
var constructorToClassMap = new WeakMap();

/**
 * Store the associations between protected prototypes and their public
 * prototype counterparts.
 */
var protectToPrototypeMap = new WeakMap();

/**
 * A Class.
 * @constructor
 * @param {string} name An optional function name given to the produced
 *   constructor. This can be useful for debugging purposes.
 * @param {Function} definition An optional function used to define the new
 *   constructor.
 * @param {Class} parent An optional parent Class instance to extend from.
 *   This parameter is only used internally.
 */
function Class(name, definition, parent) {

  // Argument shifting.
  if (typeof name == 'function') {
    parent = definition;
    definition = name;
    name = null;
  }
  this.definition = definition;
  this.parent = parent;

  // Create the constructor, add some methods to it, and store the association.
  this.Ctor = createConstructor(name);
  this.Ctor.subclass = subclass;
  this.Ctor.final = final;
  constructorToClassMap.set(this.Ctor, this);

  this._setupInheritance();
  this._storeSecrets();
  this._makeAccessors();
}

/**
 * Setup the protected and private keys and method objects. Then invoke the
 * definition with those values. Finally, return the constructor publicly.
 * @return {Function} The generated constructor.
 */
Class.prototype.construct = function() {
  if (typeof this.definition == 'function') {
    this.definition.call(
      this.Ctor,
      this.Ctor.prototype,
      this.protectedKey,
      this.protectedMethods,
      this.privateKey,
      this.privateMethods
    );
  }
  return this.Ctor;
};

/**
 * Link this class to its parent and this class's constructor to its
 * parent class's constuctor.
 */
Class.prototype._setupInheritance = function() {
  if (this.parent) {
    // Add a node-style `super_` property. This is different from above
    // but used in case existing node code expects it to be there.
    this.Ctor.super_ = this.parent.Ctor;

    // Set up the prototype chain. Store a reference the the parent constructor
    // on the prototype for easier access than the node-style `Ctor.super_`.
    this.Ctor.prototype = Object.create(this.parent.Ctor.prototype, {
      constructor: { value: this.Ctor },
      super: { value: this.parent.Ctor.prototype }
    });
  }
};

/**
 * Create the private and protect keys and methods objects.
 */
Class.prototype._storeSecrets = function() {
  // Setup the protected key and method object.
  if (this.parent) {
    this.protectedKey = this.parent.protectedKey;
    this.protectedMethods = Object.create(this.parent.protectedMethods, {
      super: { value: this.parent.protectedMethods }
    });
  } else {
    this.protectedMethods = {};
    this.protectedKey = createKey(protectedFactory);
  }
  // Associate these class's protected methods with its public prototype.
  protectToPrototypeMap.set(this.Ctor.prototype, this.protectedMethods);

  // Set up the private key and method object.
  this.privateMethods = {};
  this.privateKey = createKey(this.privateMethods);
};

/**
 * Add getter, setter, and accessor functions to the constructor prototype.
 */
Class.prototype._makeAccessors = function() {
  var Ctor = this.Ctor;
  var _ = this.protectedKey;

  Object.defineProperties(Ctor, {
    addGetters: {
      value: function(props) {
        if (!Array.isArray(props)) props = [].slice.call(arguments);
        props.forEach(function(prop) {
          Ctor.prototype['get' + capitalize(prop)] = function() {
            return _(this)[prop];
          };
        });
      }
    },
    addSetters: {
      value: function(props) {
        if (!Array.isArray(props)) props = [].slice.call(arguments);
        props.forEach(function(prop) {
          Ctor.prototype['set' + capitalize(prop)] = function(value) {
            _(this)[prop] = value;
          };
        });
      }
    },
    addAccessors: {
      value: function() {
        Ctor.addGetters.apply(Ctor, arguments);
        Ctor.addSetters.apply(Ctor, arguments);
      }
    }
  });

};

/**
 * Subclass a constructor.
 * Note: This function gets assigned to new constructor instances, so when
 * it is invoked, its `this` context will be the calling constructor. When
 * subclassing, that means `this` is the parent constructor.
 * @param {Function} definition Any function that could be passed to the Class
 *   constructor.
 * @return {Function} A new constuctor that is a subclass of the invoking
 *   consturctor.
 */
function subclass(name, definition) {
  // Argument shifting.
  if (typeof name == 'function') {
    definition = name;
    name = null;
  }
  var parent = constructorToClassMap.get(this);
  if (parent.final) {
    throw new Error('Cannot subclass constructors marked final.');
  }

  return new Class(name, definition, parent).construct();
}

/**
 * Prevent a constructor from being subclassed.
 */
function final() {
  var cls = constructorToClassMap.get(this);
  cls.final = true;
}

/**
 * A creator function that can be passed to the Private Parts `createKey`
 * method. If accepts an object and return a new object whose prototype is
 * the protected counterpart to the prototype of the passed object.
 * @param {Object} instance An instance of a constructor created with Class.
 * @return {Object} The protected methods object.
 */
function protectedFactory(instance) {
  var publicPrototype = Object.getPrototypeOf(instance);
  var protectedPrototype = protectToPrototypeMap.get(publicPrototype);
  if (!protectedPrototype) {
    throw new Error('The protected key function only accepts instances '
      + 'of objects created using Mozart constructors.'
    );
  }
  return Object.create(protectedPrototype);
}

/**
 * Create a constructor function with an optional name (the name makes it
 * easier to debug in the developer tools). The returned constructor, when
 * called, will attempt to invoke an `init` function (if it exists) with any
 * arguments passed to it.
 * @param {string} name The optional name of the constructor.
 * @return {Function} The newly created constructor function.
 */
function createConstructor(name) {
  if (!name) name = '';
  var factory = new Function('return function ' + name + '() {\n'
    + 'if (typeof this.init == \'function\')'
    + 'this.init.apply(this, arguments) }');
  return factory();
}

function capitalize(string) {
  return string.substr(0, 1).toUpperCase() + string.substr(1);
}

module.exports = Class;


text:
'use strict';

var path = require('path');
var fs = require('fs-extra');
var assert = require('yeoman-generator').assert;
var helpers = require('yeoman-generator').test;
var sinon = require('sinon');

describe('ngbp-module:module', function () {

  var runGen;

  beforeEach(function () {
    runGen = helpers
      .run(path.join(__dirname, '../module'))
      .inDir(path.join(__dirname, './temp'))
      .withArguments(['newModule'])
      .withOptions({ 'skip-install': true })
      .withPrompts({
        modules: ['templates', 'uiRouter']
      })
      .withGenerators([[helpers.createDummyGenerator(), 'mocha:app']])
      .on('ready', function () {
        fs.ensureDirSync('./test/temp/src/app');
        fs.ensureDirSync('./test/temp/src/less');
        fs.writeFileSync('./test/temp/src/less/main.less', '@include("test.less");\n');
      });
  });

  it('creates files', function (done) {
    runGen.on('ready', function () {
        fs.writeFileSync('./test/temp/src/app/app.js', "angular.module('test', ['test.existingModule'])");
      })
      .on('end', function () {
        assert.file([
          'test/temp/src/app/app.js',
          'test/temp/src/app/newModule/newModule.module.js',
          'test/temp/src/app/newModule/controllers/newModule.controllers.js',
          'test/temp/src/app/newModule/directives/newModule.directives.js',
          'test/temp/src/app/newModule/filters/newModule.filters.js',
          'test/temp/src/app/newModule/services/newModule.services.js',
          'test/temp/src/app/newModule/unit/newModule.spec.js',
          'test/temp/src/app/newModule/e2e/newModule.e2e.js'
        ]);
        done();
      });
  });

  it('updates app.js', function (done) {
    runGen.on('ready', function () {
        fs.writeFileSync('./test/temp/src/app/app.js', "angular.module('test', ['test.existingModule'])");
      })
      .on('end', function () {
        assert.fileContent('test/temp/src/app/app.js', "angular.module('test', [\n    'test.existingModule',\n    'test.newModule'\n])");
        done();
      });
  });

  it('does not update app.js if expected syntax cannot be found', function (done) {
    runGen.on('ready', function () {
      fs.writeFileSync('./test/temp/src/app/app.js', "angular.module('test')");
    })
    .on('end', function () {
      assert.fileContent('test/temp/src/app/app.js', "angular.module('test')");
      done();
    });
  });

  it('gets projectName from app.js if it does not exist', function (done) {
    runGen.on('ready', function () {
      this.generator.projectName = null;
      this.generator.config.set = sinon.stub().returns(function () {});
      fs.writeFileSync('./test/temp/src/app/app.js', "angular.module('other', ['test.existingModule'])");
    })
    .on('end', function () {
      assert.fileContent('test/temp/src/app/app.js', "angular.module('other', [\n    'test.existingModule',\n    'other.newModule'\n])");
      done();
    });
  });

});


text:
package com.oculusinfo.geometry.cartesian;

import com.oculusinfo.math.linearalgebra.Vector;

import java.util.ArrayList;
import java.util.List;

public class Spline {
    private final boolean      _periodic;
    private int          _n;
    private final List<Vector> _points;
    private final List<Double> _times;

    public Spline (boolean periodic) {
        _periodic = periodic;
        _points = new ArrayList<>();
        _times = new ArrayList<>();
        _n = 0;
    }

    // TODO:
    // (1) Create a spline through a given set of points (requires tridiagonal matrix)
    //     http://www.particleincell.com/2012/bezier-splines/
    // (2) Implement distance algorithm for splines
    // (3) Implement mean algorithm for splines

    /**
     * Add a new control point into the spline, in the proper order.
     *
     * @param time
     *            The time at which the point occurs
     * @param point
     *            The point to add
     */
    public void addPoint (double time, Vector point) {
        // Figure out at what index to add the time
        for (int i = 0; i < _n; ++i) {
            if (time < _times.get(i)) {
                // Add before point i.
                _points.add(i, point);
                _times.add(i, time);
                ++_n;
                return;
            }
        }

        // New last point
        _points.add(point);
        _times.add(time);
        ++_n;
    }

    /*
     * This method only exists to use the _periodic field, which is here for
     * future expansion, and isn't actually used yet.
     */
    protected boolean isPeriodic () {
        return _periodic;
    }

    /*
     * Get t_i for a given i
     */
    private double t (int i) {
        if (i < 0)
            throw new IndexOutOfBoundsException("Can't get t_i for i<0");
        if (i >= _times.size())
            throw new IndexOutOfBoundsException("Can't get t_i for i>n (i="+i+", n="+_n+ ')');

        double t0 = _times.get(0);
        double tn = _times.get(_times.size()-1);
        double ti = _times.get(i);
        return (ti-t0)/(tn-t0);
    }

    /*
     * Get the i at which t lies between t_floor(i) and t_ceil(i)
     */
    protected double i (double t) {
        if (t < 0)
            throw new IndexOutOfBoundsException("Attempt to get i for t<0");
        if (t >= 1)
            throw new IndexOutOfBoundsException("Attempt to get i for t>1");
        double lastti = 0;
        for (int i=0; i<_times.size(); ++i) {
            double ti = t(i);
            if (ti > t) {
                return i + (t-lastti)/(ti-lastti);
            }
        }
        // should never get here
        throw new RuntimeException("Weird i-calculation error in spline calculation - no valid i found");
    }
}


text:
class Profile;

namespace extensions {
namespace browsertest_util {

// Waits until |script| calls "window.domAutomationController.send(result)",
// where |result| is a string, and returns |result|. Fails the test and returns
// an empty string if |extension_id| isn't installed in |profile| or doesn't
// have a background page, or if executing the script fails.
std::string ExecuteScriptInBackgroundPage(Profile* profile,
                                          const std::string& extension_id,
                                          const std::string& script);

// Same as ExecuteScriptInBackgroundPage, but doesn't wait for the script
// to return a result. Fails the test and returns false if |extension_id|
// isn't installed in |profile| or doesn't have a background page, or if
// executing the script fails.
bool ExecuteScriptInBackgroundPageNoWait(Profile* profile,
                                         const std::string& extension_id,
                                         const std::string& script);

// On chromeos, the extension cache directory must be initialized before
// extensions can be installed in some situations (e.g. policy force installs
// via update urls). The chromeos device setup scripts take care of this in
// actual production devices, but some tests need to do it manually.
void CreateAndInitializeLocalCache();

}  // namespace browsertest_util
}  // namespace extensions

#endif  // CHROME_BROWSER_EXTENSIONS_BROWSERTEST_UTIL_H_


text:
<?php

use yii\db\Schema;
use yii\db\Migration;

class m150208_151701_create_post_table extends Migration
{
    public function up()
    {
        $this->createTable('post', [
            'id' => 'pk',
            'title' => Schema::TYPE_STRING . ' NOT NULL',
            'content' => Schema::TYPE_TEXT . ' NOT NULL',
            'active' => Schema::TYPE_BOOLEAN. " NOT NULL DEFAULT '1'",
            'featured' => Schema::TYPE_BOOLEAN. " NOT NULL DEFAULT '0'",
            'category_id' => Schema::TYPE_INTEGER . ' NOT NULL',
            'created_at' => Schema::TYPE_INTEGER . ' NOT NULL',
            'created_by' => Schema::TYPE_INTEGER . ' NOT NULL',
        ]);
    }

    public function down()
    {
        $this->dropTable('post');
    }

}


text:
/**
 * Created by Adrien on 30/06/2017.
 */
import React from 'react';
import {GridList, GridTile} from 'material-ui/GridList';
import IconButton from 'material-ui/IconButton';
import Subheader from 'material-ui/Subheader';
import StarBorder from 'material-ui/svg-icons/toggle/star-border';
import StartupCard from './StartupCard';
import fetch from 'isomorphic-unfetch'

const styles = {
    root: {
        display: 'flex',
        flexWrap: 'wrap',
        justifyContent: 'space-around',
    },
    gridList: {
        width: '100%',
        height: 'auto',
        overflowY: 'auto',
    }
};

/**
 * A simple example of a scrollable `GridList` containing a [Subheader](/#/components/subheader).
 */

const HighlightGridList = (props) => (

    <div style={styles.root}>

        {props.highlights.map((high) => (
<GridList
cols={2}
cellHeight="auto"
style={styles.gridList}
key={high.periode}>
<Subheader>{high.periode}</Subheader>
{high.startups.map((tile) => (
<GridTile
cols={tile.size}
rows={tile.size}
key={tile.img}>
<StartupCard
title={tile.title}
pretty={tile.pretty}
author={tile.author}
avatar={tile.avatar}
subtitle={tile.subtitle}
description={tile.description}
website={tile.website}
youtubeLink={tile.youtubeLink}
_id={tile._id}
img={tile.img}
/>
</GridTile>
))}
</GridList>
))}

    </div>
);

HighlightGridList.getInitialProps = async function (context) {
    const res = await fetch('/api/s/all')
    const data = await res.json()

    console.log(`Show data fetched. Count: ${data.length}`)

    return {
        shows: data
    }
}

export default HighlightGridList;


text:
using Glyssen.Shared.Bundle;
using SIL.DblBundle.Text;
using SIL.WritingSystems;

namespace GlyssenEngine.Bundle
{
	public class GlyssenBundle : TextBundle<GlyssenDblTextMetadata, GlyssenDblMetadataLanguage>
	{
		static GlyssenBundle()
		{
			DefaultLanguageIsoCode = WellKnownSubtags.UnlistedLanguage;
		}

		public GlyssenBundle(string pathToZippedBundle) : base(pathToZippedBundle)
		{
			Metadata.OriginalReleaseBundlePath = BundlePath;
			Metadata.FontFamily = Stylesheet.FontFamily;
			Metadata.FontSizeInPoints = Stylesheet.FontSizeInPoints;
			if (string.IsNullOrEmpty(Metadata.Language.Iso))
				Metadata.Language.Iso = LanguageIso;
		}

		public string LanguageAsString { get { return Metadata.Language.ToString(); } }
	}
}


text:
// Copyright 2016 Drew Short <drew@sothr.com>.
//
// Licensed under the MIT license<LICENSE-MIT or http://opensource.org/licenses/MIT>.
// This file may not be copied, modified, or distributed except according to those terms.

extern crate flate2;
extern crate image;
extern crate num;
extern crate sha1;

use std::default::Default;
use std::fs::{create_dir_all, File, remove_dir_all};
use std::io::{Error, ErrorKind, Read, Write};
use std::option::Option;
use std::path::Path;
use std::result::Result;
use std::str::FromStr;

use super::rustc_serialize::json;

use self::flate2::Compression;
use self::flate2::read::ZlibDecoder;
use self::flate2::write::ZlibEncoder;
use self::image::DynamicImage;
use self::sha1::Sha1;

pub const DEFAULT_CACHE_DIR: &'static str = "./.hash_cache";
const CACHED_IMAGE_EXT: &'static str = "png";
const CACHED_MATRIX_EXT: &'static str = "dft";
// Caching version information
const CACHE_VERSION: u32 = 1;
const CACHE_METADATA_FILE: &'static str = "cache.meta";

#[derive(RustcDecodable, RustcEncodable)]
struct CacheMetadata {
    cache_version: u32,
}

impl Default for CacheMetadata {
    fn default() -> CacheMetadata {
        CacheMetadata {
            cache_version: CACHE_VERSION,
        }
    }
}

impl PartialEq<CacheMetadata> for CacheMetadata {
    fn eq(&self, other: &CacheMetadata) -> bool {
        self.cache_version == other.cache_version
    }

    fn ne(&self, other: &CacheMetadata) -> bool {
        !self.eq(&other)
    }
}

/**
* Structure to hold implementation of the cache
*/
#[repr(C)]
pub struct Cache {
    pub cache_dir: String,
    pub use_cache: bool,
}

impl Default for Cache {
    fn default() -> Cache {
        Cache {
            cache_dir: String::from(DEFAULT_CACHE_DIR),
            use_cache: true,
        }
    }
}

impl Cache {
    /**
     * Create the required directories for the cache
     */
    pub fn init(&self) -> Result<(), Error> {
        match create_dir_all(&self.cache_dir) {
            Ok(_) => {
                let metadata_path_str = format!("{}/{}", self.cache_dir, CACHE_METADATA_FILE);
                let metadata_path = Path::new(&metadata_path_str);
                let current_metadata: CacheMetadata = Default::default();
                match File::open(&metadata_path) {
                    Ok(mut file) => {
                        // Metadata file exists, compare them
                        let mut loaded_metadata_string = String::new();
                        match file.read_to_string(&mut loaded_metadata_string) {
                            Ok(_) => {
                                let loaded_metadata: CacheMetadata =
                                    match json::decode(&loaded_metadata_string) {
                                        Ok(data) => data,
                                        Err(_) => CacheMetadata { cache_version: 0 },
                                    };

                                // If they match, continue
                                if current_metadata != loaded_metadata {
                                    // If they don't wipe the cache to start new
                                    match remove_dir_all(&self.cache_dir) {
                                        Ok(_) => match create_dir_all(&self.cache_dir) {
                                            Ok(_) => (),
                                            Err(e) => println!("Error: {}", e),
                                        },
                                        Err(e) => println!("Error: {}", e),
                                    };
                                };
                            }
                            Err(e) => println!("Error: {}", e),
                        };
                    }
                    // Metadata file doesn't exist, do nothing assume all is well,
                    // create new metadata file
                    Err(_) => {}
                };
                let encoded_cache_metadata = json::encode(&current_metadata).unwrap();
                match File::create(&metadata_path) {
                    Ok(mut file) => {
                        let _ = file.write(&encoded_cache_metadata.as_bytes());
                        Ok(())
                    }
                    Err(e) => Err(e),
                }
            }
            Err(e) => Err(e),
        }
    }

    /**
     * Clean the cache directory completely
     */
    pub fn clean(&self) -> Result<(), Error> {
        remove_dir_all(&self.cache_dir)
    }

    /**
     * Get the hash of the desired file and return it as a hex string
     */
    pub fn get_file_hash(&self, path: &Path) -> Result<String, Error> {
        let mut source = File::open(&path)?;
        let mut buf: Vec<u8> = Vec::new();
        source.read_to_end(&mut buf)?;
        let mut sha1 = Sha1::new();
        sha1.update(&buf);
        let digest = sha1.digest();
        // Return the hex result of the hash
        Ok(format!("{}", digest))
    }

    /**
     * Put an image buffer in the cache
     */
    pub fn put_image_in_cache(
        &self,
        path: &Path,
        size: u32,
        image: &DynamicImage,
    ) -> Result<bool, Error> {
        let hash = self.get_file_hash(&path);
        match hash {
            Ok(sha1) => {
                let cache_path_str = format!(
                    "{}/image/{}x{}/{}/{}.{}",
                    self.cache_dir,
                    size,
                    size,
                    &sha1[..10],
                    sha1,
                    CACHED_IMAGE_EXT
                );
                let cache_dir_str =
                    format!("{}/image/{}x{}/{}", self.cache_dir, size, size, &sha1[..10]);
                println!("Test");
                println!("{}", DEFAULT_CACHE_DIR);
                println!("{}", &self.cache_dir);
                //                println!("Saving: {}", &cache_path_str);
                match create_dir_all(&cache_dir_str) {
                    Ok(_) => {
                        let file_path = Path::new(&cache_path_str);
                        match File::create(file_path) {
                            Ok(_) => {
                                // Save the file into the cache
                                match image.save(file_path) {
                                    Ok(_) => {}
                                    Err(e) => {
                                        println!("Error: {}", e);
                                        return Err(Error::new(ErrorKind::Other, e));
                                    }
                                }
                            }
                            Err(e) => {
                                println!("Unable to create file {:?}", file_path);
                                return Err(e);
                            }
                        }
                    }
                    Err(e) => {
                        println!("Unable to create directory {:?}", &cache_dir_str);
                        return Err(e);
                    }
                }
            }
            Err(e) => {
                println!("Error: {}", e);
                return Err(e);
            }
        }
        Ok(true)
    }

    /**
     * Get an image buffer out of the cache
     */
    pub fn get_image_from_cache(&self, path: &Path, size: u32) -> Option<DynamicImage> {
        if self.use_cache {
            let hash = self.get_file_hash(&path);
            match hash {
                Ok(sha1) => {
                    // Check if the file exists in the cache
                    let cache_path_str = format!(
                        "{}/image/{}x{}/{}/{}.{}",
                        self.cache_dir,
                        size,
                        size,
                        &sha1[..10],
                        sha1,
                        CACHED_IMAGE_EXT
                    );
                    let cached_path = Path::new(&cache_path_str);
                    // Try to open, if it does, then we can read the image in
                    match File::open(&cached_path) {
                        Ok(_) => {
                            let image = image::open(&cached_path).unwrap();
                            Some(image)
                        }
                        // Don't really care here, it just means an existing cached
                        // file doesn't exist, or can't be read.
                        Err(_) => None,
                    }
                }
                Err(e) => {
                    println!("Error: {}", e);
                    None
                }
            }
        } else {
            None
        }
    }

    /**
     * Expects a slice of slices that represents lines in the file
     */
    pub fn put_matrix_in_cache(
        &self,
        path: &Path,
        size: u32,
        file_contents: &Vec<Vec<f64>>,
    ) -> Result<bool, Error> {
        let hash = self.get_file_hash(&path);
        match hash {
            Ok(sha1) => {
                let cache_path_str = format!(
                    "{}/matrix/{}x{}/{}/{}.{}",
                    self.cache_dir,
                    size,
                    size,
                    &sha1[..10],
                    sha1,
                    CACHED_MATRIX_EXT
                );
                let cache_dir_str = format!(
                    "{}/matrix/{}x{}/{}",
                    self.cache_dir,
                    size,
                    size,
                    &sha1[..10]
                );
                match create_dir_all(cache_dir_str) {
                    Ok(_) => {
                        let cached_path = Path::new(&cache_path_str);
                        // Save the file into the cache
                        match File::create(&cached_path) {
                            Ok(mut file) => {
                                let mut compressor =
                                    ZlibEncoder::new(Vec::new(), Compression::default());
                                for row in file_contents {
                                    let mut row_str =
                                        row.iter().fold(String::new(), |acc, &item| {
                                            acc + &format!("{},", item)
                                        });
                                    // remove the last comma
                                    let desire_len = row_str.len() - 1;
                                    row_str.truncate(desire_len);
                                    row_str.push_str("\n");
                                    compressor.write(&row_str.into_bytes())?;
                                }
                                let compressed_matrix = match compressor.finish() {
                                    Ok(data) => data,
                                    Err(e) => {
                                        println!("Unable to compress matrix data: {}", e);
                                        return Err(e);
                                    }
                                };
                                file.write(&compressed_matrix)?;
                                file.flush()?;
                            }
                            Err(e) => {
                                return Err(e);
                            }
                        }
                    }
                    Err(e) => println!("Error: {}", e),
                }
            }
            Err(e) => {
                println!("Error: {}", e);
                return Err(e);
            }
        }
        Ok(true)
    }

    /**
     * Get a matrix out of the cache
     */
    pub fn get_matrix_from_cache(&self, path: &Path, size: u32) -> Option<Vec<Vec<f64>>> {
        if self.use_cache {
            let hash = self.get_file_hash(&path);
            match hash {
                Ok(sha1) => {
                    // Check if the file exists in the cache
                    let cache_path_str = format!(
                        "{}/matrix/{}x{}/{}/{}.{}",
                        self.cache_dir,
                        size,
                        size,
                        &sha1[..10],
                        sha1,
                        CACHED_MATRIX_EXT
                    );
                    let cached_path = Path::new(&cache_path_str);
                    // Try to open, if it does, then we can read the image in
                    match File::open(&cached_path) {
                        Ok(file) => {
                            let mut decoder = ZlibDecoder::new(&file);
                            let mut matrix_data_str = String::new();
                            match decoder.read_to_string(&mut matrix_data_str) {
                                Ok(_) => {}
                                Err(e) => {
                                    println!("Unable to decompress matrix: {}", e);
                                    return None;
                                }
                            };
                            // convert the matrix
                            let matrix: Vec<Vec<f64>> = matrix_data_str
                                .trim()
                                .split("\n")
                                .map(|line| {
                                    line.split(",").map(|f| f64::from_str(f).unwrap()).collect()
                                })
                                .collect();

                            Some(matrix)
                        }
                        // Don't really care here, it just means an existing cached
                        // file doesn't exist, or can't be read.
                        Err(_) => None,
                    }
                }
                Err(e) => {
                    println!("Error: {}", e);
                    None
                }
            }
        } else {
            None
        }
    }
}

#[cfg(test)]
mod tests {
    use std::path::Path;

    use cache::Cache;

    #[test]
    fn test_get_file_hash() {
        let target = "test_images/sample_01_large.jpg";
        let target_path = Path::new(target);
        let cache: Cache = Default::default();
        let hash = cache.get_file_hash(&target_path);
        match hash {
            Ok(v) => {
                println!("Hash: {}", v);
                assert_eq!(v, String::from("4beb6f2d852b75a313863916a1803ebad13a3196"));
            }
            Err(e) => {
                println!("Error: {:?}", e);
                assert!(false);
            }
        }
    }
}


text:
require 'active_support/concern'

module Filter

  # Provides grouping, sorting, paging, 'and', and 'or' for composing queries.
  module Core
    extend ActiveSupport::Concern
    extend Validate

    private

    # Get the ActiveRecord::Relation that represents zero records.
    # @param [ActiveRecord::Base] model
    # @return [ActiveRecord::Relation] query that will get zero records
    def relation_none(model)
      validate_model(model)
      model.none
    end

    # Get the ActiveRecord::Relation that represents all records.
    # @param [ActiveRecord::Base] model
    # @return [ActiveRecord::Relation] query that will get all records
    def relation_all(model)
      validate_model(model)
      model.all
    end

    # Get the Arel::Table for this model.
    # @param [ActiveRecord::Base] model
    # @return [Arel::Table] arel table
    def relation_table(model)
      validate_model(model)
      model.arel_table
    end

    # Join conditions using or.
    # @param [Arel::Nodes::Node] first_condition
    # @param [Arel::Nodes::Node] second_condition
    # @return [Arel::Nodes::Node] condition
    def compose_or(first_condition, second_condition)
      validate_condition(first_condition)
      validate_condition(second_condition)
      first_condition.or(second_condition)
    end

    # Join conditions using and.
    # @param [Arel::Nodes::Node] first_condition
    # @param [Arel::Nodes::Node] second_condition
    # @return [Arel::Nodes::Node] condition
    def compose_and(first_condition, second_condition)
      validate_condition(first_condition)
      validate_condition(second_condition)
      first_condition.and(second_condition)
    end

    # Join conditions using not.
    # @param [Arel::Nodes::Node] condition
    # @return [Arel::Nodes::Node] condition
    def compose_not(condition)
      validate_condition(condition)
      condition.not
    end
  end
end


text:
*{ margin:0; padding:0;font-family:"micro Yahei", "微软雅黑",sans-serif}
ul{list-style:none}
img{ border:0; vertical-align:top}
a { text-decoration:none; color:#000;font-size:12px}

.header { height:80px; overflow:hidden}
.w960 {width:960px; margin:0 auto}

/* logo */
.logo { float:left;height:80px}
.logo span {display:inline-block;height:34px;margin-right:17px; margin-top:23px;background:url("../img/wy-header.png") no-repeat}
.logo-shape { width:54px}
.logo .logo-text { width:122px; background-position:-54px 0}
.logo .logo-desc { width:145px; background-position:-180px 0}

/* 导航 */
.nav { float:right; height:80px}
.nav li{ float:left; height:80px; line-height:80px;font-size:0; text-align:center; display:inline}
.nav a{ display:inline-block;font-size:16px;padding:0 20px;height:76px; border-bottom:4px solid #fff; color:#8d8d8d}
.nav .active { border-bottom-color:#3091f2;font-weight:700}
.web-wy { float:right;position:relative;height:40px; line-height:40px; width:110px;border-radius:3px; background:#3091f2;
    text-indent:25px;color:#fff; margin-top:20px; margin-left:42px}
.right-tri { position:absolute; height:0; border:5px solid #3091f2; border-left:5px solid #fff; left:76px; top:16px}

/* 底部版权 */
#footer { height:134px; background:#e6e6e6}
.footer-content { height:54px; width:650px; margin:0 auto;padding:40px 155px}
.copyright { position:absolute; margin-left:40px;display:inline-block;font-size:12px; line-height:18px;color:#999}
.copyright a {color:#999}