text:
import React from 'react';
import {
  Editor as OrigEditor,
  IEditSession,
  Position,
  TextMode as OrigTextMode,
} from 'brace';
import AceEditor, { IAceEditorProps } from 'react-ace';
import AsyncEsmComponent, {
  PlaceholderProps,
} from 'src/components/AsyncEsmComponent';

export interface AceCompleterKeywordData {
  name: string;
  value: string;
  score: number;
  meta: string;
}

export type TextMode = OrigTextMode & { $id: string };

export interface AceCompleter {
  insertMatch: (
    data?: Editor | { value: string } | string,
    options?: AceCompleterKeywordData,
  ) => void;
}

export type Editor = OrigEditor & {
  completer: AceCompleter;
  completers: AceCompleter[];
};

export interface AceCompleterKeyword extends AceCompleterKeywordData {
  completer?: AceCompleter;
}

/**
 * Async loaders to import brace modules. Must manually create call `import(...)`
 * promises because webpack can only analyze asycn imports statically.
 */
const aceModuleLoaders = {
  'mode/sql': () => import('brace/mode/sql'),
  'mode/markdown': () => import('brace/mode/markdown'),
  'mode/css': () => import('brace/mode/css'),
  'mode/json': () => import('brace/mode/json'),
  'mode/yaml': () => import('brace/mode/yaml'),
  'mode/html': () => import('brace/mode/html'),
  'mode/javascript': () => import('brace/mode/javascript'),
  'theme/textmate': () => import('brace/theme/textmate'),
  'theme/github': () => import('brace/theme/github'),
  'ext/language_tools': () => import('brace/ext/language_tools'),
};

export type AceModule = keyof typeof aceModuleLoaders;

export type AsyncAceEditorProps = IAceEditorProps & {
  keywords?: AceCompleterKeyword[];
};

export type AceEditorMode = 'sql';
export type AceEditorTheme = 'textmate' | 'github';
export type AsyncAceEditorOptions = {
  defaultMode?: AceEditorMode;
  defaultTheme?: AceEditorTheme;
  defaultTabSize?: number;
  placeholder?: React.ComponentType<
    PlaceholderProps & Partial<IAceEditorProps>
  > | null;
};

/**
 * Get an async AceEditor with automatical loading of specified ace modules.
 */
export default function AsyncAceEditor(
  aceModules: AceModule[],
  {
    defaultMode,
    defaultTheme,
    defaultTabSize = 2,
    placeholder,
  }: AsyncAceEditorOptions = {},
) {
  return AsyncEsmComponent(async () => {
    const { default: ace } = await import('brace');
    const { default: ReactAceEditor } = await import('react-ace');

    await Promise.all(aceModules.map(x => aceModuleLoaders[x]()));

    const inferredMode =
      defaultMode ||
      aceModules.find(x => x.startsWith('mode/'))?.replace('mode/', '');
    const inferredTheme =
      defaultTheme ||
      aceModules.find(x => x.startsWith('theme/'))?.replace('theme/', '');

    return React.forwardRef<AceEditor, AsyncAceEditorProps>(
      function ExtendedAceEditor(
        {
          keywords,
          mode = inferredMode,
          theme = inferredTheme,
          tabSize = defaultTabSize,
          defaultValue = '',
          ...props
        },
        ref,
      ) {
        if (keywords) {
          const langTools = ace.acequire('ace/ext/language_tools');
          const completer = {
            getCompletions: (
              editor: AceEditor,
              session: IEditSession,
              pos: Position,
              prefix: string,
              callback: (error: null, wordList: object[]) => void,
            ) => {
              // If the prefix starts with a number, don't try to autocomplete
              if (!Number.isNaN(parseInt(prefix, 10))) {
                return;
              }
              if ((session.getMode() as TextMode).$id === `ace/mode/${mode}`) {
                callback(null, keywords);
              }
            },
          };
          langTools.setCompleters([completer]);
        }
        return (
          <ReactAceEditor
            ref={ref}
            mode={mode}
            theme={theme}
            tabSize={tabSize}
            defaultValue={defaultValue}
            {...props}
          />
        );
      },
    );
  }, placeholder);
}

export const SQLEditor = AsyncAceEditor([
  'mode/sql',
  'theme/github',
  'ext/language_tools',
]);

export const FullSQLEditor = AsyncAceEditor(
  ['mode/sql', 'theme/github', 'ext/language_tools'],
  {
    // a custom placeholder in SQL lab for less jumpy re-renders
    placeholder: () => {
      const gutterBackground = '#e8e8e8'; // from ace-github theme
      return (
        <div
          style={{
            height: '100%',
          }}
        >
          <div
            style={{ width: 41, height: '100%', background: gutterBackground }}
          />
          {/* make it possible to resize the placeholder */}
          <div className="ace_content" />
        </div>
      );
    },
  },
);

export const MarkdownEditor = AsyncAceEditor([
  'mode/markdown',
  'theme/textmate',
]);

export const TextAreaEditor = AsyncAceEditor([
  'mode/markdown',
  'mode/sql',
  'mode/json',
  'mode/html',
  'mode/javascript',
  'theme/textmate',
]);

export const CssEditor = AsyncAceEditor(['mode/css', 'theme/github']);

export const JsonEditor = AsyncAceEditor(['mode/json', 'theme/github']);

/**
 * JSON or Yaml config editor.
 */
export const ConfigEditor = AsyncAceEditor([
  'mode/json',
  'mode/yaml',
  'theme/github',
]);


text:
<?php

namespace Openroot\Bundle\ClientContextBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Openroot\Bundle\ClientContextBundle\Interfaces\ClientContextInterface;

/**
 * @ORM\Entity(repositoryClass="Openroot\Bundle\ClientContextBundle\Entity\Repository\ClientHttpContextRepository")
 * @ORM\Table(name="openroot_clientcontext_httpcontext", uniqueConstraints={
 *  @ORM\UniqueConstraint(name="context_idx", columns={"host", "port"})
 * })
 */
class ClientHttpContext implements ClientContextInterface
{
    /**
     * @var int
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var Client
     * @ORM\ManyToOne(targetEntity="Openroot\Bundle\ClientContextBundle\Entity\Client", cascade={"all"}, fetch="EAGER", inversedBy="httpContexts")
     */
    private $client;

    /**
     * @var bool
     * @ORM\Column(type="boolean", nullable=false, options={"default": 0})
     */
    private $main;

    /**
     * @var string
     * @ORM\Column(type="string", length=255, nullable=false)
     */
    private $host;

    /**
     * @var int
     * @ORM\Column(type="integer", nullable=false)
     */
    private $port;

    /**
     * Setup
     */
    public function __construct()
    {
        $this->main = false;
    }

    /**
     * @return int
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * @return boolean
     */
    public function isMain()
    {
        return (bool)$this->main;
    }

    /**
     * @param boolean $main
     */
    public function setMain($main)
    {
        $this->main = (bool)$main;
    }

    /**
     * @return Client
     */
    public function getClient()
    {
        return $this->client;
    }

    /**
     * @param Client $client
     */
    public function setClient(Client $client = null)
    {
        $this->client = $client;
    }

    /**
     * @return string
     */
    public function getHost()
    {
        return $this->host;
    }

    /**
     * @param string $host
     */
    public function setHost($host)
    {
        $this->host = $host;
    }

    /**
     * @return int
     */
    public function getPort()
    {
        return $this->port;
    }

    /**
     * @param int $port
     */
    public function setPort($port)
    {
        $this->port = $port;
    }
}

redpajama_set_name: RedPajamaGithub


text:
The New Relic Framework causes an application to be automatically configured to work with a bound [New Relic Service][].

    Detection Criterion	Existence of a single bound New Relic service.  The existence of an New Relic service defined by the VCAP_SERVICES payload containing a service name-version, name, label or tag with newrelic as a substring.

    Tags	<tt>new-relic-agent=<version></tt>

Tags are printed to standard output by the buildpack detect script

## User-Provided Service
When binding New Relic using a user-provided service, it must have a name or tag with newrelic in it.  The credential payload can contain the following entries:

| Name | Description
| ---- | -----------
| `licenseKey` | The license key to use when authenticating

## Configuration
For general information on configuring the buildpack, refer to [Configuration and Extension][].

The framework can be configured by modifying the [`config/newrelic.yml`][] file.  The framework uses the [`Repository` utility support][repositories] and so it supports the [version syntax][] defined there.

| Name | Description
| ---- | -----------
| `repository_root` | The URL of the New Relic repository index ([details][repositories]).
| `version` | The version of New Relic to use. Candidate versions can be found in [this listing][].

[Configuration and Extension]: ../README.md#Configuration-and-Extension
[`config/newrelic.yml`]: ../config/newrelic.yml
[New Relic Service]: https://newrelic.com
[repositories]: util-repositories.md
[this listing]: http://download.pivotal.io.s3.amazonaws.com/new-relic/index.yml
[version syntax]: util-repositories.md#version-syntax-and-ordering


text:
<!--
 ~ Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
 ~
 ~ WSO2 Inc. licenses this file to you 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.
 -->
<assembly>
    <formats>
        <format>zip</format>
    </formats>

    <includeBaseDirectory>false</includeBaseDirectory>
    <fileSets>
      <!-- Copying p2 profile and osgi bundles-->
        <fileSet>
            <directory>../p2-profile-generation/carbon-p2-profile/target/carbon-p2-profile</directory>
            <outputDirectory>wso2carbon-core-${project.version}/repository/components</outputDirectory>
            <excludes>
                <exclude>**/eclipse.ini</exclude>
                <exclude>**/*.lock</exclude>
                <exclude>**/.data</exclude>
                <exclude>**/.settings</exclude>
            </excludes>
        </fileSet>
    </fileSets>
</assembly>


text:
package de.berrnd.Time_Recording_Auto_Export_Tasker_Plugin;

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

public class DateHelper {

    public static Date addDays(Date date, int days) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.add(Calendar.DATE, days);
        return cal.getTime();
    }

    public static int getDatePart(Date date, int part) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        return cal.get(part);
    }

    public static String toIsoDateString(Date date) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        return dateFormat.format(date);
    }

    public static Date fromIsoDate(String isoDate) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

        Date date = new Date();
        try {
            date = dateFormat.parse(isoDate);
        } catch (ParseException ex) {
        }

        return date;
    }

    public static String toSystemLocaleString(Date date) {
        return DateFormat.getDateInstance().format(date);
    }

}


text:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <title>pymatgen package — pymatgen 2019.7.2 documentation</title>
    <link rel="stylesheet" href="_static/basic.css" type="text/css" />
    <link rel="stylesheet" href="_static/pygments.css" type="text/css" />

    <link rel="shortcut icon" href="_static/favicon.ico"/>
    <link rel="index" title="Index" href="genindex.html" />
    <link rel="search" title="Search" href="search.html" />

Navigation

          index

          modules |

pymatgen 2019.7.2 documentation »

pymatgen package¶

Subpackages¶

pymatgen.alchemy package

Subpackages

Submodules

pymatgen.alchemy.filters module

pymatgen.alchemy.materials module

pymatgen.alchemy.transmuters module

Module contents

pymatgen.analysis package

Subpackages

pymatgen.analysis.chemenv package

Subpackages

pymatgen.analysis.chemenv.coordination_environments package

Subpackages

pymatgen.analysis.chemenv.coordination_environments.coordination_geometries_files package

Module contents

pymatgen.analysis.chemenv.coordination_environments.strategy_files package

Module contents

Submodules

pymatgen.analysis.chemenv.coordination_environments.chemenv_strategies module

pymatgen.analysis.chemenv.coordination_environments.coordination_geometries module

pymatgen.analysis.chemenv.coordination_environments.coordination_geometry_finder module

pymatgen.analysis.chemenv.coordination_environments.structure_environments module

pymatgen.analysis.chemenv.coordination_environments.voronoi module

Module contents

pymatgen.analysis.chemenv.utils package

Subpackages

Submodules

pymatgen.analysis.chemenv.utils.chemenv_config module

pymatgen.analysis.chemenv.utils.chemenv_errors module

pymatgen.analysis.chemenv.utils.coordination_geometry_utils module

pymatgen.analysis.chemenv.utils.defs_utils module

pymatgen.analysis.chemenv.utils.func_utils module

pymatgen.analysis.chemenv.utils.math_utils module

pymatgen.analysis.chemenv.utils.scripts_utils module

Module contents

Module contents

pymatgen.analysis.cost package

Subpackages

Submodules

pymatgen.analysis.cost.cost module

Module contents

pymatgen.analysis.defects package

Subpackages

Submodules

pymatgen.analysis.defects.core module

pymatgen.analysis.defects.corrections module

pymatgen.analysis.defects.defect_compatibility module

pymatgen.analysis.defects.dilute_solution_model module

pymatgen.analysis.defects.generators module

pymatgen.analysis.defects.thermodynamics module

pymatgen.analysis.defects.utils module

Module contents

pymatgen.analysis.diffraction package

Subpackages

Submodules

pymatgen.analysis.diffraction.core module

pymatgen.analysis.diffraction.neutron module

pymatgen.analysis.diffraction.xrd module

Module contents

pymatgen.analysis.elasticity package

Submodules

pymatgen.analysis.elasticity.elastic module

pymatgen.analysis.elasticity.strain module

pymatgen.analysis.elasticity.stress module

pymatgen.analysis.elasticity.tensors module

Module contents

pymatgen.analysis.ferroelectricity package

Submodules

pymatgen.analysis.ferroelectricity.polarization module

Module contents

pymatgen.analysis.gb package

Submodules

pymatgen.analysis.gb.grain module

Module contents

pymatgen.analysis.hhi package

Subpackages

Submodules

pymatgen.analysis.hhi.hhi module

Module contents

pymatgen.analysis.magnetism package

Submodules

pymatgen.analysis.magnetism.analyzer module

pymatgen.analysis.magnetism.jahnteller module

Module contents

pymatgen.analysis.structure_prediction package

Subpackages

Submodules

pymatgen.analysis.structure_prediction.dopant_predictor module

pymatgen.analysis.structure_prediction.substitution_probability module

pymatgen.analysis.structure_prediction.substitutor module

pymatgen.analysis.structure_prediction.volume_predictor module

Module contents

pymatgen.analysis.xas package

Subpackages

Submodules

pymatgen.analysis.xas.spectrum module

Module contents

Submodules

pymatgen.analysis.adsorption module

pymatgen.analysis.aflow_prototypes module

pymatgen.analysis.bond_dissociation module

pymatgen.analysis.bond_valence module

pymatgen.analysis.diffusion_analyzer module

pymatgen.analysis.dimensionality module

pymatgen.analysis.energy_models module

pymatgen.analysis.eos module

pymatgen.analysis.ewald module

pymatgen.analysis.excitation module

pymatgen.analysis.find_dimension module

pymatgen.analysis.fragmenter module

pymatgen.analysis.functional_groups module

pymatgen.analysis.graphs module

pymatgen.analysis.interface module

pymatgen.analysis.interface_reactions module

pymatgen.analysis.local_env module

pymatgen.analysis.molecule_matcher module

pymatgen.analysis.molecule_structure_comparator module

pymatgen.analysis.nmr module

pymatgen.analysis.path_finder module

pymatgen.analysis.phase_diagram module

pymatgen.analysis.piezo module

pymatgen.analysis.pourbaix_diagram module

pymatgen.analysis.quasiharmonic module

pymatgen.analysis.reaction_calculator module

pymatgen.analysis.structure_analyzer module

pymatgen.analysis.structure_matcher module

pymatgen.analysis.substrate_analyzer module

pymatgen.analysis.surface_analysis module

pymatgen.analysis.thermochemistry module

pymatgen.analysis.transition_state module

pymatgen.analysis.wulff module

Module contents

pymatgen.apps package

Subpackages

pymatgen.apps.battery package

Subpackages

Submodules

pymatgen.apps.battery.analyzer module

pymatgen.apps.battery.battery_abc module

pymatgen.apps.battery.conversion_battery module

pymatgen.apps.battery.insertion_battery module

pymatgen.apps.battery.plotter module

Module contents

pymatgen.apps.borg package

Subpackages

Submodules

pymatgen.apps.borg.hive module

pymatgen.apps.borg.queen module

Module contents

Module contents

pymatgen.cli package

Submodules

pymatgen.cli.feff_input_generation module

pymatgen.cli.feff_plot_cross_section module

pymatgen.cli.feff_plot_dos module

pymatgen.cli.gaussian_analyzer module

pymatgen.cli.get_environment module

pymatgen.cli.pmg module

pymatgen.cli.pmg_analyze module

pymatgen.cli.pmg_config module

pymatgen.cli.pmg_plot module

pymatgen.cli.pmg_potcar module

pymatgen.cli.pmg_query module

pymatgen.cli.pmg_structure module

Module contents

pymatgen.command_line package

Subpackages

Submodules

pymatgen.command_line.aconvasp_caller module

pymatgen.command_line.bader_caller module

pymatgen.command_line.critic2_caller module

pymatgen.command_line.enumlib_caller module

pymatgen.command_line.gulp_caller module

Module contents

pymatgen.core package

Subpackages

Submodules

pymatgen.core.bonds module

pymatgen.core.composition module

pymatgen.core.ion module

pymatgen.core.lattice module

pymatgen.core.libxcfunc module

pymatgen.core.molecular_orbitals module

pymatgen.core.operations module

pymatgen.core.periodic_table module

pymatgen.core.sites module

pymatgen.core.spectrum module

pymatgen.core.structure module

pymatgen.core.surface module

pymatgen.core.tensors module

pymatgen.core.trajectory module

pymatgen.core.units module

pymatgen.core.xcfunc module

Module contents

pymatgen.electronic_structure package

Subpackages

Submodules

pymatgen.electronic_structure.bandstructure module

pymatgen.electronic_structure.boltztrap module

pymatgen.electronic_structure.boltztrap2 module

pymatgen.electronic_structure.cohp module

pymatgen.electronic_structure.core module

pymatgen.electronic_structure.dos module

pymatgen.electronic_structure.plotter module

Module contents

pymatgen.entries package

Subpackages

Submodules

pymatgen.entries.compatibility module

pymatgen.entries.computed_entries module

pymatgen.entries.entry_tools module

pymatgen.entries.exp_entries module

pymatgen.entries.post_processors_abc module

Module contents

pymatgen.ext package

Subpackages

Submodules

pymatgen.ext.cod module

pymatgen.ext.crystalsai module

pymatgen.ext.jhu module

pymatgen.ext.matproj module

Module contents

pymatgen.io package

Subpackages

pymatgen.io.abinit package

Subpackages

Submodules

pymatgen.io.abinit.abiinspect module

pymatgen.io.abinit.abiobjects module

pymatgen.io.abinit.abitimer module

pymatgen.io.abinit.calculations module

pymatgen.io.abinit.db module

pymatgen.io.abinit.events module

pymatgen.io.abinit.flows module

pymatgen.io.abinit.helpers module

pymatgen.io.abinit.launcher module

pymatgen.io.abinit.netcdf module

pymatgen.io.abinit.nodes module

pymatgen.io.abinit.pseudos module

pymatgen.io.abinit.qadapters module

pymatgen.io.abinit.qjobs module

pymatgen.io.abinit.qutils module

pymatgen.io.abinit.scheduler_error_handlers module

pymatgen.io.abinit.scheduler_error_parsers module

pymatgen.io.abinit.tasks module

pymatgen.io.abinit.utils module

pymatgen.io.abinit.works module

pymatgen.io.abinit.wrappers module

Module contents

pymatgen.io.exciting package

Submodules

pymatgen.io.exciting.inputs module

Module contents

pymatgen.io.feff package

Subpackages

Submodules

pymatgen.io.feff.inputs module

pymatgen.io.feff.outputs module

pymatgen.io.feff.sets module

Module contents

pymatgen.io.lammps package

Subpackages

Submodules

pymatgen.io.lammps.data module

pymatgen.io.lammps.inputs module

pymatgen.io.lammps.outputs module

pymatgen.io.lammps.utils module

Module contents

pymatgen.io.qchem package

Subpackages

Submodules

pymatgen.io.qchem.inputs module

pymatgen.io.qchem.outputs module

pymatgen.io.qchem.sets module

pymatgen.io.qchem.utils module

Module contents

pymatgen.io.vasp package

Subpackages

Submodules

pymatgen.io.vasp.inputs module

pymatgen.io.vasp.outputs module

pymatgen.io.vasp.sets module

Module contents

Submodules

pymatgen.io.adf module

pymatgen.io.aiida module

pymatgen.io.ase module

pymatgen.io.atat module

pymatgen.io.babel module

pymatgen.io.cif module

pymatgen.io.cssr module

pymatgen.io.fiesta module

pymatgen.io.gaussian module

pymatgen.io.lmto module

pymatgen.io.lobster module

pymatgen.io.nwchem module

pymatgen.io.phonopy module

pymatgen.io.prismatic module

pymatgen.io.pwscf module

pymatgen.io.qchem_deprecated module

pymatgen.io.xcrysden module

pymatgen.io.xr module

pymatgen.io.xyz module

pymatgen.io.zeopp module

Module contents

pymatgen.optimization package

Subpackages

Submodules

pymatgen.optimization.linear_assignment module

pymatgen.optimization.linear_assignment_numpy module

Module contents

pymatgen.phonon package

Subpackages

Submodules

pymatgen.phonon.bandstructure module

pymatgen.phonon.dos module

pymatgen.phonon.plotter module

Module contents

pymatgen.symmetry package

Subpackages

Submodules

pymatgen.symmetry.analyzer module

pymatgen.symmetry.bandstructure module

pymatgen.symmetry.groups module

pymatgen.symmetry.maggroups module

pymatgen.symmetry.settings module

pymatgen.symmetry.structure module

Module contents

pymatgen.transformations package

Subpackages

Submodules

pymatgen.transformations.advanced_transformations module

pymatgen.transformations.defect_transformations module

pymatgen.transformations.site_transformations module

pymatgen.transformations.standard_transformations module

pymatgen.transformations.transformation_abc module

Module contents

pymatgen.util package

Subpackages

Submodules

pymatgen.util.convergence module

pymatgen.util.coord module

pymatgen.util.coord_cython module

pymatgen.util.io_utils module

pymatgen.util.num module

pymatgen.util.plotting module

pymatgen.util.provenance module

pymatgen.util.sequence module

pymatgen.util.serialization module

pymatgen.util.string module

pymatgen.util.testing module

pymatgen.util.typing module

Module contents

pymatgen.vis package

Subpackages

Submodules

pymatgen.vis.plotters module

pymatgen.vis.structure_chemview module

pymatgen.vis.structure_vtk module

Module contents

Submodules¶

pymatgen.dao module

Module contents¶

get_structure_from_mp(formula)[source]¶

Convenience method to get a crystal from the Materials Project database via
the API. Requires PMG_MAPI_KEY to be set.

Parameters

formula (str) – A formula

Returns

(Structure) The lowest energy structure in Materials Project with that

formula.

loadfn(fname)[source]¶

Convenience method to perform quick loading of data from a filename. The
type of object returned depends the file type.

Parameters

fname (string) – A filename.

Returns

Note that fname is matched using unix-style, i.e., fnmatch.
(Structure) if POSCAR/CONTCAR/.cif
(Vasprun) *vasprun
(obj) if json (passthrough to monty.serialization.loadfn)

Navigation

          index

          modules |

pymatgen 2019.7.2 documentation »

        © Copyright 2011, Pymatgen Development Team.
      Created using Sphinx 2.0.1.

This page uses
Google Analytics to collect statistics. You can disable it by blocking
the JavaScript coming from www.google-analytics.com.


text:
@implementation AccountSummaryAdaptiveLayout{
    NSInteger itemWidth;
    NSInteger itemHeight;
}

-(void)prepareLayout{
    [super prepareLayout];
    itemWidth = (self.collectionView.frame.size.width - CELL_PADDING)/[self.collectionView numberOfItemsInSection:0] - CELL_PADDING;
    itemHeight = (self.collectionView.frame.size.height - STATUS_BAR_HEIGHT)*[self.collectionView numberOfItemsInSection:0]/6 - CELL_PADDING;
}

-(CGSize)collectionViewContentSize {
    return CGSizeMake(self.collectionView.frame.size.width, self.collectionView.frame.size.height - STATUS_BAR_HEIGHT);
    //iOS 8 bug: somehow when the collection view controller is pushed into a navigation controller with navigation bar, the frame/bounds are no longer returned correctly.
}

- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)path {
    UICollectionViewLayoutAttributes* attributes = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:path];
    attributes.size = CGSizeMake(itemWidth,itemHeight);
    attributes.center = CGPointMake(itemWidth/2 + path.row * (itemWidth + CELL_PADDING) + CELL_PADDING, itemHeight/2 + path.section * (itemHeight + CELL_PADDING));
    return attributes;
}

-(NSArray*)layoutAttributesForElementsInRect:(CGRect)rect {
    NSMutableArray* attributes = [NSMutableArray array];
    UICollectionViewLayoutAttributes *attrs = nil;
    for(NSInteger i=0 ; i < [self.collectionView numberOfSections]; i++) {
        for (NSInteger j=0 ; j < [self.collectionView numberOfItemsInSection:i]; j++) {
            NSIndexPath* indexPath = [NSIndexPath indexPathForItem:j inSection:i];
            attrs = [self layoutAttributesForItemAtIndexPath:indexPath];
            if(!CGRectIsEmpty(CGRectIntersection(attrs.frame, rect))){
                [attributes addObject:attrs];
            }
        }
    }
    return attributes;
}

@end


text:
/*Gaussian_Elimination..
This program needs as a input, the original matrix and the number of rows and columns.
You are able to change the MAX value if you need to work with a bigger matrix*/

#include <iostream>
#define MAX 2000

void Gaussian_Elimination (double matrix[][MAX],int total_row,int total_column)
{
    //Some variables for make my loops
    int i,j,row,column;
    int swap_row = 0;

    //This array will divide the row that is procesing
    double divider[MAX];

    for (row = 0; row < total_row; t++)
    {
        //This make a matrix that will multiply the current row
        for (column = 1+swap_row; column < total_row; column++)
            divider[column] = (double)m[column][row] / m[row][row];

        //Now the divider's matrix will modify the original matrix
        for (i = 1+swap_row; i<total_row; i++)

            for (j=0; j<total_column; j++)
                matrix[i][j] = matrix[i][j] - matrix[row][j]*divider[i];
        swap_row++;
    }
}


text:
namespace Planex.Data.Common.Models
{
    using System;
    using System.ComponentModel.DataAnnotations;
    using System.ComponentModel.DataAnnotations.Schema;

    public abstract class BaseModel<TKey> : IAuditInfo, IDeletableEntity
    {
        public DateTime CreatedOn { get; set; }

        public DateTime? DeletedOn { get; set; }

        [Key]
        public TKey Id { get; set; }

        [Index]
        public bool IsDeleted { get; set; }

        public DateTime? ModifiedOn { get; set; }
    }
}


text:
package hu.unideb.bernkastel.model;

import com.google.gson.annotations.Expose;
import hu.unideb.bernkastel.controller.Constants;

/**
 * Represents the Chasm which gathers Favors in batches of size {@code gatheringBatchSize}.
 * The Favors can be harvested, which adds them to the currently available currencies.
 */
public class Chasm {
    /** Represents the amount of Favors currently gathered in the Chasm. */
    @Expose(serialize = true, deserialize = true)
    private Integer gatheredFavors;

    /** Represents the current size of the batch the Chasm gathers Favors in. */
    @Expose(serialize = true, deserialize = true)
    private Double gatheringBatchSize;

    /**
     * Empty Constructor. Initializes values to default.
     */
    public Chasm() {
        gatheringBatchSize = Constants.baseGatheringBatchSize.doubleValue();
        gatheredFavors = 0;
    }

    /**
     * Getter method for {@code gatheredFavors}.
     * @return the amount of Favors currently gathered in the Chasm.
     */
    public Integer getGatheredFavors() {
        return gatheredFavors;
    }

    /**
     * Setter method for {@code gatheredFavors}.
     * @param gatheredFavors the amount of Favors to set to be currently gathered in the Chasm.
     */
    public void setGatheredFavors(Integer gatheredFavors) {
        this.gatheredFavors = gatheredFavors;
    }

    /**
     * Getter method for {@code gatheringBatchSize}.
     * @return the current size of the batch the Chasm collects Favors in.
     */
    public Double getGatheringBatchSize() {
        return gatheringBatchSize;
    }

    /**
     * Setter method for {@code gatheringBatchSize}.
     * @param gatheringBatchSize the current size of the batch to set the Chasm to collects Favors in.
     */
    public void setGatheringBatchSize(Double gatheringBatchSize) {
        this.gatheringBatchSize = gatheringBatchSize;
    }
}


text:
from __future__ import unicode_literals

import django.contrib.postgres.fields.jsonb
from django.db import migrations

class Migration(migrations.Migration):

    dependencies = [
        ('transcript', '0009_auto_20170308_1450'),
    ]

    operations = [
        migrations.AddField(
            model_name='transcript',
            name='statistics',
            field=django.contrib.postgres.fields.jsonb.JSONField(default={'corrections_submitted': 0, 'phrases_close_to_minimum_sample_size_percent': 0, 'phrases_needing_correction_percent': 0, 'phrases_not_needing_correction_percent': 0, 'phrases_ready_for_export': 0, 'phrases_with_corrections_percent': 0, 'phrases_with_votes_percent': 0, 'total_number_of_phrases': 0}),
        ),
    ]


text:
from flask import Flask, jsonify, abort

app = Flask(__name__)

tasks = [
    {
        'id': 1,
        'title': u'Buy groceries',
        'description': u'Milk, Cheese, Pizza, Fruit, Tylenol',
        'done': False
    },
    {
        'id': 2,
        'title': u'Learn Python',
        'description': u'Need to find a good Python tutorial on the web',
        'done': False
    }
]

from flask.ext.httpauth import HTTPBasicAuth
auth = HTTPBasicAuth()

@auth.get_password
def get_password(username):
    if username == 'miguel':
        return 'python'
    return None

@auth.error_handler
def unauthorized():
    return make_response(jsonify({'error': 'Unauthorized access'}), 403)

@app.route('/todo/api/v1.0/tasks', methods=['GET'])
@auth.login_required
def get_tasks():
    return jsonify({'tasks': [make_public_task(task) for task in tasks]})

@app.route('/todo/api/v1.0/tasks/<int:task_id>', methods=['GET'])
def get_task(task_id):
    task = [task for task in tasks if task['id'] == task_id]
    if len(task) == 0:
        abort(404)
    return jsonify({'task': task[0]})

from flask import make_response

@app.errorhandler(404)
def not_found(error):
    return make_response(jsonify({'error': 'Not found'}), 404)

from flask import request

@app.route('/todo/api/v1.0/tasks', methods=['POST'])
def create_task():
    if not request.json or not 'title' in request.json:
        abort(400)
    task = {
        'id': tasks[-1]['id'] + 1,
        'title': request.json['title'],
        'description': request.json.get('description', ""),
        'done': False
    }
    tasks.append(task)
    return jsonify({'task': task}), 201

@app.route('/todo/api/v1.0/tasks/<int:task_id>', methods=['PUT'])
def update_task(task_id):
    task = [task for task in tasks if task['id'] == task_id]
    if len(task) == 0:
        abort(404)
    if not request.json:
        abort(400)
    if 'title' in request.json and type(request.json['title']) != unicode:
        abort(400)
    if 'description' in request.json and type(request.json['description']) is not unicode:
        abort(400)
    if 'done' in request.json and type(request.json['done']) is not bool:
        abort(400)
    task[0]['title'] = request.json.get('title', task[0]['title'])
    task[0]['description'] = request.json.get('description', task[0]['description'])
    task[0]['done'] = request.json.get('done', task[0]['done'])
    return jsonify({'task': task[0]})

@app.route('/todo/api/v1.0/tasks/<int:task_id>', methods=['DELETE'])
def delete_task(task_id):
    task = [task for task in tasks if task['id'] == task_id]
    if len(task) == 0:
        abort(404)
    tasks.remove(task[0])
    return jsonify({'result': True})

from flask import url_for

def make_public_task(task):
    new_task = {}
    for field in task:
        if field == 'id':
            new_task['uri'] = url_for('get_task', task_id=task['id'], _external=True)
        else:
            new_task[field] = task[field]
    return new_task

if __name__ == '__main__':
    app.run(debug=True)


text:
from typing import Any, Callable, Dict, Generic, Optional, TypeVar
import warnings

from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest
from azure.mgmt.core.exceptions import ARMErrorFormat

from ... import models as _models

T = TypeVar('T')
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]]

class OperationStatusesOperations:
    """OperationStatusesOperations async operations.

    You should not instantiate this class directly. Instead, you should create a Client instance that
    instantiates it for you and attaches it as an attribute.

    :ivar models: Alias to model classes used in this operation group.
    :type models: ~video_analyzer.models
    :param client: Client for service requests.
    :param config: Configuration of service client.
    :param serializer: An object model serializer.
    :param deserializer: An object model deserializer.
    """

    models = _models

    def __init__(self, client, config, serializer, deserializer) -> None:
        self._client = client
        self._serialize = serializer
        self._deserialize = deserializer
        self._config = config

    async def get(
        self,
        resource_group_name: str,
        account_name: str,
        name: str,
        operation_id: str,
        **kwargs: Any
    ) -> "_models.VideoAnalyzerPrivateEndpointConnectionOperationStatus":
        """Get operation status.

        Get private endpoint connection operation status.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
        :type resource_group_name: str
        :param account_name: The Video Analyzer account name.
        :type account_name: str
        :param name: Private endpoint connection name.
        :type name: str
        :param operation_id: Operation Id.
        :type operation_id: str
        :keyword callable cls: A custom type or function that will be passed the direct response
        :return: VideoAnalyzerPrivateEndpointConnectionOperationStatus, or the result of cls(response)
        :rtype: ~video_analyzer.models.VideoAnalyzerPrivateEndpointConnectionOperationStatus
        :raises: ~azure.core.exceptions.HttpResponseError
        """
        cls = kwargs.pop('cls', None)  # type: ClsType["_models.VideoAnalyzerPrivateEndpointConnectionOperationStatus"]
        error_map = {
            401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
        }
        error_map.update(kwargs.pop('error_map', {}))
        api_version = "2021-11-01-preview"
        accept = "application/json"

        # Construct URL
        url = self.get.metadata['url']  # type: ignore
        path_format_arguments = {
            'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1),
            'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1),
            'accountName': self._serialize.url("account_name", account_name, 'str'),
            'name': self._serialize.url("name", name, 'str'),
            'operationId': self._serialize.url("operation_id", operation_id, 'str'),
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}  # type: Dict[str, Any]
        query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')

        # Construct headers
        header_parameters = {}  # type: Dict[str, Any]
        header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')

        request = self._client.get(url, query_parameters, header_parameters)
        pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
        response = pipeline_response.http_response

        if response.status_code not in [200]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response)
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        deserialized = self._deserialize('VideoAnalyzerPrivateEndpointConnectionOperationStatus', pipeline_response)

        if cls:
            return cls(pipeline_response, deserialized, {})

        return deserialized
    get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Media/videoAnalyzers/{accountName}/privateEndpointConnections/{name}/operationStatuses/{operationId}'}  # type: ignore


text:
use strict;
use CoGeX;
use Data::Dumper;
use Getopt::Long;

use vars qw($DEBUG $GO $db $user $pass $coge $dsgid1 $dsgid2);

#Testing: ./replicate_annotations.pl -u coge -p xxx -db xxx -dsgid1 11022 -dsgid2 16746

GetOptions ( "debug=s" => \$DEBUG,
             "go=s"    => \$GO,
             "database|db=s"=>\$db,
	     "user|u=s"=>\$user,
	     "password|pw|p=s"=>\$pass,
	     "dsgid1=i"=>\$dsgid1,
	     "dsgid2=i"=>\$dsgid2,
	   );

my $connstr = "dbi:mysql:dbname=$db;host=localhost;port=3307";
$coge = CoGeX->connect($connstr, $user, $pass );
#$coge->storage->debugobj(new DBIxProfiler());
#$coge->storage->debug(1);

unless ($coge && $dsgid1 && $dsgid2)
  {
    print qq{
Welcome to $0

Purpose:  clone gene models and annotations between two dataset groups.  Does check to see if there is a matching entry in the database to avoid duplicates.  This permits adding new annotations, updating annotations, etc.

Usage:  $0  -db <coge database name> -u <coge database user> -pw <coge database password> -dsgid1 <coge database id for dataset_group to be master> -dsgid2 <coge database id for dataset_group to be copied into> -go 1

Copyright Eric Lyons 2012

};
    exit;
  }

my ($dsg1) = $coge->resultset('DatasetGroup')->find($dsgid1);
my ($dsg2) = $coge->resultset('DatasetGroup')->find($dsgid2);

unless ($dsg1 && $dsg2)
  {
    print qq{
Error:  unable to create a datasetgroup object for one of the IDs
};
    exit;
  }

my $ds1 = map_chr_to_ds($dsg1);
my $ds2 = map_chr_to_ds($dsg2);

unless (scalar keys %$ds1 == scalar keys %$ds2)
  {
    print qq{
Chromosome count mismatch!  Continuing.  Check errors below.
};
  }

print "go flag is not set to 1.  Nothing will be added to database.\n" unless $GO;

foreach my $chr1 (sort keys %$ds1)
  {
    unless ($ds2->{$chr1})
      {
	print "Chromosome $chr1 does not exist in dataset_group_2.  Please check the chromosome names if you think this is in error.  Skipping to next chromosome\n";
	next;
      }
    foreach my $f1 ($ds1->{$chr1}->features->search({chromosome=>$chr1}))
      {
	my ($f2) = $ds2->{$chr1}->features->search({
						    chromosome=>$chr1,
						    feature_type_id=>$f1->feature_type_id,
						    start=>$f1->start,
						    stop=>$f1->stop,
						    strand=>$f1->strand,
						   });
	if ($f2)
	  {
	    print "Feature already exists.\n" if $DEBUG;
	  }
	else
	  {
	    ($f2)= replicate_feature (f1=>$f1, ds2=>$ds2->{$chr1});
	  }
	next unless $f2; #can't do much without the annotation
	replicate_names(f1=>$f1, f2=>$f2);
	replicate_annotations(f1=>$f1, f2=>$f2);
      }
  }

sub replicate_annotations
  {
    my %opts = @_;
    my $f1 = $opts{f1};
    my $f2 = $opts{f2};
    print "Processing annotations\n" if $DEBUG;
    foreach my $anno ($f1->annotations)
      {
	my (@annos) = $f2->annotations->search({annotation=>$anno->annotation, annotation_type_id=>$anno->annotation_type_id});
	if (scalar @annos)
	  {
	    print "\tAnnotation exists\n" if $DEBUG;
	    next;
	  }
	print "\tAdding annotation\n" if $DEBUG;
	$f2->add_to_annotations({annotation=>$anno->annotation, annotation_type_id=>$anno->annotation_type_id}) if $GO;
      }
  }

sub replicate_names
  {
    my %opts = @_;
    my $f1 = $opts{f1};
    my $f2 = $opts{f2};
    print "Processing names\n" if $DEBUG;
    foreach my $name ($f1->feature_names)
      {
	my @names = $f2->feature_names->search({name=>$name->name, description=>$name->description});
	if (scalar @names)
	  {
	    print "\tName exists\n" if $DEBUG;
	    next;
	  }
	print "\tAdding name\n" if $DEBUG;
	$f2->add_to_feature_names({name=>$name->name, description=>$name->description, primary_name=>$name->primary_name}) if $GO;
      }
  }

sub replicate_feature
  {
    my %opts = @_;
    my $f1 = $opts{f1};
    my $ds2 = $opts{ds2};
    print "Creating feature\n" if $DEBUG;
    my ($f2)= $ds2->add_to_features({
				  chromosome=>$f1->chromosome,
				  feature_type_id=>$f1->feature_type_id,
				  start=>$f1->start,
				  stop=>$f1->stop,
				  strand=>$f1->strand,
				 }) if $GO;
    foreach my $loc ($f1->locations)
      {
	print "\tadding location\n" if $DEBUG;
	$f2->add_to_locations({
			       start=>$loc->start,
			       stop=>$loc->stop,
			       strand=>$loc->strand,
			       chromosome=>$loc->chromosome,
			      }) if $GO;
      }
    return $f2;
  }

sub map_chr_to_ds
  {
    my $dsg = shift;
    my %ds;
    foreach my $ds ($dsg->datasets)
      {
	foreach my $chr ($ds->chromosomes)
	  {
	    $ds{$chr}=$ds;
	  }
      }
    return \%ds;
  }


text:
'use strict';

/**
 * Module dependencies.
 */
var mongoose = require('mongoose'),
	Post = mongoose.model('Post'),
	_ = require('lodash');

/**
 * Get the error message from error object
 */
var getErrorMessage = function(err) {
	var message = '';

	if (err.code) {
		switch (err.code) {
			case 11000:
			case 11001:
				message = 'Post already exists';
				break;
			default:
				message = 'Something went wrong';
		}
	} else {
		for (var errName in err.errors) {
			if (err.errors[errName].message) message = err.errors[errName].message;
		}
	}

	return message;
};

/**
 * Create a Post
 */
exports.create = function(req, res) {
	var post = new Post(req.body);
	post.user = req.user;

	post.save(function(err) {
		if (err) {
			return res.send(400, {
				message: getErrorMessage(err)
			});
		} else {
			res.jsonp(post);
		}
	});
};

/**
 * Show the current Post
 */
exports.read = function(req, res) {
	res.jsonp(req.post);
};

/**
 * Update a Post
 */
exports.update = function(req, res) {
	var post = req.post ;

	post = _.extend(post , req.body);

	post.save(function(err) {
		if (err) {
			return res.send(400, {
				message: getErrorMessage(err)
			});
		} else {
			res.jsonp(post);
		}
	});
};

/**
 * Delete an Post
 */
exports.delete = function(req, res) {
	var post = req.post ;

	post.remove(function(err) {
		if (err) {
			return res.send(400, {
				message: getErrorMessage(err)
			});
		} else {
			res.jsonp(post);
		}
	});
};

/**
 * List of Posts
 */
exports.list = function(req, res) { Post.find().sort('-created').populate('user', 'displayName').exec(function(err, posts) {
		if (err) {
			return res.send(400, {
				message: getErrorMessage(err)
			});
		} else {
			res.jsonp(posts);
		}
	});
};

/**
 * Post middleware
 */
exports.postByID = function(req, res, next, id) { Post.findById(id).populate('user', 'displayName').exec(function(err, post) {
		if (err) return next(err);
		if (! post) return next(new Error('Failed to load Post ' + id));
		req.post = post ;
		next();
	});
};

/**
 * Post authorization middleware
 */
exports.hasAuthorization = function(req, res, next) {
	if (req.post.user.id !== req.user.id) {
		return res.send(403, 'User is not authorized');
	}
	next();
};


text:
// Generated by the protocol buffer compiler.  DO NOT EDIT!
// source: google/ads/googleads/v12/enums/hotel_rate_type.proto

package com.google.ads.googleads.v12.enums;

/**
 *

 * Container for enum describing possible hotel rate types.
 *

 *
 * Protobuf type {@code google.ads.googleads.v12.enums.HotelRateTypeEnum}
 */
public final class HotelRateTypeEnum extends
    com.google.protobuf.GeneratedMessageV3 implements
    // @@protoc_insertion_point(message_implements:google.ads.googleads.v12.enums.HotelRateTypeEnum)
    HotelRateTypeEnumOrBuilder {
private static final long serialVersionUID = 0L;
  // Use HotelRateTypeEnum.newBuilder() to construct.
  private HotelRateTypeEnum(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
    super(builder);
  }
  private HotelRateTypeEnum() {
  }

  @java.lang.Override
  @SuppressWarnings({"unused"})
  protected java.lang.Object newInstance(
      UnusedPrivateParameter unused) {
    return new HotelRateTypeEnum();
  }

  @java.lang.Override
  public final com.google.protobuf.UnknownFieldSet
  getUnknownFields() {
    return this.unknownFields;
  }
  public static final com.google.protobuf.Descriptors.Descriptor
      getDescriptor() {
    return com.google.ads.googleads.v12.enums.HotelRateTypeProto.internal_static_google_ads_googleads_v12_enums_HotelRateTypeEnum_descriptor;
  }

  @java.lang.Override
  protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
      internalGetFieldAccessorTable() {
    return com.google.ads.googleads.v12.enums.HotelRateTypeProto.internal_static_google_ads_googleads_v12_enums_HotelRateTypeEnum_fieldAccessorTable
        .ensureFieldAccessorsInitialized(
            com.google.ads.googleads.v12.enums.HotelRateTypeEnum.class, com.google.ads.googleads.v12.enums.HotelRateTypeEnum.Builder.class);
  }

  /**
   *

   * Enum describing possible hotel rate types.
   *

   *
   * Protobuf enum {@code google.ads.googleads.v12.enums.HotelRateTypeEnum.HotelRateType}
   */
  public enum HotelRateType
      implements com.google.protobuf.ProtocolMessageEnum {
    /**
     *

     * Not specified.
     *

     *
     * UNSPECIFIED = 0;
     */
    UNSPECIFIED(0),
    /**
     *

     * The value is unknown in this version.
     *

     *
     * UNKNOWN = 1;
     */
    UNKNOWN(1),
    /**
     *

     * Rate type information is unavailable.
     *

     *
     * UNAVAILABLE = 2;
     */
    UNAVAILABLE(2),
    /**
     *

     * Rates available to everyone.
     *

     *
     * PUBLIC_RATE = 3;
     */
    PUBLIC_RATE(3),
    /**
     *

     * A membership program rate is available and satisfies basic requirements
     * like having a public rate available. UI treatment will strikethrough the
     * public rate and indicate that a discount is available to the user. For
     * more on Qualified Rates, visit
     * https://developers.google.com/hotels/hotel-ads/dev-guide/qualified-rates
     *

     *
     * QUALIFIED_RATE = 4;
     */
    QUALIFIED_RATE(4),
    /**
     *

     * Rates available to users that satisfy some eligibility criteria, for
     * example, all signed-in users, 20% of mobile users, all mobile users in
     * Canada, etc.
     *

     *
     * PRIVATE_RATE = 5;
     */
    PRIVATE_RATE(5),
    UNRECOGNIZED(-1),
    ;

    /**
     *

     * Not specified.
     *

     *
     * UNSPECIFIED = 0;
     */
    public static final int UNSPECIFIED_VALUE = 0;
    /**
     *

     * The value is unknown in this version.
     *

     *
     * UNKNOWN = 1;
     */
    public static final int UNKNOWN_VALUE = 1;
    /**
     *

     * Rate type information is unavailable.
     *

     *
     * UNAVAILABLE = 2;
     */
    public static final int UNAVAILABLE_VALUE = 2;
    /**
     *

     * Rates available to everyone.
     *

     *
     * PUBLIC_RATE = 3;
     */
    public static final int PUBLIC_RATE_VALUE = 3;
    /**
     *

     * A membership program rate is available and satisfies basic requirements
     * like having a public rate available. UI treatment will strikethrough the
     * public rate and indicate that a discount is available to the user. For
     * more on Qualified Rates, visit
     * https://developers.google.com/hotels/hotel-ads/dev-guide/qualified-rates
     *

     *
     * QUALIFIED_RATE = 4;
     */
    public static final int QUALIFIED_RATE_VALUE = 4;
    /**
     *

     * Rates available to users that satisfy some eligibility criteria, for
     * example, all signed-in users, 20% of mobile users, all mobile users in
     * Canada, etc.
     *

     *
     * PRIVATE_RATE = 5;
     */
    public static final int PRIVATE_RATE_VALUE = 5;

    public final int getNumber() {
      if (this == UNRECOGNIZED) {
        throw new java.lang.IllegalArgumentException(
            "Can't get the number of an unknown enum value.");
      }
      return value;
    }

    /**
     * @param value The numeric wire value of the corresponding enum entry.
     * @return The enum associated with the given numeric wire value.
     * @deprecated Use {@link #forNumber(int)} instead.
     */
    @java.lang.Deprecated
    public static HotelRateType valueOf(int value) {
      return forNumber(value);
    }

    /**
     * @param value The numeric wire value of the corresponding enum entry.
     * @return The enum associated with the given numeric wire value.
     */
    public static HotelRateType forNumber(int value) {
      switch (value) {
        case 0: return UNSPECIFIED;
        case 1: return UNKNOWN;
        case 2: return UNAVAILABLE;
        case 3: return PUBLIC_RATE;
        case 4: return QUALIFIED_RATE;
        case 5: return PRIVATE_RATE;
        default: return null;
      }
    }

    public static com.google.protobuf.Internal.EnumLiteMap<HotelRateType>
        internalGetValueMap() {
      return internalValueMap;
    }
    private static final com.google.protobuf.Internal.EnumLiteMap<
        HotelRateType> internalValueMap =
          new com.google.protobuf.Internal.EnumLiteMap<HotelRateType>() {
            public HotelRateType findValueByNumber(int number) {
              return HotelRateType.forNumber(number);
            }
          };

    public final com.google.protobuf.Descriptors.EnumValueDescriptor
        getValueDescriptor() {
      if (this == UNRECOGNIZED) {
        throw new java.lang.IllegalStateException(
            "Can't get the descriptor of an unrecognized enum value.");
      }
      return getDescriptor().getValues().get(ordinal());
    }
    public final com.google.protobuf.Descriptors.EnumDescriptor
        getDescriptorForType() {
      return getDescriptor();
    }
    public static final com.google.protobuf.Descriptors.EnumDescriptor
        getDescriptor() {
      return com.google.ads.googleads.v12.enums.HotelRateTypeEnum.getDescriptor().getEnumTypes().get(0);
    }

    private static final HotelRateType[] VALUES = values();

    public static HotelRateType valueOf(
        com.google.protobuf.Descriptors.EnumValueDescriptor desc) {
      if (desc.getType() != getDescriptor()) {
        throw new java.lang.IllegalArgumentException(
          "EnumValueDescriptor is not for this type.");
      }
      if (desc.getIndex() == -1) {
        return UNRECOGNIZED;
      }
      return VALUES[desc.getIndex()];
    }

    private final int value;

    private HotelRateType(int value) {
      this.value = value;
    }

    // @@protoc_insertion_point(enum_scope:google.ads.googleads.v12.enums.HotelRateTypeEnum.HotelRateType)
  }

  private byte memoizedIsInitialized = -1;
  @java.lang.Override
  public final boolean isInitialized() {
    byte isInitialized = memoizedIsInitialized;
    if (isInitialized == 1) return true;
    if (isInitialized == 0) return false;

    memoizedIsInitialized = 1;
    return true;
  }

  @java.lang.Override
  public void writeTo(com.google.protobuf.CodedOutputStream output)
                      throws java.io.IOException {
    getUnknownFields().writeTo(output);
  }

  @java.lang.Override
  public int getSerializedSize() {
    int size = memoizedSize;
    if (size != -1) return size;

    size = 0;
    size += getUnknownFields().getSerializedSize();
    memoizedSize = size;
    return size;
  }

  @java.lang.Override
  public boolean equals(final java.lang.Object obj) {
    if (obj == this) {
     return true;
    }
    if (!(obj instanceof com.google.ads.googleads.v12.enums.HotelRateTypeEnum)) {
      return super.equals(obj);
    }
    com.google.ads.googleads.v12.enums.HotelRateTypeEnum other = (com.google.ads.googleads.v12.enums.HotelRateTypeEnum) obj;

    if (!getUnknownFields().equals(other.getUnknownFields())) return false;
    return true;
  }

  @java.lang.Override
  public int hashCode() {
    if (memoizedHashCode != 0) {
      return memoizedHashCode;
    }
    int hash = 41;
    hash = (19 * hash) + getDescriptor().hashCode();
    hash = (29 * hash) + getUnknownFields().hashCode();
    memoizedHashCode = hash;
    return hash;
  }

  public static com.google.ads.googleads.v12.enums.HotelRateTypeEnum parseFrom(
      java.nio.ByteBuffer data)
      throws com.google.protobuf.InvalidProtocolBufferException {
    return PARSER.parseFrom(data);
  }
  public static com.google.ads.googleads.v12.enums.HotelRateTypeEnum parseFrom(
      java.nio.ByteBuffer data,
      com.google.protobuf.ExtensionRegistryLite extensionRegistry)
      throws com.google.protobuf.InvalidProtocolBufferException {
    return PARSER.parseFrom(data, extensionRegistry);
  }
  public static com.google.ads.googleads.v12.enums.HotelRateTypeEnum parseFrom(
      com.google.protobuf.ByteString data)
      throws com.google.protobuf.InvalidProtocolBufferException {
    return PARSER.parseFrom(data);
  }
  public static com.google.ads.googleads.v12.enums.HotelRateTypeEnum parseFrom(
      com.google.protobuf.ByteString data,
      com.google.protobuf.ExtensionRegistryLite extensionRegistry)
      throws com.google.protobuf.InvalidProtocolBufferException {
    return PARSER.parseFrom(data, extensionRegistry);
  }
  public static com.google.ads.googleads.v12.enums.HotelRateTypeEnum parseFrom(byte[] data)
      throws com.google.protobuf.InvalidProtocolBufferException {
    return PARSER.parseFrom(data);
  }
  public static com.google.ads.googleads.v12.enums.HotelRateTypeEnum parseFrom(
      byte[] data,
      com.google.protobuf.ExtensionRegistryLite extensionRegistry)
      throws com.google.protobuf.InvalidProtocolBufferException {
    return PARSER.parseFrom(data, extensionRegistry);
  }
  public static com.google.ads.googleads.v12.enums.HotelRateTypeEnum parseFrom(java.io.InputStream input)
      throws java.io.IOException {
    return com.google.protobuf.GeneratedMessageV3
        .parseWithIOException(PARSER, input);
  }
  public static com.google.ads.googleads.v12.enums.HotelRateTypeEnum parseFrom(
      java.io.InputStream input,
      com.google.protobuf.ExtensionRegistryLite extensionRegistry)
      throws java.io.IOException {
    return com.google.protobuf.GeneratedMessageV3
        .parseWithIOException(PARSER, input, extensionRegistry);
  }
  public static com.google.ads.googleads.v12.enums.HotelRateTypeEnum parseDelimitedFrom(java.io.InputStream input)
      throws java.io.IOException {
    return com.google.protobuf.GeneratedMessageV3
        .parseDelimitedWithIOException(PARSER, input);
  }
  public static com.google.ads.googleads.v12.enums.HotelRateTypeEnum parseDelimitedFrom(
      java.io.InputStream input,
      com.google.protobuf.ExtensionRegistryLite extensionRegistry)
      throws java.io.IOException {
    return com.google.protobuf.GeneratedMessageV3
        .parseDelimitedWithIOException(PARSER, input, extensionRegistry);
  }
  public static com.google.ads.googleads.v12.enums.HotelRateTypeEnum parseFrom(
      com.google.protobuf.CodedInputStream input)
      throws java.io.IOException {
    return com.google.protobuf.GeneratedMessageV3
        .parseWithIOException(PARSER, input);
  }
  public static com.google.ads.googleads.v12.enums.HotelRateTypeEnum parseFrom(
      com.google.protobuf.CodedInputStream input,
      com.google.protobuf.ExtensionRegistryLite extensionRegistry)
      throws java.io.IOException {
    return com.google.protobuf.GeneratedMessageV3
        .parseWithIOException(PARSER, input, extensionRegistry);
  }

  @java.lang.Override
  public Builder newBuilderForType() { return newBuilder(); }
  public static Builder newBuilder() {
    return DEFAULT_INSTANCE.toBuilder();
  }
  public static Builder newBuilder(com.google.ads.googleads.v12.enums.HotelRateTypeEnum prototype) {
    return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
  }
  @java.lang.Override
  public Builder toBuilder() {
    return this == DEFAULT_INSTANCE
        ? new Builder() : new Builder().mergeFrom(this);
  }

  @java.lang.Override
  protected Builder newBuilderForType(
      com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
    Builder builder = new Builder(parent);
    return builder;
  }
  /**
   *

   * Container for enum describing possible hotel rate types.
   *

   *
   * Protobuf type {@code google.ads.googleads.v12.enums.HotelRateTypeEnum}
   */
  public static final class Builder extends
      com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements
      // @@protoc_insertion_point(builder_implements:google.ads.googleads.v12.enums.HotelRateTypeEnum)
      com.google.ads.googleads.v12.enums.HotelRateTypeEnumOrBuilder {
    public static final com.google.protobuf.Descriptors.Descriptor
        getDescriptor() {
      return com.google.ads.googleads.v12.enums.HotelRateTypeProto.internal_static_google_ads_googleads_v12_enums_HotelRateTypeEnum_descriptor;
    }

    @java.lang.Override
    protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
        internalGetFieldAccessorTable() {
      return com.google.ads.googleads.v12.enums.HotelRateTypeProto.internal_static_google_ads_googleads_v12_enums_HotelRateTypeEnum_fieldAccessorTable
          .ensureFieldAccessorsInitialized(
              com.google.ads.googleads.v12.enums.HotelRateTypeEnum.class, com.google.ads.googleads.v12.enums.HotelRateTypeEnum.Builder.class);
    }

    // Construct using com.google.ads.googleads.v12.enums.HotelRateTypeEnum.newBuilder()
    private Builder() {

    }

    private Builder(
        com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
      super(parent);

    }
    @java.lang.Override
    public Builder clear() {
      super.clear();
      return this;
    }

    @java.lang.Override
    public com.google.protobuf.Descriptors.Descriptor
        getDescriptorForType() {
      return com.google.ads.googleads.v12.enums.HotelRateTypeProto.internal_static_google_ads_googleads_v12_enums_HotelRateTypeEnum_descriptor;
    }

    @java.lang.Override
    public com.google.ads.googleads.v12.enums.HotelRateTypeEnum getDefaultInstanceForType() {
      return com.google.ads.googleads.v12.enums.HotelRateTypeEnum.getDefaultInstance();
    }

    @java.lang.Override
    public com.google.ads.googleads.v12.enums.HotelRateTypeEnum build() {
      com.google.ads.googleads.v12.enums.HotelRateTypeEnum result = buildPartial();
      if (!result.isInitialized()) {
        throw newUninitializedMessageException(result);
      }
      return result;
    }

    @java.lang.Override
    public com.google.ads.googleads.v12.enums.HotelRateTypeEnum buildPartial() {
      com.google.ads.googleads.v12.enums.HotelRateTypeEnum result = new com.google.ads.googleads.v12.enums.HotelRateTypeEnum(this);
      onBuilt();
      return result;
    }

    @java.lang.Override
    public Builder clone() {
      return super.clone();
    }
    @java.lang.Override
    public Builder setField(
        com.google.protobuf.Descriptors.FieldDescriptor field,
        java.lang.Object value) {
      return super.setField(field, value);
    }
    @java.lang.Override
    public Builder clearField(
        com.google.protobuf.Descriptors.FieldDescriptor field) {
      return super.clearField(field);
    }
    @java.lang.Override
    public Builder clearOneof(
        com.google.protobuf.Descriptors.OneofDescriptor oneof) {
      return super.clearOneof(oneof);
    }
    @java.lang.Override
    public Builder setRepeatedField(
        com.google.protobuf.Descriptors.FieldDescriptor field,
        int index, java.lang.Object value) {
      return super.setRepeatedField(field, index, value);
    }
    @java.lang.Override
    public Builder addRepeatedField(
        com.google.protobuf.Descriptors.FieldDescriptor field,
        java.lang.Object value) {
      return super.addRepeatedField(field, value);
    }
    @java.lang.Override
    public Builder mergeFrom(com.google.protobuf.Message other) {
      if (other instanceof com.google.ads.googleads.v12.enums.HotelRateTypeEnum) {
        return mergeFrom((com.google.ads.googleads.v12.enums.HotelRateTypeEnum)other);
      } else {
        super.mergeFrom(other);
        return this;
      }
    }

    public Builder mergeFrom(com.google.ads.googleads.v12.enums.HotelRateTypeEnum other) {
      if (other == com.google.ads.googleads.v12.enums.HotelRateTypeEnum.getDefaultInstance()) return this;
      this.mergeUnknownFields(other.getUnknownFields());
      onChanged();
      return this;
    }

    @java.lang.Override
    public final boolean isInitialized() {
      return true;
    }

    @java.lang.Override
    public Builder mergeFrom(
        com.google.protobuf.CodedInputStream input,
        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
        throws java.io.IOException {
      if (extensionRegistry == null) {
        throw new java.lang.NullPointerException();
      }
      try {
        boolean done = false;
        while (!done) {
          int tag = input.readTag();
          switch (tag) {
            case 0:
              done = true;
              break;
            default: {
              if (!super.parseUnknownField(input, extensionRegistry, tag)) {
                done = true; // was an endgroup tag
              }
              break;
            } // default:
          } // switch (tag)
        } // while (!done)
      } catch (com.google.protobuf.InvalidProtocolBufferException e) {
        throw e.unwrapIOException();
      } finally {
        onChanged();
      } // finally
      return this;
    }
    @java.lang.Override
    public final Builder setUnknownFields(
        final com.google.protobuf.UnknownFieldSet unknownFields) {
      return super.setUnknownFields(unknownFields);
    }

    @java.lang.Override
    public final Builder mergeUnknownFields(
        final com.google.protobuf.UnknownFieldSet unknownFields) {
      return super.mergeUnknownFields(unknownFields);
    }

    // @@protoc_insertion_point(builder_scope:google.ads.googleads.v12.enums.HotelRateTypeEnum)
  }

  // @@protoc_insertion_point(class_scope:google.ads.googleads.v12.enums.HotelRateTypeEnum)
  private static final com.google.ads.googleads.v12.enums.HotelRateTypeEnum DEFAULT_INSTANCE;
  static {
    DEFAULT_INSTANCE = new com.google.ads.googleads.v12.enums.HotelRateTypeEnum();
  }

  public static com.google.ads.googleads.v12.enums.HotelRateTypeEnum getDefaultInstance() {
    return DEFAULT_INSTANCE;
  }

  private static final com.google.protobuf.Parser<HotelRateTypeEnum>
      PARSER = new com.google.protobuf.AbstractParser<HotelRateTypeEnum>() {
    @java.lang.Override
    public HotelRateTypeEnum parsePartialFrom(
        com.google.protobuf.CodedInputStream input,
        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
        throws com.google.protobuf.InvalidProtocolBufferException {
      Builder builder = newBuilder();
      try {
        builder.mergeFrom(input, extensionRegistry);
      } catch (com.google.protobuf.InvalidProtocolBufferException e) {
        throw e.setUnfinishedMessage(builder.buildPartial());
      } catch (com.google.protobuf.UninitializedMessageException e) {
        throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial());
      } catch (java.io.IOException e) {
        throw new com.google.protobuf.InvalidProtocolBufferException(e)
            .setUnfinishedMessage(builder.buildPartial());
      }
      return builder.buildPartial();
    }
  };

  public static com.google.protobuf.Parser<HotelRateTypeEnum> parser() {
    return PARSER;
  }

  @java.lang.Override
  public com.google.protobuf.Parser<HotelRateTypeEnum> getParserForType() {
    return PARSER;
  }

  @java.lang.Override
  public com.google.ads.googleads.v12.enums.HotelRateTypeEnum getDefaultInstanceForType() {
    return DEFAULT_INSTANCE;
  }

}


text:
<!doctype html>

  <meta charset="utf-8">

  <title>Basis.js demos: Tabs</title>


text:
static NSString* const kUserDefaultCrashSequenceCount = @"DFApplication_crashSequenceCount";
static NSUInteger const kCrashSequenceCountMax = 3;

//-------------------------------------------------------------------------------------------------
@implementation DFApplication
{
    BOOL _isRelaunching;
    BOOL _isPostmortem;
}

//-------------------------------------------------------------------------------------------------
- (id)init
{
	self = [super init];
	if (self != nil)
	{
	}
	return self;
}

//-------------------------------------------------------------------------------------------------
- (void)dealloc
{
	[super dealloc];
}

//-------------------------------------------------------------------------------------------------
- (void)launchAnotherInstanceAndWaitForTermination
{
    _isRelaunching = YES;

    // NOTE: it seems to sometimes not work, at least it fails sometimes on 10.8 in sandboxed mode

    // launch a script that waits for the app to exit and then relaunches it
    NSString* scriptPath = [[NSBundle mainBundle] pathForResource:@"DFRelaunch" ofType:@"sh"];
    NSString* bundlePath = [NSString stringWithFormat:@"%s", [NSBundle mainBundle].executablePath.fileSystemRepresentation];
    NSString* processIdentifier = [NSString stringWithFormat:@"%d", [NSProcessInfo processInfo].processIdentifier];
    NSString* bundleId = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleIdentifier"];
    NSArray* arguments = @[scriptPath,
                           bundlePath,
                           processIdentifier,
                           bundleId];
    NSTask* task = [[[NSTask alloc] init] autorelease];
    task.launchPath = @"/bin/bash";
    task.arguments = arguments;
    [task launch];
}

//-------------------------------------------------------------------------------------------------
- (void)relaunch
{

	// prevent endless loop of relaunch and crash
	NSUInteger crashSequenceCount = [[NSUserDefaults standardUserDefaults] integerForKey:kUserDefaultCrashSequenceCount];
    if (crashSequenceCount < kCrashSequenceCountMax - 1)
	{
		[self launchAnotherInstanceAndWaitForTermination];
	}
	[self terminate:self];
}

//-------------------------------------------------------------------------------------------------
- (void)terminate:(id)sender
{
	// abnormal termination
	if (_isPostmortem && _isRelaunching)
	{
        // save sequential crash count
		NSUInteger crashSequenceCount = [[NSUserDefaults standardUserDefaults] integerForKey:kUserDefaultCrashSequenceCount];
        ++crashSequenceCount;
        [[NSUserDefaults standardUserDefaults] setInteger:crashSequenceCount
                                                   forKey:kUserDefaultCrashSequenceCount];
        [[NSUserDefaults standardUserDefaults] synchronize];

	}
	// normal termination
	else
	{
        // reset crash counter
		[[NSUserDefaults standardUserDefaults] removeObjectForKey:kUserDefaultCrashSequenceCount];
		[[NSUserDefaults standardUserDefaults] synchronize];
	}
	// do terminate
	[super terminate:self];
}

//-------------------------------------------------------------------------------------------------
- (BOOL)shouldIgnoreException:(NSException*)exception
{
	NSString* exceptionName = exception.name;
	NSString* exceptionMessage = exception.reason;

    // accessibility exceptions are a normal mode of operation, should be ignored
	BOOL isAccessibilityException = [exceptionName isEqualToString:NSAccessibilityException];

    // Sparkle Update bugs should be ignored
	BOOL isSparkleException = [exceptionMessage rangeOfString:@"Versions/A/Sparkle"].location != NSNotFound;

    // Simble exceptions should be ignored
	BOOL isSimbleException = [exceptionMessage rangeOfString:@"SIMBL"].location != NSNotFound;

	return isAccessibilityException || isSparkleException || isSimbleException;
}

//-------------------------------------------------------------------------------------------------
- (void)reportExceptionInMainThread:(NSException*)exception
{
    @try
    {
        if (!_isPostmortem)
        {
            // prevent endless loop
            _isPostmortem = YES;

            NSLog(@"Reporting exception: %@", exception.reason);

            // hide all windows
            for (NSWindow* window in [NSApp windows])
            {
                [window orderOut:self];
            }

            // show problem report window
            [[DFCrashReportWindowController singleton] showReportForException:exception];
        }
    }
    @catch (NSException* fatalException)
    {
        // the exception occurred during exception handling - considered fatal
        NSLog(@"Fatal error:%@\nwhile processing exception: %@", fatalException.reason, exception.reason);
        @try
        {
            [(DFApplication*)NSApp relaunch];
        }
        @catch (NSException* exception)
        {
            // absorb silently
        }
    }
}

//-------------------------------------------------------------------------------------------------
- (void)reportException:(NSException*)exception
{
    [super reportException:exception];

	if (![self shouldIgnoreException:exception])
    {
        // main thread
        if ([NSThread currentThread] == [NSThread mainThread])
        {
            [self reportExceptionInMainThread:exception];
        }
        // not main thread
        else
        {
            // handle on main thread
            [self performSelectorOnMainThread:@selector(reportExceptionInMainThread:)
                                   withObject:exception
                                waitUntilDone:NO];
            // exit immediately, or will crash the app
            [NSThread exit];
        }
    }
}

@end


text:
(function($) {
    $.extend(true, window, {
        Slick: {
            Data: {
                DataView: DataView,
                Aggregators: {
                    Avg: AvgAggregator,
                    Min: MinAggregator,
                    Max: MaxAggregator
                }
            }
        }
    });

    /***
     * A sample Model implementation.
     * Provides a filtered view of the underlying data.
     *
     * Relies on the data item having an "id" property uniquely identifying it.
     */
    function DataView() {
        var self = this;

        // private
        var idProperty = "id";  // property holding a unique row id
        var items = [];			// data by index
        var rows = [];			// data by row
        var idxById = {};		// indexes by id
        var rowsById = null;	// rows by id; lazy-calculated
        var filter = null;		// filter function
        var updated = null; 	// updated item ids
        var suspend = false;	// suspends the recalculation
        var sortAsc = true;
        var fastSortField;
        var sortComparer;

        // grouping
        var groupingGetter;
        var groupingGetterIsAFn;
        var groupingFormatter;
        var groupingComparer;
        var groups = [];
        var collapsedGroups = {};
        var aggregators;
        var aggregateCollapsed = false;

        var pagesize = 0;
        var pagenum = 0;
        var totalRows = 0;

        // events
        var onRowCountChanged = new Slick.Event();
        var onRowsChanged = new Slick.Event();
        var onPagingInfoChanged = new Slick.Event();

        function beginUpdate() {
            suspend = true;
        }

        function endUpdate(hints) {
            suspend = false;
            refresh(hints);
        }

        function refreshIdxById() {
            idxById = {};
            for (var i = 0,l = items.length; i < l; i++) {
                var id = items[i][idProperty];
                if (id == undefined || idxById[id] != undefined)
                    throw "Each data element must implement a unique 'id' property";
                idxById[id] = i;
            }
        }

        function getItems() {
            return items;
        }

        function setItems(data, objectIdProperty) {
            if (objectIdProperty !== undefined) idProperty = objectIdProperty;
            items = data;
            refreshIdxById();
            refresh();
        }

        function setPagingOptions(args) {
            if (args.pageSize != undefined)
                pagesize = args.pageSize;

            if (args.pageNum != undefined)
                pagenum = Math.min(args.pageNum, Math.ceil(totalRows / pagesize));

            onPagingInfoChanged.notify(getPagingInfo(), null, self);

            refresh();
        }

        function getPagingInfo() {
            return {pageSize:pagesize, pageNum:pagenum, totalRows:totalRows};
        }

        function sort(comparer, ascending) {
           sortAsc = ascending;
           sortComparer = comparer;
           fastSortField = null;
           if (ascending === false) items.reverse();
           items.sort(comparer);
           if (ascending === false) items.reverse();
           refreshIdxById();
           refresh();
        }

       /***
        * Provides a workaround for the extremely slow sorting in IE.
        * Does a [lexicographic] sort on a give column by temporarily overriding Object.prototype.toString
        * to return the value of that field and then doing a native Array.sort().
        */
       function fastSort(field, ascending) {
           sortAsc = ascending;
           fastSortField = field;
           sortComparer = null;
           var oldToString = Object.prototype.toString;
           Object.prototype.toString = (typeof field == "function")?field:function() { return this[field] };
           // an extra reversal for descending sort keeps the sort stable
           // (assuming a stable native sort implementation, which isn't true in some cases)
           if (ascending === false) items.reverse();
           items.sort();
           Object.prototype.toString = oldToString;
           if (ascending === false) items.reverse();
           refreshIdxById();
           refresh();
       }

        function reSort() {
            if (sortComparer) {
               sort(sortComparer, sortAsc);
            }
            else if (fastSortField) {
               fastSort(fastSortField, sortAsc);
            }
        }

        function setFilter(filterFn) {
            filter = filterFn;
            refresh();
        }

        function groupBy(valueGetter, valueFormatter, sortComparer) {
            groupingGetter = valueGetter;
            groupingGetterIsAFn = typeof groupingGetter === "function";
            groupingFormatter = valueFormatter;
            groupingComparer = sortComparer;
            collapsedGroups = {};
            groups = [];
            refresh();
        }

        function setAggregators(groupAggregators, includeCollapsed) {
            aggregators = groupAggregators;
            aggregateCollapsed = includeCollapsed !== undefined ? includeCollapsed : aggregateCollapsed;
            refresh();
        }

        function getItemByIdx(i) {
            return items[i];
        }

        function getIdxById(id) {
            return idxById[id];
        }

        // calculate the lookup table on first call
        function getRowById(id) {
            if (!rowsById) {
                rowsById = {};
                for (var i = 0, l = rows.length; i < l; ++i) {
                    rowsById[rows[i][idProperty]] = i;
                }
            }

            return rowsById[id];
        }

        function getItemById(id) {
            return items[idxById[id]];
        }

        function updateItem(id, item) {
            if (idxById[id] === undefined || id !== item[idProperty])
                throw "Invalid or non-matching id";
            items[idxById[id]] = item;
            if (!updated) updated = {};
            updated[id] = true;
            refresh();
        }

        function insertItem(insertBefore, item) {
            items.splice(insertBefore, 0, item);
            refreshIdxById();  // TODO:  optimize
            refresh();
        }

        function addItem(item) {
            items.push(item);
            refreshIdxById();  // TODO:  optimize
            refresh();
        }

        function deleteItem(id) {
            if (idxById[id] === undefined)
                throw "Invalid id";
            items.splice(idxById[id], 1);
            refreshIdxById();  // TODO:  optimize
            refresh();
        }

        function getLength() {
            return rows.length;
        }

        function getItem(i) {
            return rows[i];
        }

        function collapseGroup(groupingValue) {
            collapsedGroups[groupingValue] = true;
            refresh();
        }

        function expandGroup(groupingValue) {
            delete collapsedGroups[groupingValue];
            refresh();
        }

        function getGroups() {
            return groups;
        }

        function extractGroups(rows) {
            var group;
            var val;
            var groups = [];
            var groupsByVal = {};
            var r;

            for (var i = 0, l = rows.length; i < l; i++) {
                r = rows[i];
                val = (groupingGetterIsAFn) ? groupingGetter(r) : r[groupingGetter];
                group = groupsByVal[val];
                if (!group) {
                    group = new Slick.Group();
                    group.count = 0;
                    group.value = val;
                    group.rows = [];
                    groups[groups.length] = group;
                    groupsByVal[val] = group;
                }

                group.rows[group.count++] = r;
            }

            return groups;
        }

        // TODO:  lazy totals calculation

        function calculateGroupTotals(group) {
            var r, idx;

            if (group.collapsed && !aggregateCollapsed) {
                return;
            }

            idx = aggregators.length;
            while (idx--) {
                aggregators[idx].init();
            }

            for (var j = 0, jj = group.rows.length; j < jj; j++) {
                r = group.rows[j];
                idx = aggregators.length;
                while (idx--) {
                    aggregators[idx].accumulate(r);
                }
            }

            var t = new Slick.GroupTotals();
            idx = aggregators.length;
            while (idx--) {
                aggregators[idx].storeResult(t);
            }
            t.group = group;
            group.totals = t;
        }

        function calculateTotals(groups) {
            var idx = groups.length;
            while (idx--) {
                calculateGroupTotals(groups[idx]);
            }
        }

        function finalizeGroups(groups) {
            var idx = groups.length, g;
            while (idx--) {
                g = groups[idx];
                g.collapsed = (g.value in collapsedGroups);
                g.title = groupingFormatter ? groupingFormatter(g) : g.value;
            }
        }

        function flattenGroupedRows(groups) {
            var groupedRows = [], gl = 0, idx, t, g, r;
            for (var i = 0, l = groups.length; i < l; i++) {
                g = groups[i];
                groupedRows[gl++] = g;

                if (!g.collapsed) {
                    for (var j = 0, jj = g.rows.length; j < jj; j++) {
                        groupedRows[gl++] = g.rows[j];
                    }
                }

                if (g.totals && (!g.collapsed || aggregateCollapsed)) {
                    groupedRows[gl++] = g.totals;
                }
            }
            return groupedRows;
        }

        function getFilteredAndPagedItems(items, filter) {
            var pageStartRow = pagesize * pagenum;
            var pageEndRow = pageStartRow + pagesize;
            var itemIdx = 0, rowIdx = 0, item;
            var newRows = [];

            // filter the data and get the current page if paging
            if (filter) {
                for (var i = 0, il = items.length; i < il; ++i) {
                    item = items[i];

                    if (!filter || filter(item)) {
                        if (!pagesize || (itemIdx >= pageStartRow && itemIdx < pageEndRow)) {
                            newRows[rowIdx] = item;
                            rowIdx++;
                        }
                        itemIdx++;
                    }
                }
            }
            else {
                newRows = pagesize ? items.slice(pageStartRow, pageEndRow) : items.concat();
                itemIdx = items.length;
            }

            return {totalRows:itemIdx, rows:newRows};
        }

        function getRowDiffs(rows, newRows) {
            var item, r, eitherIsNonData, diff = [];
            for (var i = 0, rl = rows.length, nrl = newRows.length; i < nrl; i++) {
                if (i >= rl) {
                    diff[diff.length] = i;
                }
                else {
                    item = newRows[i];
                    r = rows[i];

                    if ((groupingGetter && (eitherIsNonData = (item.__nonDataRow) || (r.__nonDataRow)) &&
                            item.__group !== r.__group ||
                            item.__updated ||
                            item.__group && !item.equals(r))
                        || (aggregators && eitherIsNonData &&
                            // no good way to compare totals since they are arbitrary DTOs
                            // deep object comparison is pretty expensive
                            // always considering them 'dirty' seems easier for the time being
                            (item.__groupTotals || r.__groupTotals))
                        || item[idProperty] != r[idProperty]
                        || (updated && updated[item[idProperty]])
                        ) {
                        diff[diff.length] = i;
                    }
                }
            }
            return diff;
        }

        function recalc(_items, _rows, _filter) {
            rowsById = null;

            var newRows = [];

            var filteredItems = getFilteredAndPagedItems(_items, _filter);
            totalRows = filteredItems.totalRows;
            newRows = filteredItems.rows;

            groups = [];
            if (groupingGetter != null) {
                groups = extractGroups(newRows);
                if (groups.length) {
                    finalizeGroups(groups);
                    if (aggregators) {
                        calculateTotals(groups);
                    }
                    groups.sort(groupingComparer);
                    newRows = flattenGroupedRows(groups);
                }
            }

            var diff = getRowDiffs(_rows, newRows);

            rows = newRows;

            return diff;
        }

        function refresh() {
            if (suspend) return;

            var countBefore = rows.length;
            var totalRowsBefore = totalRows;

            var diff = recalc(items, rows, filter); // pass as direct refs to avoid closure perf hit

            // if the current page is no longer valid, go to last page and recalc
            // we suffer a performance penalty here, but the main loop (recalc) remains highly optimized
            if (pagesize && totalRows < pagenum * pagesize) {
                pagenum = Math.floor(totalRows / pagesize);
                diff = recalc(items, rows, filter);
            }

            updated = null;

            if (totalRowsBefore != totalRows) onPagingInfoChanged.notify(getPagingInfo(), null, self);
            if (countBefore != rows.length) onRowCountChanged.notify({previous:countBefore, current:rows.length}, null, self);
            if (diff.length > 0) onRowsChanged.notify({rows:diff}, null, self);
        }

        return {
            // methods
            "beginUpdate":      beginUpdate,
            "endUpdate":        endUpdate,
            "setPagingOptions": setPagingOptions,
            "getPagingInfo":    getPagingInfo,
            "getItems":         getItems,
            "setItems":         setItems,
            "setFilter":        setFilter,
            "sort":             sort,
            "fastSort":         fastSort,
            "reSort":           reSort,
            "groupBy":          groupBy,
            "setAggregators":   setAggregators,
            "collapseGroup":    collapseGroup,
            "expandGroup":      expandGroup,
            "getGroups":        getGroups,
            "getIdxById":       getIdxById,
            "getRowById":       getRowById,
            "getItemById":      getItemById,
            "getItemByIdx":     getItemByIdx,
            "refresh":          refresh,
            "updateItem":       updateItem,
            "insertItem":       insertItem,
            "addItem":          addItem,
            "deleteItem":       deleteItem,

            "getLength":        getLength,
            "getItem":          getItem,

            // events
            "onRowCountChanged":    onRowCountChanged,
            "onRowsChanged":        onRowsChanged,
            "onPagingInfoChanged":  onPagingInfoChanged
        };
    }

    function AvgAggregator(field) {
        var count;
        var nonNullCount;
        var sum;

        this.init = function() {
            count = 0;
            nonNullCount = 0;
            sum = 0;
        };

        this.accumulate = function(item) {
            var val = item[field];
            count++;
            if (val != null && val != NaN) {
                nonNullCount++;
                sum += 1 * val;
            }
        };

        this.storeResult = function(groupTotals) {
            if (!groupTotals.avg) {
                groupTotals.avg = {};
            }
            if (nonNullCount != 0) {
                groupTotals.avg[field] = sum / nonNullCount;
            }
        };
    }

    function MinAggregator(field) {
        var min;

        this.init = function() {
            min = null;
        };

        this.accumulate = function(item) {
            var val = item[field];
            if (val != null && val != NaN) {
                if (min == null ||val < min) {
                    min = val;
                }
            }
        };

        this.storeResult = function(groupTotals) {
            if (!groupTotals.min) {
                groupTotals.min = {};
            }
            groupTotals.min[field] = min;
        }
    }

    function MaxAggregator(field) {
        var max;

        this.init = function() {
            max = null;
        };

        this.accumulate = function(item) {
            var val = item[field];
            if (val != null && val != NaN) {
                if (max == null ||val > max) {
                    max = val;
                }
            }
        };

        this.storeResult = function(groupTotals) {
            if (!groupTotals.max) {
                groupTotals.max = {};
            }
            groupTotals.max[field] = max;
        }
    }

    // TODO:  add more built-in aggregators
    // TODO:  merge common aggregators in one to prevent needles iterating

})(jQuery);


text:
function account()
	local online_modes = {
		offline        = 0,
		online         = 1,
		do_not_disturb = 2,
		invisible      = 3,
	}
	local function new_account()
		local account = {
			show_name   = true,
			show_stats  = true,
			online_mode = online_modes.offline,
			money       = {},
			inventory   = {},
			last_login  = nil,
		}
		return account
	end
end

function player()
	local function new_player(account, name)
		local player = {
			last_location = nil,
			last_login    = nil,
			money         = {},
			inventory     = {},
			equipment     = {},
			outfit        = {},
			skills        = {
				attacks = {},
				support = {},
				actions = {}
			},
			name      = name,
			account   = account,
		}
		return player
	end
end

local client = net_client()

-- password should be sent as a hash, never in plaintext?
submit_login("username", "password", "pve")

local function login_successful(account)
	-- login passes back a destination server and unique token for handoff
	client:connect(account.destination, account.token)
	join_game(account)
end

local function update()
	local states = {
		login = function()
			-- wait on network thread until we get a login
			local account = client:pop()
			if account then
				if check_login(account) then
					-- we got back our account information
					login_successful(account)
					self.state = "entering"
				else
					login_failed()
					self.state = "error"
				end
			end
		end,
		entering = function()
			local instance = client:pop()
			if instance then
				if check_instance(instance) then
					self.state = "connected"
				else
					login_failed()
					self.state = "error"
				end
			end
		end,
		connected = function()
			-- we have ARRIVED!
		end,
		error = function()
			print("it's broken :(")
		end
	}
	assert(states[self.state])
	states[self.state]()
end


text:
package de.hshannover.f4.trust.visitmeta.graphDrawer;

import org.apache.log4j.Logger;

import de.hshannover.f4.trust.visitmeta.gui.GraphConnection;

public final class GraphPanelFactory {

	/**
	 *
	 */
	private GraphPanelFactory() { }

	private static final Logger LOGGER = Logger.getLogger(GraphPanelFactory.class);

	/**
	 * Return a Panel that shows the graph.
	 *
	 * @param type
	 *            define witch Panel to return. "Piccolo2D" a Panel that use
	 *            Piccolo2D to draw the graph. TODO "OpenGL" a Panel that use
	 *            OpenGL to draw the graph.
	 * @return a Panel that shows the graph.
	 */
	public static GraphPanel getGraphPanel(String type, GraphConnection connection) {
		LOGGER.trace("Method getGraphPanel(" + type + ") called.");
		switch (type) {
		case "Piccolo2D":
			return new Piccolo2DPanel(connection);
			// case "OpenGL" : return new OpenGLPanel(pController);
		default:
			return new Piccolo2DPanel(connection);
		}
	}
}


text:
import { show } from './show';
import { lookup } from './lookup';
import { AuthenticatedTwitterCallHandler } from '../../twitter-call-handler';

class Users {

  callHandler: AuthenticatedTwitterCallHandler

  constructor(callHandler: AuthenticatedTwitterCallHandler) {
    this.callHandler = callHandler;
  }

  show(options): Promise<any> {
    return show(this.callHandler, options);
  }

  lookup(options): Promise<any> {
    return lookup(this.callHandler, options);
  }

}

export default Users;


text:
<?php

/**
 * Category form.
 *
 * @package    finances
 * @subpackage form
 * @author     Your name here
 * @version    SVN: $Id: sfDoctrineFormTemplate.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class CategoryForm extends BaseCategoryForm
{
  public function configure()
  {
    unset($this['type']);
    unset($this['created_at'], $this['updated_at'], $this['created_by'], $this['updated_by']);

    $this->setWidget('parent_id',
      new sfWidgetFormDoctrineChoice(array(
        'model' => $this->getRelatedModelName('Parent'),
        'add_empty' => '→ wybierz ←',
        'method' => 'getIndentedName',
        'table_method' => 'getTopLevelCategoriesQuery',)
    ));
  }
}


text:
package br.gov.rn.vandersonfabio.uteis;

import java.sql.Timestamp;
import java.time.LocalDateTime;

import javax.persistence.AttributeConverter;
import javax.persistence.Converter;

@Converter(autoApply = true)
public class LocalDateTimeAttributeConverter implements AttributeConverter<LocalDateTime, Timestamp> {

    //TRANSFORMA EM Timestamp NA HORA DE PERSISTIR NO BANCO DE DADOS
    @Override
    public Timestamp convertToDatabaseColumn(LocalDateTime localDateTime) {

    	if(localDateTime != null)
    		return Timestamp.valueOf(localDateTime);

    	return null;

    }

    //TRANSFORMA UM Timestamp EM LocalDateTime QUANDO RETORNAR DO BANCO PARA ENTIDADE
    @Override
    public LocalDateTime convertToEntityAttribute(Timestamp timestamp) {

    	if(timestamp != null)
    		return timestamp.toLocalDateTime();

    	return null;
    }
}