text:
// .\Release\x64\benchmarks.exe --benchmark_repetitions=3 --benchmark_filter=Planetarium  // NOLINT(whitespace/line_length)

#include "ksp_plugin/planetarium.hpp"

#include <algorithm>

#include "astronomy/time_scales.hpp"
#include "base/status_utilities.hpp"
#include "benchmark/benchmark.h"
#include "physics/body_centred_non_rotating_dynamic_frame.hpp"
#include "physics/discrete_trajectory.hpp"
#include "physics/solar_system.hpp"
#include "testing_utilities/solar_system_factory.hpp"

namespace principia {
namespace geometry {

using astronomy::operator""_UT1;
using astronomy::operator""_TT;
using base::make_not_null_unique;
using base::not_null;
using geometry::Bivector;
using geometry::DeduceSignReversingOrientation;
using geometry::Perspective;
using geometry::RigidTransformation;
using geometry::RP2Lines;
using geometry::Signature;
using geometry::Vector;
using geometry::Velocity;
using integrators::SymmetricLinearMultistepIntegrator;
using integrators::methods::Quinlan1999Order8A;
using integrators::methods::QuinlanTremaine1990Order12;
using ksp_plugin::Camera;
using ksp_plugin::Barycentric;
using ksp_plugin::Navigation;
using ksp_plugin::NavigationFrame;
using ksp_plugin::Planetarium;
using ksp_plugin::ScaledSpacePoint;
using ksp_plugin::World;
using physics::BodyCentredNonRotatingDynamicFrame;
using physics::DegreesOfFreedom;
using physics::DiscreteTrajectory;
using physics::Ephemeris;
using physics::KeplerianElements;
using physics::KeplerOrbit;
using physics::MassiveBody;
using physics::MasslessBody;
using physics::SolarSystem;
using quantities::Angle;
using quantities::Cos;
using quantities::Infinity;
using quantities::Length;
using quantities::Sin;
using quantities::Time;
using quantities::si::ArcMinute;
using quantities::si::Day;
using quantities::si::Degree;
using quantities::si::Kilo;
using quantities::si::Metre;
using quantities::si::Milli;
using quantities::si::Minute;
using quantities::si::Radian;
using quantities::si::Second;
using testing_utilities::SolarSystemFactory;

namespace {

constexpr Length near = 40'000 * Kilo(Metre);
constexpr Length far = 400'000 * Kilo(Metre);
constexpr Length focal = 1 * Metre;

Perspective<Navigation, Camera> PolarPerspective(
    Length const distance_from_earth) {
  using LeftNavigation =
      Frame<enum class LeftNavigationTag, Arbitrary, Handedness::Left>;
  return {
      RigidTransformation<Navigation, Camera>(
          Navigation::origin + Displacement<Navigation>(
                                   {0 * Metre, 0 * Metre, distance_from_earth}),
          Camera::origin,
          Rotation<LeftNavigation, Camera>(
              Vector<double, LeftNavigation>({1, 0, 0}),
              Vector<double, LeftNavigation>({0, -1, 0}),
              Bivector<double, LeftNavigation>({0, 0, -1}))
              .Forget<OrthogonalMap>() *
          Signature<Navigation, LeftNavigation>(
              Sign::Positive(),
              Sign::Positive(),
              DeduceSignReversingOrientation{}).Forget<OrthogonalMap>()),
      focal};
}

Perspective<Navigation, Camera> EquatorialPerspective(
    Length const distance_from_earth) {
  using LeftNavigation =
      Frame<enum class LeftNavigationTag, Arbitrary, Handedness::Left>;
  return {
      RigidTransformation<Navigation, Camera>(
          Navigation::origin + Displacement<Navigation>(
                                   {0 * Metre, distance_from_earth, 0 * Metre}),
          Camera::origin,
          Rotation<LeftNavigation, Camera>(
              Vector<double, LeftNavigation>({1, 0, 0}),
              Vector<double, LeftNavigation>({0, 0, 1}),
              Bivector<double, LeftNavigation>({0, -1, 0}))
              .Forget<OrthogonalMap>() *
          Signature<Navigation, LeftNavigation>(
              Sign::Positive(),
              Sign::Positive(),
              DeduceSignReversingOrientation{}).Forget<OrthogonalMap>()),
      focal};
}

class Satellites {
 public:
  Satellites()
      : solar_system_(make_not_null_unique<SolarSystem<Barycentric>>(
            SOLUTION_DIR / "astronomy" / "sol_gravity_model.proto.txt",
            SOLUTION_DIR / "astronomy" /
                "sol_initial_state_jd_2451545_000000000.proto.txt",
            /*ignore_frame=*/true)),
        ephemeris_(solar_system_->MakeEphemeris(
            /*accuracy_parameters=*/{/*fitting_tolerance=*/1 * Milli(Metre),
                                     /*geopotential_tolerance=*/0x1p-24},
            EphemerisParameters())),
        earth_(solar_system_->massive_body(
            *ephemeris_,
            SolarSystemFactory::name(SolarSystemFactory::Earth))),
        earth_centred_inertial_(
            make_not_null_unique<
                BodyCentredNonRotatingDynamicFrame<Barycentric, Navigation>>(
                ephemeris_.get(),
                earth_)) {
    // Two-line elements for GOES-8:
    // 1 23051U 94022A   00004.06628221 -.00000243  00000-0  00000-0 0  9630
    // 2 23051   0.4232  97.7420 0004776 192.8349 121.5613  1.00264613 28364
    constexpr Instant goes_8_epoch = "JD2451548.56628221"_UT1;
    KeplerianElements<Barycentric> goes_8_elements;
    goes_8_elements.inclination = 0.4232 * Degree;
    goes_8_elements.longitude_of_ascending_node = 97.7420 * Degree;
    goes_8_elements.eccentricity = 0.0004776;
    goes_8_elements.argument_of_periapsis = 192.8349 * Degree;
    goes_8_elements.mean_anomaly = 121.5613 * Degree;
    goes_8_elements.mean_motion = 1.00264613 * (2 * π * Radian / Day);

    CHECK_OK(ephemeris_->Prolong(goes_8_epoch));
    KeplerOrbit<Barycentric> const goes_8_orbit(
        *earth_, MasslessBody{}, goes_8_elements, goes_8_epoch);
    CHECK_OK(goes_8_trajectory_.Append(
        goes_8_epoch,
        ephemeris_->trajectory(earth_)->EvaluateDegreesOfFreedom(goes_8_epoch) +
            goes_8_orbit.StateVectors(goes_8_epoch)));
    auto goes_8_instance = ephemeris_->NewInstance(
        {&goes_8_trajectory_},
        Ephemeris<Barycentric>::NoIntrinsicAccelerations,
        HistoryParameters());
    CHECK_OK(ephemeris_->FlowWithFixedStep(goes_8_epoch + 100 * Day,
                                           *goes_8_instance));
  }

  DiscreteTrajectory<Barycentric> const& goes_8_trajectory() const {
    return goes_8_trajectory_;
  }

  Planetarium MakePlanetarium(
      Perspective<Navigation, Camera> const& perspective) const {
    // No dark area, human visual acuity, wide field of view.
    Planetarium::Parameters parameters(
        /*sphere_radius_multiplier=*/1,
        /*angular_resolution=*/0.4 * ArcMinute,
        /*field_of_view=*/90 * Degree);
    return Planetarium(parameters,
                       perspective,
                       ephemeris_.get(),
                       earth_centred_inertial_.get(),
        [](Position<Navigation> const& plotted_point) {
          constexpr auto inverse_scale_factor = 1 / (6000 * Metre);
          return ScaledSpacePoint::FromCoordinates(
              ((plotted_point - Navigation::origin) *
               inverse_scale_factor).coordinates());
        });
  }

 private:
  Ephemeris<Barycentric>::FixedStepParameters EphemerisParameters() {
    return Ephemeris<Barycentric>::FixedStepParameters(
        SymmetricLinearMultistepIntegrator<QuinlanTremaine1990Order12,
                                           Position<Barycentric>>(),
        /*step=*/10 * Minute);
  }

  Ephemeris<Barycentric>::FixedStepParameters HistoryParameters() {
    return Ephemeris<Barycentric>::FixedStepParameters(
        SymmetricLinearMultistepIntegrator<Quinlan1999Order8A,
                                           Position<Barycentric>>(),
        /*step=*/10 * Second);
  }

  not_null<std::unique_ptr<SolarSystem<Barycentric>>> const solar_system_;
  not_null<std::unique_ptr<Ephemeris<Barycentric>>> const ephemeris_;
  not_null<MassiveBody const*> const earth_;
  not_null<std::unique_ptr<NavigationFrame>> const earth_centred_inertial_;
  DiscreteTrajectory<Barycentric> goes_8_trajectory_;
};

}  // namespace

void RunBenchmark(benchmark::State& state,
                  Perspective<Navigation, Camera> const& perspective) {
  Satellites satellites;
  Planetarium planetarium = satellites.MakePlanetarium(perspective);
  RP2Lines<Length, Camera> lines;
  int total_lines = 0;
  int iterations = 0;
  // This is the time of a lunar eclipse in January 2000.
  constexpr Instant now = "2000-01-21T04:41:30,5"_TT;
  for (auto _ : state) {
    lines = planetarium.PlotMethod2(satellites.goes_8_trajectory(),
                                    satellites.goes_8_trajectory().begin(),
                                    satellites.goes_8_trajectory().end(),
                                    now,
                                    /*reverse=*/false);
    total_lines += lines.size();
    ++iterations;
  }
  Length min_x = Infinity<Length>;
  Length min_y = Infinity<Length>;
  Length max_x = -Infinity<Length>;
  Length max_y = -Infinity<Length>;
  int points = 0;
  for (auto const& line : lines) {
    points += line.size();
    for (auto const& point : line) {
      min_x = std::min(min_x, point.x());
      min_y = std::min(min_y, point.y());
      max_x = std::max(max_x, point.x());
      max_y = std::max(max_y, point.y());
    }
  }
  state.SetLabel(std::to_string(points) + " points in " +
                 std::to_string(total_lines / iterations) + " lines within [" +
                 DebugString(min_x) + ", " + DebugString(max_x) + "] × [" +
                 DebugString(min_y) + ", " + DebugString(max_y) + "]");
}

void BM_PlanetariumPlotMethod2NearPolarPerspective(benchmark::State& state) {
  RunBenchmark(state, PolarPerspective(near));
}

void BM_PlanetariumPlotMethod2FarPolarPerspective(benchmark::State& state) {
  RunBenchmark(state, PolarPerspective(far));
}

void BM_PlanetariumPlotMethod2NearEquatorialPerspective(
    benchmark::State& state) {
  RunBenchmark(state, EquatorialPerspective(near));
}

void BM_PlanetariumPlotMethod2FarEquatorialPerspective(
    benchmark::State& state) {
  RunBenchmark(state, EquatorialPerspective(far));
}

BENCHMARK(BM_PlanetariumPlotMethod2NearPolarPerspective)
    ->Unit(benchmark::kMillisecond);
BENCHMARK(BM_PlanetariumPlotMethod2FarPolarPerspective)
    ->Unit(benchmark::kMillisecond);
BENCHMARK(BM_PlanetariumPlotMethod2NearEquatorialPerspective)
    ->Unit(benchmark::kMillisecond);
BENCHMARK(BM_PlanetariumPlotMethod2FarEquatorialPerspective)
    ->Unit(benchmark::kMillisecond);

}  // namespace geometry
}  // namespace principia


text:
import React, { Component } from 'react';
import {
  StyleSheet,
  Text,
  View,
  Image,
  ScrollView
} from 'react-native';

var Dimensions = require('Dimensions');
var {width, height} = Dimensions.get('window')

import HomeTopListView from './hometoplistview'

var HomeTopMenu = React.createClass({

    getDefaultProps(){
        return {
            data: []
        }
    },

    getInitialState(){
        return {
            selectedIndicator: 0
        }
    },

    render(){
        return (
            <View style={styles.container}>
                <ScrollView
                    pagingEnabled={true}
                    showHorizontalScrollIndicator={false}
                    horizontal={true}
                    onMomentumScrollEnd={this.pageScrollEnd}
                >
                    {this.renderScrollItem()}
                </ScrollView>
                <View style={styles.bottomViewStyle}>
                    {this.renderIndicatorItem()}
                </View>
            </View>
        )
    },

    pageScrollEnd(e){
        var offsetX = e.nativeEvent.contentOffset.x;
        var currentPage = Math.round(offsetX / width);
        this.setState({
            selectedIndicator: currentPage
        })
    },

    renderIndicatorItem(){
        var itemArr = [], style;
        for (var i = 0; i < 2; i++) {
            style = this.state.selectedIndicator === i ? {color: 'orange'} : {color: 'gray'}
            itemArr.push(
                <Text key={i} style={[{fontSize: 25}, style]}>•</Text>
            )
        }
        return itemArr
    },

    renderScrollItem(){
        var dataArr = this.props.data;
        var itemArr = [];
        for (var i = 0; i < dataArr.length; i++) {
            itemArr.push(
                <HomeTopListView data={dataArr[i]} key={i}/>
            );
        }
        return itemArr
    }
});

const styles = StyleSheet.create({
    container: {
        backgroundColor: 'white'
    },
    bottomViewStyle: {
        flexDirection: 'row',
        justifyContent: 'center'
    }
});

module.exports = HomeTopMenu

redpajama_set_name: RedPajamaGithub


text:
using namespace clang::ast_matchers;

namespace clang {
namespace tidy {
namespace google {
namespace build {

UnnamedNamespaceInHeaderCheck::UnnamedNamespaceInHeaderCheck(
    StringRef Name, ClangTidyContext *Context)
    : ClangTidyCheck(Name, Context),
      RawStringHeaderFileExtensions(Options.getLocalOrGlobal(
          "HeaderFileExtensions", utils::defaultHeaderFileExtensions())) {
  if (!utils::parseHeaderFileExtensions(RawStringHeaderFileExtensions,
                                        HeaderFileExtensions, ',')) {
    llvm::errs() << "Invalid header file extension: "
                 << RawStringHeaderFileExtensions << "\n";
  }
}

void UnnamedNamespaceInHeaderCheck::storeOptions(
    ClangTidyOptions::OptionMap &Opts) {
  Options.store(Opts, "HeaderFileExtensions", RawStringHeaderFileExtensions);
}

void UnnamedNamespaceInHeaderCheck::registerMatchers(
    ast_matchers::MatchFinder *Finder) {
  // Only register the matchers for C++; the functionality currently does not
  // provide any benefit to other languages, despite being benign.
  if (getLangOpts().CPlusPlus)
    Finder->addMatcher(namespaceDecl(isAnonymous()).bind("anonymousNamespace"),
                       this);
}

void UnnamedNamespaceInHeaderCheck::check(
    const MatchFinder::MatchResult &Result) {
  const auto *N = Result.Nodes.getNodeAs<NamespaceDecl>("anonymousNamespace");
  SourceLocation Loc = N->getBeginLoc();
  if (!Loc.isValid())
    return;

  if (utils::isPresumedLocInHeaderFile(Loc, *Result.SourceManager,
                                       HeaderFileExtensions))
    diag(Loc, "do not use unnamed namespaces in header files");
}

} // namespace build
} // namespace google
} // namespace tidy
} // namespace clang


text:
this.state.value -= parseInt(request.params.value, 0);
request.result = this.state.value;


text:
openlayers-mongo-sinatra
========================

A bare bones web application for editing points of interest on an OpenLayers map. It is backed by a Sinatra API that persists data to MongoDB.


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

var ridRegExp = /^#[0-9]+:[0-9]+$/;

exports.isRid = function(value)
{
  return typeof value === 'string' && ridRegExp.test(value);
};

/**
 * @param {Object} document
 * @param {Boolean=true} inArray
 * @return {Object}
 */
exports.toJSON = function(document, inArray)
{
  if (typeof inArray === 'undefined')
  {
    inArray = true;
  }

  if (typeof document.rid === 'string')
  {
    document.id = document.rid;
    document.rid = undefined;
  }
  else
  {
    document.id = document['@rid'];
  }

  for (var property in document)
  {
    if (!document.hasOwnProperty(property))
    {
      continue;
    }

    if (property[0] === '@')
    {
      document[property] = undefined;

      continue;
    }

    document[property] = convertValueToJSON(document[property], inArray);
  }

  return document;
};

/**
 * @private
 * @param {*} value
 * @param {Boolean} inArray
 * @return {*}
 */
function convertValueToJSON(value, inArray)
{
  var type = typeof value;

  if (type === 'string' && ridRegExp.test(value))
  {
    return value.substr(1);
  }

  if (value !== null && type === 'object')
  {
    return exports.toJSON(value, inArray);
  }

  if (inArray && Array.isArray(value))
  {
    for (var i = 0, l = value.length; i < l; ++i)
    {
      value[i] = convertValueToJSON(value[i]);
    }
  }

  return value;
}


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>org.gardler.biglittlechallenge</groupId>
	<artifactId>trials-player</artifactId>
	<version>${trials.version}</version>
	<packaging>jar</packaging>

	<name>trials-player</name>
	<url>http://maven.apache.org</url>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<slf4j.version>1.7.21</slf4j.version>
		<trials.version>0.0.1-SNAPSHOT</trials.version>
		<log4j.version>2.7</log4j.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.gardler.biglittlechallenge</groupId>
			<artifactId>trials-model</artifactId>
			<version>${trials.version}</version>
		</dependency>
		<dependency>
			<groupId>org.gardler.biglittlechallenge</groupId>
			<artifactId>trials-ai</artifactId>
			<version>${trials.version}</version>
		</dependency>
		<dependency>
			<groupId>javax.ws.rs</groupId>
			<artifactId>javax.ws.rs-api</artifactId>
			<version>2.1-m01</version>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
			<version>${slf4j.version}</version>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-log4j12</artifactId>
			<version>${slf4j.version}</version>
		</dependency>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.9</version>
			<scope>test</scope>
		</dependency>
	</dependencies>
</project>


text:
"""
This file is part of the web2py Web Framework
Copyrighted by Massimo Di Pierro <mdipierro@cs.depaul.edu>
License: LGPLv3 (http://www.gnu.org/licenses/lgpl.html)

Basic caching classes and methods
=================================

- Cache - The generic caching object interfacing with the others
- CacheInRam - providing caching in ram
- CacheOnDisk - provides caches on disk

Memcache is also available via a different module (see gluon.contrib.memcache)

When web2py is running on Google App Engine,
caching will be provided by the GAE memcache
(see gluon.contrib.gae_memcache)
"""
import traceback
import time
import portalocker
import shelve
import thread
import os
import logging
import re
try:
    import settings
    have_settings = True
except ImportError:
    have_settings = False

logger = logging.getLogger("web2py.cache")

__all__ = ['Cache', 'lazy_cache']

DEFAULT_TIME_EXPIRE = 300

class CacheAbstract(object):
    """
    Abstract class for cache implementations.
    Main function is now to provide referenced api documentation.

    Use CacheInRam or CacheOnDisk instead which are derived from this class.

    Attentions, Michele says:

    There are signatures inside gdbm files that are used directly
    by the python gdbm adapter that often are lagging behind in the
    detection code in python part.
    On every occasion that a gdbm store is probed by the python adapter,
    the probe fails, because gdbm file version is newer.
    Using gdbm directly from C would work, because there is backward
    compatibility, but not from python!
    The .shelve file is discarded and a new one created (with new
    signature) and it works until it is probed again...
    The possible consequences are memory leaks and broken sessions.
    """

    cache_stats_name = 'web2py_cache_statistics'

    def __init__(self, request=None):
        """
        Paremeters
        ----------
        request:
            the global request object
        """
        raise NotImplementedError

    def __call__(self, key, f,
                 time_expire=DEFAULT_TIME_EXPIRE):
        """
        Tries retrieve the value corresponding to `key` from the cache of the
        object exists and if it did not expire, else it called the function `f`
        and stores the output in the cache corresponding to `key`. In the case
        the output of the function is returned.

        :param key: the key of the object to be store or retrieved
        :param f: the function, whose output is to be cached
        :param time_expire: expiration of the cache in microseconds

        - `time_expire` is used to compare the current time with the time when
            the requested object was last saved in cache. It does not affect
            future requests.
        - Setting `time_expire` to 0 or negative value forces the cache to
            refresh.

        If the function `f` is `None` the cache is cleared.
        """
        raise NotImplementedError

    def clear(self, regex=None):
        """
        Clears the cache of all keys that match the provided regular expression.
        If no regular expression is provided, it clears all entries in cache.

        Parameters
        ----------
        regex:
            if provided, only keys matching the regex will be cleared.
            Otherwise all keys are cleared.
        """

        raise NotImplementedError

    def increment(self, key, value=1):
        """
        Increments the cached value for the given key by the amount in value

        Parameters
        ----------
        key:
            key for the cached object to be incremeneted
        value:
            amount of the increment (defaults to 1, can be negative)
        """
        raise NotImplementedError

    def _clear(self, storage, regex):
        """
        Auxiliary function called by `clear` to search and clear cache entries
        """
        r = re.compile(regex)
        for (key, value) in storage.items():
            if r.match(str(key)):
                del storage[key]

class CacheInRam(CacheAbstract):
    """
    Ram based caching

    This is implemented as global (per process, shared by all threads)
    dictionary.
    A mutex-lock mechanism avoid conflicts.
    """

    locker = thread.allocate_lock()
    meta_storage = {}

    def __init__(self, request=None):
        self.initialized = False
        self.request = request

    def initialize(self):
        if self.initialized:
            return
        else:
            self.initialized = True
        self.locker.acquire()
        request = self.request
        if request:
            app = request.application
        else:
            app = ''
        if not app in self.meta_storage:
            self.storage = self.meta_storage[app] = {
                CacheAbstract.cache_stats_name: {'hit_total': 0, 'misses': 0}}
        else:
            self.storage = self.meta_storage[app]
        self.locker.release()

    def clear(self, regex=None):
        self.initialize()
        self.locker.acquire()
        storage = self.storage
        if regex is None:
            storage.clear()
        else:
            self._clear(storage, regex)

        if not CacheAbstract.cache_stats_name in storage.keys():
            storage[CacheAbstract.cache_stats_name] = {
                'hit_total': 0, 'misses': 0}

        self.locker.release()

    def __call__(self, key, f,
                 time_expire=DEFAULT_TIME_EXPIRE,
                 destroyer=None):
        """
        Attention! cache.ram does not copy the cached object. It just stores a reference to it.
        Turns out the deepcopying the object has some problems:
        1) would break backward compatibility
        2) would be limiting because people may want to cache live objects
        3) would work unless we deepcopy no storage and retrival which would make things slow.
        Anyway. You can deepcopy explicitly in the function generating the value to be cached.
        """
        self.initialize()

        dt = time_expire
        now = time.time()

        self.locker.acquire()
        item = self.storage.get(key, None)
        if item and f is None:
            del self.storage[key]
            if destroyer:
                destroyer(item[1])
        self.storage[CacheAbstract.cache_stats_name]['hit_total'] += 1
        self.locker.release()

        if f is None:
            return None
        if item and (dt is None or item[0] > now - dt):
            return item[1]
        elif item and (item[0] < now - dt) and destroyer:
            destroyer(item[1])
        value = f()

        self.locker.acquire()
        self.storage[key] = (now, value)
        self.storage[CacheAbstract.cache_stats_name]['misses'] += 1
        self.locker.release()
        return value

    def increment(self, key, value=1):
        self.initialize()
        self.locker.acquire()
        try:
            if key in self.storage:
                value = self.storage[key][1] + value
            self.storage[key] = (time.time(), value)
        except BaseException, e:
            self.locker.release()
            raise e
        self.locker.release()
        return value

class CacheOnDisk(CacheAbstract):
    """
    Disk based cache

    This is implemented as a shelve object and it is shared by multiple web2py
    processes (and threads) as long as they share the same filesystem.
    The file is locked wen accessed.

    Disk cache provides persistance when web2py is started/stopped but it slower
    than `CacheInRam`

    Values stored in disk cache must be pickable.
    """

    def _close_shelve_and_unlock(self):
        try:
            if self.storage:
                self.storage.close()
        finally:
            if self.locker and self.locked:
                portalocker.unlock(self.locker)
                self.locker.close()
                self.locked = False

    def _open_shelve_and_lock(self):
        """Open and return a shelf object, obtaining an exclusive lock
        on self.locker first. Replaces the close method of the
        returned shelf instance with one that releases the lock upon
        closing."""

        storage = None
        locker = None
        locked = False
        try:
            locker = locker = open(self.locker_name, 'a')
            portalocker.lock(locker, portalocker.LOCK_EX)
            locked = True
            try:
                storage = shelve.open(self.shelve_name)
            except:
                logger.error('corrupted cache file %s, will try rebuild it'
                             % (self.shelve_name))
                storage = None
            if not storage and os.path.exists(self.shelve_name):
                os.unlink(self.shelve_name)
                storage = shelve.open(self.shelve_name)
            if not CacheAbstract.cache_stats_name in storage.keys():
                storage[CacheAbstract.cache_stats_name] = {
                    'hit_total': 0, 'misses': 0}
            storage.sync()
        except Exception, e:
            if storage:
                storage.close()
                storage = None
            if locked:
                portalocker.unlock(locker)
                locker.close()
            locked = False
            raise RuntimeError(
                'unable to create/re-create cache file %s' % self.shelve_name)
        self.locker = locker
        self.locked = locked
        self.storage = storage
        return storage

    def __init__(self, request=None, folder=None):
        self.initialized = False
        self.request = request
        self.folder = folder

    def initialize(self):
        if self.initialized:
            return
        else:
            self.initialized = True
        folder = self.folder
        request = self.request

        # Lets test if the cache folder exists, if not
        # we are going to create it
        folder = folder or os.path.join(request.folder, 'cache')

        if not os.path.exists(folder):
            os.mkdir(folder)

        ### we need this because of a possible bug in shelve that may
        ### or may not lock
        self.locker_name = os.path.join(folder, 'cache.lock')
        self.shelve_name = os.path.join(folder, 'cache.shelve')

    def clear(self, regex=None):
        self.initialize()
        storage = self._open_shelve_and_lock()
        try:
            if regex is None:
                storage.clear()
            else:
                self._clear(storage, regex)
            storage.sync()
        finally:
            self._close_shelve_and_unlock()

    def __call__(self, key, f,
                 time_expire=DEFAULT_TIME_EXPIRE):
        self.initialize()
        dt = time_expire
        storage = self._open_shelve_and_lock()
        try:
            item = storage.get(key, None)
            storage[CacheAbstract.cache_stats_name]['hit_total'] += 1
            if item and f is None:
                del storage[key]
                storage.sync()
            now = time.time()
            if f is None:
                value = None
            elif item and (dt is None or item[0] > now - dt):
                value = item[1]
            else:
                value = f()
                storage[key] = (now, value)
                storage[CacheAbstract.cache_stats_name]['misses'] += 1
                storage.sync()
        finally:
            self._close_shelve_and_unlock()

        return value

    def increment(self, key, value=1):
        self.initialize()
        storage = self._open_shelve_and_lock()
        try:
            if key in storage:
                value = storage[key][1] + value
            storage[key] = (time.time(), value)
            storage.sync()
        finally:
            self._close_shelve_and_unlock()
        return value

class CacheAction(object):
    def __init__(self, func, key, time_expire, cache, cache_model):
        self.__name__ = func.__name__
        self.__doc__ = func.__doc__
        self.func = func
        self.key = key
        self.time_expire = time_expire
        self.cache = cache
        self.cache_model = cache_model

    def __call__(self, *a, **b):
        if not self.key:
            key2 = self.__name__ + ':' + repr(a) + ':' + repr(b)
        else:
            key2 = self.key.replace('%(name)s', self.__name__)\
                .replace('%(args)s', str(a)).replace('%(vars)s', str(b))
        cache_model = self.cache_model
        if not cache_model or isinstance(cache_model, str):
            cache_model = getattr(self.cache, cache_model or 'ram')
        return cache_model(key2,
                           lambda a=a, b=b: self.func(*a, **b),
                           self.time_expire)

class Cache(object):
    """
    Sets up generic caching, creating an instance of both CacheInRam and
    CacheOnDisk.
    In case of GAE will make use of gluon.contrib.gae_memcache.

    - self.ram is an instance of CacheInRam
    - self.disk is an instance of CacheOnDisk
    """

    autokey = ':%(name)s:%(args)s:%(vars)s'

    def __init__(self, request):
        """
        Parameters
        ----------
        request:
            the global request object
        """
        # GAE will have a special caching
        if have_settings and settings.global_settings.web2py_runtime_gae:
            from contrib.gae_memcache import MemcacheClient
            self.ram = self.disk = MemcacheClient(request)
        else:
            # Otherwise use ram (and try also disk)
            self.ram = CacheInRam(request)
            try:
                self.disk = CacheOnDisk(request)
            except IOError:
                logger.warning('no cache.disk (IOError)')
            except AttributeError:
                # normally not expected anymore, as GAE has already
                # been accounted for
                logger.warning('no cache.disk (AttributeError)')

    def __call__(self,
                 key=None,
                 time_expire=DEFAULT_TIME_EXPIRE,
                 cache_model=None):
        """
        Decorator function that can be used to cache any function/method.

        Example::

            @cache('key', 5000, cache.ram)
            def f():
                return time.ctime()

        When the function f is called, web2py tries to retrieve
        the value corresponding to `key` from the cache of the
        object exists and if it did not expire, else it calles the function `f`
        and stores the output in the cache corresponding to `key`. In the case
        the output of the function is returned.

        :param key: the key of the object to be store or retrieved
        :param time_expire: expiration of the cache in microseconds
        :param cache_model: "ram", "disk", or other
            (like "memcache" if defined). It defaults to "ram".

        Notes
        -----
        `time_expire` is used to compare the curret time with the time when the
        requested object was last saved in cache. It does not affect future
        requests.
        Setting `time_expire` to 0 or negative value forces the cache to
        refresh.

        If the function `f` is an action, we suggest using
        `request.env.path_info` as key.
        """

        def tmp(func, cache=self, cache_model=cache_model):
            return CacheAction(func, key, time_expire, self, cache_model)
        return tmp

    @staticmethod
    def with_prefix(cache_model, prefix):
        """
        allow replacing cache.ram with cache.with_prefix(cache.ram,'prefix')
        it will add prefix to all the cache keys used.
        """
        return lambda key, f, time_expire=DEFAULT_TIME_EXPIRE, prefix=prefix:\
            cache_model(prefix + key, f, time_expire)

def lazy_cache(key=None, time_expire=None, cache_model='ram'):
    """
    can be used to cache any function including in modules,
    as long as the cached function is only called within a web2py request
    if a key is not provided, one is generated from the function name
    the time_expire defaults to None (no cache expiration)
    if cache_model is "ram" then the model is current.cache.ram, etc.
    """
    def decorator(f, key=key, time_expire=time_expire, cache_model=cache_model):
        key = key or repr(f)

        def g(*c, **d):
            from gluon import current
            return current.cache(key, time_expire, cache_model)(f)(*c, **d)
        g.__name__ = f.__name__
        return g
    return decorator


text:
Rails.application.routes.draw do

  devise_for :users, at: 'auth', skip: [:omniauth_callbacks], controllers: { sessions: 'auth/sessions' }

  #################### V1 (default) ##################

  api_version(:module => "V1", :header => {:name => "Accept", :value => "version=1"}, default: true) do
    resources :users
  end

  #################### V2 ##################

  api_version(:module => "V2", :header => {:name => "Accept", :value => "version=2"}) do
    # resources :users
  end

end


text:
#if ENABLED_CUDA

using System;
using System.Collections.Generic;
using System.Text;

namespace OpenCvSharp.Cuda
{
#pragma warning disable 1591

    public enum FeatureSet
    {
        Compute10 = 10,
        Compute11 = 11,
        Compute12 = 12,
        Compute13 = 13,
        Compute20 = 20,
        Compute21 = 21,
        Compute30 = 30,
        Compute35 = 35,

        GlobalAtomics = Compute11,
        SharedAtomics = Compute12,
        NativeDouble = Compute13,
        WarpShuffleFunctions = Compute30,
        DynamicParallelism = Compute35
    }
}

#endif


text:
    static inline int num_cores() {
        SYSTEM_INFO sysinfo;
        GetSystemInfo(&sysinfo);
        return sysinfo.dwNumberOfProcessors;
    }
#else
    #include <unistd.h>
    static inline int num_cores() {
        return (int) sysconf(_SC_NPROCESSORS_ONLN);
    }
#endif

namespace {

class ThreadPool : SkNoncopyable {
public:
    static void Add(SkRunnable* task, int32_t* pending) {
        if (!gGlobal) {  // If we have no threads, run synchronously.
            return task->run();
        }
        gGlobal->add(task, pending);
    }

    static void Wait(int32_t* pending) {
        if (!gGlobal) {  // If we have no threads, the work must already be done.
            SkASSERT(*pending == 0);
            return;
        }
        while (sk_acquire_load(pending) > 0) {  // Pairs with sk_atomic_dec here or in Loop.
            // Lend a hand until our SkTaskGroup of interest is done.
            Work work;
            {
                AutoLock lock(&gGlobal->fReady);
                if (gGlobal->fWork.isEmpty()) {
                    // Someone has picked up all the work (including ours).  How nice of them!
                    // (They may still be working on it, so we can't assert *pending == 0 here.)
                    continue;
                }
                gGlobal->fWork.pop(&work);
            }
            // This Work isn't necessarily part of our SkTaskGroup of interest, but that's fine.
            // We threads gotta stick together.  We're always making forward progress.
            work.task->run();
            sk_atomic_dec(work.pending);  // Release pairs with the sk_acquire_load() just above.
        }
    }

private:
    struct AutoLock {
        AutoLock(SkCondVar* c) : fC(c) { fC->lock(); }
        ~AutoLock() { fC->unlock(); }
    private:
        SkCondVar* fC;
    };

    struct Work {
        SkRunnable* task;  // A task to ->run(),
        int32_t* pending;  // then sk_atomic_dec(pending) afterwards.
    };

    explicit ThreadPool(int threads) : fDraining(false) {
        if (threads == 0) {
            threads = num_cores();
        }
        for (int i = 0; i < threads; i++) {
            fThreads.push(SkNEW_ARGS(SkThread, (&ThreadPool::Loop, this)));
            fThreads.top()->start();
        }
    }

    ~ThreadPool() {
        SkASSERT(fWork.isEmpty());  // All SkTaskGroups should be destroyed by now.
        {
            AutoLock lock(&fReady);
            fDraining = true;
            fReady.broadcast();
        }
        for (int i = 0; i < fThreads.count(); i++) {
            fThreads[i]->join();
        }
        SkASSERT(fWork.isEmpty());  // Can't hurt to double check.
        fThreads.deleteAll();
    }

    void add(SkRunnable* task, int32_t* pending) {
        Work work = { task, pending };
        sk_atomic_inc(pending);  // No barrier needed.
        {
            AutoLock lock(&fReady);
            fWork.push(work);
            fReady.signal();
        }
    }

    static void Loop(void* arg) {
        ThreadPool* pool = (ThreadPool*)arg;
        Work work;
        while (true) {
            {
                AutoLock lock(&pool->fReady);
                while (pool->fWork.isEmpty()) {
                    if (pool->fDraining) {
                        return;
                    }
                    pool->fReady.wait();
                }
                pool->fWork.pop(&work);
            }
            work.task->run();
            sk_atomic_dec(work.pending);  // Release pairs with sk_acquire_load() in Wait().
        }
    }

    SkTDArray<Work>      fWork;
    SkTDArray<SkThread*> fThreads;
    SkCondVar            fReady;
    bool                 fDraining;

    static ThreadPool* gGlobal;
    friend struct SkTaskGroup::Enabler;
};
ThreadPool* ThreadPool::gGlobal = NULL;

}  // namespace

SkTaskGroup::Enabler::Enabler(int threads) {
    SkASSERT(ThreadPool::gGlobal == NULL);
    ThreadPool::gGlobal = SkNEW_ARGS(ThreadPool, (threads));
}

SkTaskGroup::Enabler::~Enabler() {
    SkASSERT(ThreadPool::gGlobal != NULL);
    SkDELETE(ThreadPool::gGlobal);
}

SkTaskGroup::SkTaskGroup() : fPending(0) {}

void SkTaskGroup::add(SkRunnable* task) { ThreadPool::Add(task, &fPending); }
void SkTaskGroup::wait()                { ThreadPool::Wait(&fPending); }


text:
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
	android:id="@+id/name"
	style="@style/ListItemTitle"
	android:layout_toRightOf="@+id/folder"
	android:layout_width="fill_parent"
	android:layout_height="wrap_content"
	android:paddingLeft="10dp"
	android:layout_gravity="left" />


text:
package com.qihua.front.cart;

import java.sql.Types;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.ArrayUtils;
import org.springframework.stereotype.Repository;

import com.qihua.common.repository.GenericBeanPropertyRowMapper;
import com.qihua.common.repository.JdbcRepository;

@Repository
public class CartRepository extends JdbcRepository<Cart, String> {

  public List<Cart> selectByMemberId(String memberId) {
    StringBuilder sql = new StringBuilder();
    sql.append(" SELECT tb.cart_id,         ");
    sql.append("        tb.member_id,       ");
    sql.append("        tb.product_id,      ");
    sql.append("        tb.product_name,    ");
    sql.append("        tb.product_img_name,");
    sql.append("        tb.score,           ");
    sql.append("        tb.quantity         ");
    sql.append("   FROM t_cart tb           ");
    sql.append("  WHERE tb.member_id = ?    ");

    return jdbcTemplate.query(sql.toString(), new Object[] {memberId}, new int[] {Types.VARCHAR},
        new GenericBeanPropertyRowMapper<Cart>(Cart.class));
  }

  public Cart select(String memberId, String productId) {
    StringBuilder sql = new StringBuilder();
    sql.append(" SELECT tb.cart_id,         ");
    sql.append("        tb.score,           ");
    sql.append("        tb.quantity         ");
    sql.append("   FROM t_cart tb           ");
    sql.append("  WHERE tb.member_id = ?    ");
    sql.append("    AND tb.product_id = ?   ");

    return jdbcTemplate.queryForObject(sql.toString(), new Object[] {memberId, productId},
        new int[] {Types.VARCHAR, Types.VARCHAR}, new GenericBeanPropertyRowMapper<Cart>(Cart.class));
  }

  public long calcScore(String memberId) {
    StringBuilder sql = new StringBuilder();
    sql.append("   SELECT sum(score * quantity) ");
    sql.append("     FROM t_cart                ");
    sql.append("    WHERE member_id = ?         ");
    sql.append(" GROUP BY member_id             ");

    Object[] params = new Object[] {memberId};
    int[] types = new int[] {Types.VARCHAR};

    return jdbcTemplate.queryForObject(sql.toString(), params, types, Long.class);
  }

  public void deleteByMemberId(String memberId) {
    List<Object> params = new ArrayList<Object>();
    List<Integer> types = new ArrayList<Integer>();

    StringBuilder sql = new StringBuilder("DELETE FROM t_cart WHERE member_id = ? ");

    params.add(memberId);
    types.add(Types.VARCHAR);

    jdbcTemplate.update(sql.toString(), params.toArray(),
        ArrayUtils.toPrimitive(types.toArray(new Integer[types.size()])));
  }

  public void updateQuantity(Cart cart) {
    List<Object> params = new ArrayList<Object>();
    List<Integer> types = new ArrayList<Integer>();

    StringBuilder sql = new StringBuilder("UPDATE t_cart SET quantity = ? WHERE cart_id = ? ");

    params.add(cart.getQuantity());
    types.add(Types.BIGINT);

    params.add(cart.getCartId());
    types.add(Types.VARCHAR);

    jdbcTemplate.update(sql.toString(), params.toArray(),
        ArrayUtils.toPrimitive(types.toArray(new Integer[types.size()])));
  }

}


text:
"use strict";
var _ = require('lodash');

module.exports = function(middleware) {

    if (_.isFunction(middleware)) {

        return middleware;
    }
    throw new Error('Non-function middleware is not supported in the default middleware handler. Overwrite "middlewareHandler" to support your case.');
};


text:
package org.dstadler.commons.testing;

import java.io.Closeable;
import java.io.IOException;
import java.net.ServerSocket;
import java.util.Properties;
import java.util.concurrent.Callable;
import java.util.logging.Logger;

import org.dstadler.commons.http.NanoHTTPD;

/**
 * Simple REST WebServer that can be used to mock REST responses to client-code tests.
 *
 * Use it as follows
 *
 * <code>
 try (MockRESTServer server = new MockRESTServer()) {

     // get the actually used port to use in the client code
     server.getPort();

     // set the response that you want the server to send back
     server.setResponse("whatever you want to return");

     ..
 }
 </code>
 */
public class MockRESTServer implements Closeable {
    private static final Logger log = Logger.getLogger(MockRESTServer.class.getName());

    // The range of ports that we try to use for the listening.
    private static final int PORT_RANGE_START = 15100;
    private static final int PORT_RANGE_END = 15110;

    private final NanoHTTPD httpd;
    private final int port;

    /**
     * Create a mock server that responds to REST requests with the given HTTP Status Code.
     *
     * The server tries ports in the range listed above to find one that can be used. If none is usable, a IOException
     * is thrown.
     *
     * @param status The HTTP status to return, see NanoHTTPD.HTTP_...
     * @param mime The mime-type to set for the response, see NanoHTTPD.MIME_...
     * @param msg The actual message to return when the HTTP server is called.
     * @throws IOException
     *             If instantiating the Server failed.
     */
    public MockRESTServer(final String status, final String mime, final String msg) throws IOException {
        // first try to get the next free port
        port = getNextFreePort();

        httpd = new NanoHTTPD(port) {
            /**
             * Internal method to provide the response that is set.
             */
            @Override
            public Response serve(String uri, String method, Properties header, Properties params) {
                return new NanoHTTPD.Response(status, mime, msg);
            }
        };
    }

    /**
     * Create a mock server that handles REST requests by running the given Runnable and responding with the given HTTP Status Code.
     *
     * The server tries ports in the range listed above to find one that can be used. If none is usable, a IOException
     * is thrown.
     *
     * @param response A {@link Runnable} which is called whenever the HTTP server is called.
     * @param status The HTTP status to return, see NanoHTTPD.HTTP_...
     * @param mime The mime-type to set for the response, see NanoHTTPD.MIME_...
     * @param msg The actual message to return when the HTTP server is called.
     * @throws IOException If instantiating the Server failed.
     */
    public MockRESTServer(final Runnable response, final String status, final String mime, final String msg) throws IOException {
        // first try to get the next free port
        port = getNextFreePort();

        httpd = new NanoHTTPD(port) {
            /**
             * Internal method to run the provided Runnable
             */
            @Override
            public Response serve(String uri, String method, Properties header, Properties params) {
                response.run();
                return new NanoHTTPD.Response(status, mime, msg);
            }
        };
    }

    /**
     * Create a mock server that responds to REST requests via the given Callable.
     *
     * The server tries ports in the range listed above to find one that can be used. If none is usable, a IOException
     * is thrown.
     *
     * @param response A {@link Callable} which is called whenever the HTTP server is called. The returned
     *                 {@link org.dstadler.commons.http.NanoHTTPD.Response} contains the HTTP Status Code,
     *                 the mime-type and the result-text.
     * @throws IOException If instantiating the Server failed.
     */
    public MockRESTServer(final Callable<NanoHTTPD.Response> response) throws IOException {
        // first try to get the next free port
        port = getNextFreePort();

        httpd = new NanoHTTPD(port) {
            /**
             * Internal method to run the provided Runnable
             */
            @Override
            public Response serve(String uri, String method, Properties header, Properties params) {
                try {
                    return response.call();
                } catch (Exception e) {
                    throw new IllegalStateException(e);
                }
            }
        };
    }

    /**
     * Method that is used to find the next available port. It uses the two constants PORT_RANGE_START and
     * PORT_RANGE_END defined above to limit the range of ports that are tried.
     *
     * @return A port number that can be used.
     * @throws IOException
     *             If no available port is found.
     */
    private static int getNextFreePort() throws IOException {
        for (int port = PORT_RANGE_START; port < PORT_RANGE_END; port++) {
            try {
                @SuppressWarnings("resource")
                ServerSocket sock = new ServerSocket(port);
                sock.close();
                //
                return port;
            } catch (IOException e) {
                // seems to be taken, try next one
                log.warning("Port " + port + " seems to be used already, trying next one: " + e);
            }
        }

        throw new IOException("No free port found in the range of [" + PORT_RANGE_START + " - " + PORT_RANGE_END + "]");
    }

    public int getPort() {
        return port;
    }

    @Override
    public void close() {
        httpd.stop();
    }
}


text:
require_relative 'spec_helper'

describe package('tigervnc-server') do
  it { should be_installed }
end

describe service('vncserver') do
  it { should be_enabled }
end


text:
namespace OpenGD.Logic.Actions
{
    using System.Collections.Generic;

    public interface IAction
    {
        bool IsValid(GameState gameState, out IList<ActionValidationError> validationResults);

        void Resolve(GameState gameState);
    }
}


text:
var auroraMenuSpeed = 150;
var auroraAnimateSlide = true;

$(document).ready(function(){
	$('.auroramenu').each(function(){
  	var auroraMenuCount = $('.auroramenu').index($(this))
		var auroraMenuItems = $(this).children('li');
		auroraMenuItems.each(function(){
  		var auroraMenuItem = $(this);
			var auroraMenuItemCount = $(auroraMenuItems).index(auroraMenuItem);
		  var auroraSubMenu = auroraMenuItem.children('ul');
			if($.cookie('arMenu_' + auroraMenuCount + '_arItem_' + auroraMenuItemCount) == 1){
				auroraSubMenu.show().addClass('auroraopen');
			} else {
				auroraSubMenu.hide().removeClass('auroraopen');
			}
			auroraMenuItem
		    .attr('auroramenuitem','arMenu_' + auroraMenuCount + '_arItem_' + auroraMenuItemCount)
			  .children('a').click(function(e){
  			  e.preventDefault();
					var arshow = 0;
					var auroraThisMenuItem = $(this).parent('li');
					var auroraThisSubMenu = $(this).siblings('ul');
        	if ($.browser.msie && parseInt($.browser.version) < 8 && $.fx.off = false) {
            var auroraFxStateAltered = true;
        		$.fx.off = true;
        	}
					if(auroraThisMenuItem.hasClass('auroraopen')){
						auroraThisMenuItem.removeClass('auroraopen');
						auroraThisSubMenu.slideUp(auroraMenuSpeed);
					} else {
						arshow = 1;
						auroraThisMenuItem.addClass('auroraopen');
						auroraThisSubMenu.slideDown(auroraMenuSpeed);
					}
        	if (auroraFxStateAltered) {
        		$.fx.off = false;
        	}
				  $.cookie($(this).attr('auroramenuitem') , arshow , {path: '/'});
  			});
		});
	});
});


text:
package town.lost.oms;

import net.openhft.chronicle.bytes.MethodReader;
import net.openhft.chronicle.core.Jvm;
import net.openhft.chronicle.core.Mocker;
import net.openhft.chronicle.queue.ChronicleQueue;
import net.openhft.chronicle.queue.RollCycles;
import net.openhft.chronicle.queue.impl.single.SingleChronicleQueueBuilder;
import town.lost.oms.api.OMSIn;

public class OrderViewerMain {
    public static void main(String[] args) {
        System.out.println("\nWaiting for messages");
        try (ChronicleQueue q = SingleChronicleQueueBuilder.binary("in").rollCycle(RollCycles.TEST8_DAILY).build()) {
            OMSIn logging = Mocker.logging(OMSIn.class, "read - ", System.out);
            MethodReader reader = q.createTailer().methodReader(logging);
            while (true) {
                if (!reader.readOne())
                    Jvm.pause(50);
            }
        }
    }
}


text: SELECT md5sum(a || b) FROM t1


text:
<?php

namespace Desmay\UserBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use FOS\UserBundle\Model\User as BaseUser;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * User
 *
 * @ORM\Table(name="user", uniqueConstraints={@ORM\UniqueConstraint(name="pseudo", columns={"pseudo"})})
 * @ORM\Entity
 */
class User extends BaseUser {

    /**
     * @var integer
     *
     * @ORM\Column(name="idCountry", type="integer", nullable=true)
     */
    private $idcountry;

    /**
     * @var integer
     *
     * @ORM\Column(name="idStatistics", type="integer", nullable=true)
     */
    private $idstatistics;

    /**
     * @var integer
     *
     * @ORM\Column(name="idWeek", type="integer", nullable=true)
     */
    private $idweek;

    /**
     * @var string
     * @Assert\Length(
     *     min=3,
     *     max=50,
     *     minMessage="The first name is to short.",
     *     maxMessage="The first name is to long.",
     *     groups={"Registration", "Profile"}
     * )
     * @ORM\Column(name="firstName", type="string", length=50, nullable=true)
     */
    private $firstname;

    /**
     * @var string
     * @Assert\Length(
     *     min=3,
     *     max=50,
     *     minMessage="The last name is to short.",
     *     maxMessage="The last name is to long.",
     *     groups={"Registration", "Profile"}
     * )
     * @ORM\Column(name="lastName", type="string", length=50, nullable=true)
     */
    private $lastname;

    /**
     * @var boolean
     *
     * @ORM\Column(name="sexe", type="boolean", nullable=false)
     */
    private $sexe;

    /**
     * @var \DateTime
     * @ORM\Column(name="dateBorn", type="date", nullable=false)
     */
    private $dateborn;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="dateCreate", type="date", nullable=true)
     */
    private $datecreate;

    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    protected $id;

    /**
     * Set idcountry
     *
     * @param integer $idcountry
     *
     * @return User
     */
    public function setIdcountry($idcountry) {
        $this->idcountry = $idcountry;

        return $this;
    }

    /**
     * Get idcountry
     *
     * @return integer
     */
    public function getIdcountry() {
        return $this->idcountry;
    }

    /**
     * Set idstatistics
     *
     * @param integer $idstatistics
     *
     * @return User
     */
    public function setIdstatistics($idstatistics) {
        $this->idstatistics = $idstatistics;

        return $this;
    }

    /**
     * Get idstatistics
     *
     * @return integer
     */
    public function getIdstatistics() {
        return $this->idstatistics;
    }

    /**
     * Set idweek
     *
     * @param integer $idweek
     *
     * @return User
     */
    public function setIdweek($idweek) {
        $this->idweek = $idweek;

        return $this;
    }

    /**
     * Get idweek
     *
     * @return integer
     */
    public function getIdweek() {
        return $this->idweek;
    }

    /**
     * Set firstname
     *
     * @param string $firstname
     *
     * @return User
     */
    public function setFirstname($firstname) {
        $this->firstname = $firstname;

        return $this;
    }

    /**
     * Get firstname
     *
     * @return string
     */
    public function getFirstname() {
        return $this->firstname;
    }

    /**
     * Set lastname
     *
     * @param string $lastname
     *
     * @return User
     */
    public function setLastname($lastname) {
        $this->lastname = $lastname;

        return $this;
    }

    /**
     * Get lastname
     *
     * @return string
     */
    public function getLastname() {
        return $this->lastname;
    }

    /**
     * Set pseudo
     *
     * @param string $pseudo
     *
     * @return User
     */
    public function setPseudo($pseudo) {
        $this->pseudo = $pseudo;

        return $this;
    }

    /**
     * Get pseudo
     *
     * @return string
     */
    public function getPseudo() {
        return $this->pseudo;
    }

    /**
     * Set username
     *
     * @param string $username
     *
     * @return User
     */
    public function setUsername($username) {
        $this->username = $username;

        return $this;
    }

    /**
     * Get username
     *
     * @return string
     */
    public function getUsername() {
        return $this->username;
    }

    /**
     * Set password
     *
     * @param string $password
     *
     * @return User
     */
    public function setPassword($password) {
        $this->password = $password;

        return $this;
    }

    /**
     * Get password
     *
     * @return string
     */
    public function getPassword() {
        return $this->password;
    }

    /**
     * Set email
     *
     * @param string $email
     *
     * @return User
     */
    public function setEmail($email) {
        $this->email = $email;

        return $this;
    }

    /**
     * Get email
     *
     * @return string
     */
    public function getEmail() {
        return $this->email;
    }

    /**
     * Set sexe
     *
     * @param boolean $sexe
     *
     * @return User
     */
    public function setSexe($sexe) {
        $this->sexe = $sexe;

        return $this;
    }

    /**
     * Get sexe
     *
     * @return boolean
     */
    public function getSexe() {
        return $this->sexe;
    }

    /**
     * Set dateborn
     *
     * @param \DateTime $dateborn
     *
     * @return User
     */
    public function setDateborn($dateborn) {
        $this->dateborn = $dateborn;

        return $this;
    }

    /**
     * Get dateborn
     *
     * @return \DateTime
     */
    public function getDateborn() {
        return $this->dateborn;
    }

    /**
     * Set datecreate
     *
     * @param \DateTime $datecreate
     *
     * @return User
     */
    public function setDatecreate($datecreate) {
        $this->datecreate = $datecreate;

        return $this;
    }

    /**
     * Get datecreate
     *
     * @return \DateTime
     */
    public function getDatecreate() {
        return $this->datecreate;
    }

    /**
     * Set datelastvisit
     *
     * @param \DateTime $datelastvisit
     *
     * @return User
     */
    public function setDatelastvisit($datelastvisit) {
        $this->datelastvisit = $datelastvisit;

        return $this;
    }

    /**
     * Get datelastvisit
     *
     * @return \DateTime
     */
    public function getDatelastvisit() {
        return $this->datelastvisit;
    }

    /**
     * Set role
     *
     * @param string $role
     *
     * @return User
     */
    public function setRole($role) {
        $this->role = $role;

        return $this;
    }

    /**
     * Get role
     *
     * @return string
     */
    public function getRole() {
        return $this->role;
    }

    /**
     * Set archive
     *
     * @param boolean $archive
     *
     * @return User
     */
    public function setArchive($archive) {
        $this->archive = $archive;

        return $this;
    }

    /**
     * Get archive
     *
     * @return boolean
     */
    public function getArchive() {
        return $this->archive;
    }

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

}


text:
@if($errors->any())

        ×
        @foreach($errors->all() as $error)
            {{ $error }}
        @endforeach

@endif

<form class="row" id="content-report-form" method="post" action="{{ url('report/content') }}">
    {{ csrf_field() }}
    @if($user['type'] === 'admin' || $user['type'] === 'record-label')
        <input id="hidRole" value="{{$user['type']}}" type="hidden">
        @if($user['type'] <> 'artist')

                Artists:
                <select name="artist_id" id="selRepArtists" class="form-control chosen-select" required>
                    <option value="" selected disabled>choose artists</option>
                    @foreach($artists as $artist)
                        <option value="{{ $artist->id }}" {{ (old('artist_id') === $artist->id)? "selected" : "" }}>{{ $artist->nick_name }}</option>
                    @endforeach
                </select>

        @endif

            Title:
            <select name="q_id" id="selRepTitle" class="form-control" required>
                <option value="{{old('q_id') ?? ''}}" selected disabled>{{ $title ?? "choose title" }}</option>
            </select>

    @else

            Title:
            <select name="q_id" id="c-filter" class="form-control" required>
                <option value="{{old('q_id') ?? ''}}" selected disabled>{{ $title ?? "choose title" }}</option>
            </select>

    @endif

        Select date:

            <input name="start_date" id="start-date" type="text" class="form-control search-dates"
                   value="{{ $start ?? date('Y-m-d') }}" required>

to

            <input name="end_date" id="end-date" type="text" class="form-control search-dates"
                   value="{{ $end ?? date('Y-m-d') }}" required>

        Show
        <select name="show" id="show" class="form-control"
                onchange="document.querySelector('#content-report-form').submit()">
            <option value="" disabled selected>Select type</option>
            <option value="plays">Plays</option>
            <option value="heat map">Heat Map</option>
        </select>

</form>


text:
[CmdletBinding()]
Param
(
	[Parameter(Mandatory=$true)]
	[string]$VSTSAccount,

	[Parameter(Mandatory=$true)]
	[string]$PersonalAccessToken,

	[Parameter(Mandatory=$true)]
	[string]$AgentName,

	[Parameter(Mandatory=$true)]
	[string]$PoolName,

	[Parameter(Mandatory=$true)]
	[int]$AgentCount,

	[Parameter(Mandatory=$true)]
	[string]$AdminUser,

	[Parameter(Mandatory=$true)]
	[array]$Modules
)

Write-Verbose "Entering InstallVSOAgent.ps1" -verbose

$currentLocation = Split-Path -parent $MyInvocation.MyCommand.Definition
Write-Verbose "Current folder: $currentLocation" -verbose

#Create a temporary directory where to download from VSTS the agent package (vsts-agent.zip) and then launch the configuration.
$agentTempFolderName = Join-Path $env:temp ([System.IO.Path]::GetRandomFileName())
New-Item -ItemType Directory -Force -Path $agentTempFolderName
Write-Verbose "Temporary Agent download folder: $agentTempFolderName" -verbose

$serverUrl = "https://$VSTSAccount.visualstudio.com"
Write-Verbose "Server URL: $serverUrl" -verbose

$retryCount = 3
$retries = 1
Write-Verbose "Downloading Agent install files" -verbose
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
do
{
  try
  {
    Write-Verbose "Trying to get download URL for latest VSTS agent release..."
    $latestRelease = Invoke-RestMethod -Uri "https://api.github.com/repos/Microsoft/vsts-agent/releases"
	$latestRelease = $latestRelease | Where-Object assets -ne $null | Sort-Object created_at -Descending | Select-Object -First 1
    $assetsURL = ($latestRelease.assets).browser_download_url
    $latestReleaseDownloadUrl = ((Invoke-RestMethod -Uri $assetsURL) -match 'win').downloadurl
    Invoke-WebRequest -Uri $latestReleaseDownloadUrl -Method Get -OutFile "$agentTempFolderName\agent.zip"
    Write-Verbose "Downloaded agent successfully on attempt $retries" -verbose
    break
  }
  catch
  {
    $exceptionText = ($_ | Out-String).Trim()
    Write-Verbose "Exception occured downloading agent: $exceptionText in try number $retries" -verbose
    $retries++
    Start-Sleep -Seconds 30
  }
}
while ($retries -le $retryCount)

for ($i=0; $i -lt $AgentCount; $i++)
{
	$Agent = ($AgentName + "-" + $i)

	# Construct the agent folder under the main (hardcoded) C: drive.
	$agentInstallationPath = Join-Path "C:" $Agent

	# Create the directory for this agent.
	New-Item -ItemType Directory -Force -Path $agentInstallationPath

	# Set the current directory to the agent dedicated one previously created.
	Push-Location -Path $agentInstallationPath

	Write-Verbose "Extracting the zip file for the agent" -verbose
	$destShellFolder = (new-object -com shell.application).namespace("$agentInstallationPath")
	$destShellFolder.CopyHere((new-object -com shell.application).namespace("$agentTempFolderName\agent.zip").Items(),16)

	# Removing the ZoneIdentifier from files downloaded from the internet so the plugins can be loaded
	# Don't recurse down _work or _diag, those files are not blocked and cause the process to take much longer
	Write-Verbose "Unblocking files" -verbose
	Get-ChildItem -Recurse -Path $agentInstallationPath | Unblock-File | out-null

	# Retrieve the path to the config.cmd file.
	$agentConfigPath = [System.IO.Path]::Combine($agentInstallationPath, 'config.cmd')
	Write-Verbose "Agent Location = $agentConfigPath" -Verbose
	if (![System.IO.File]::Exists($agentConfigPath))
	{
		Write-Error "File not found: $agentConfigPath" -Verbose
		return
	}

	# Call the agent with the configure command and all the options (this creates the settings file) without prompting
	# the user or blocking the cmd execution
	Write-Verbose "Configuring agent '$($Agent)'" -Verbose
	.\config.cmd --unattended --url $serverUrl --auth PAT --token $PersonalAccessToken --pool $PoolName --agent $Agent --runasservice

	Write-Verbose "Agent install output: $LASTEXITCODE" -Verbose

	Pop-Location
}

# Adding new Path to PSModulePath environment variable
$CurrentValue = [Environment]::GetEnvironmentVariable("PSModulePath", "Machine")
[Environment]::SetEnvironmentVariable("PSModulePath", $CurrentValue + ";C:\Modules", "Machine")
$NewValue = [Environment]::GetEnvironmentVariable("PSModulePath", "Machine")
Write-Verbose "new Path is: $($NewValue)" -verbose

# Creating new Path
if (!(Test-Path -Path C:\Modules -ErrorAction SilentlyContinue))
{	New-Item -ItemType Directory -Name Modules -Path C:\ -Verbose }

# Installing New Modules and Removing Old
Foreach ($Module in $Modules)
{	Find-Module -Name $Module.Name -RequiredVersion $Module.Version -Repository PSGallery -Verbose | Save-Module -Path C:\Modules -Verbose	}

$DefaultModules = "PowerShellGet", "PackageManagement","Pester"

Foreach ($Module in $DefaultModules)
{
	if ($tmp = Get-Module $Module -ErrorAction SilentlyContinue) {	Remove-Module $Module -Force	}
	Find-Module -Name $Module -Repository PSGallery -Verbose | Install-Module -Force -Confirm:$false -SkipPublisherCheck -Verbose
}

# Uninstalling old Azure PowerShell Modules
$programName = "Microsoft Azure PowerShell"
$app = Get-WmiObject -Class Win32_Product -Filter "Name Like '$($programName)%'" -Verbose
$app.Uninstall()

Write-Verbose "Exiting InstallVSTSAgent.ps1" -Verbose


text:
<?xml version="1.0" encoding="UTF-8"?>
<JWindow xmlns="org.aswing" xmlns:geom="org.aswing.geom">
    <content>
        <JPanel>
            <layout>
                    <FlowLayout>
                            <align>org.aswing.FlowLayout.LEFT</align>
                            <hgap>30</hgap>
                            <vgap>30</vgap>
                            <margin>true</margin>
                    </FlowLayout>
            </layout>
            <JLabelButton text="'First'"/>
            <JLabelButton text="'Second'">
                <font>
                    <ASFont underline="true"/>
                </font>
                <rolloverColor><ASColor rgb="0x00ff00"/></rolloverColor>
            </JLabelButton>
            <JLabelButton text="'Third'">
                <pressedColor>
                    <ASColor rgb="0xff0000"/>
                </pressedColor>
            </JLabelButton>
        </JPanel>
    </content>
</JWindow>


text:
<!doctype html>

	<meta charset="utf-8">
	<title><?php echo lang("update_user_privileges_demo"); ?> | Flexi Auth | <?php echo lang("a_user_authentication_library"); ?></title>
	<meta name="description" content="Flexi Auth, the user authentication library designed for developers."/>
	<meta name="keywords" content="demo, Flexi Auth, user authentication, Codeigniter"/>
	<?php $this->load->view('includes/head'); ?>

	<?php $this->load->view('includes/header'); ?>

	<?php $this->load->view('includes/demo_header'); ?>

<?php echo lang("admin_update_user_privilege"); ?>

The Flexi Auth library allows for unlimited custom privileges to be defined. The privileges can then be assigned to user groups or users individually.

Once privileges have been defined, access to specific pages or even specific sections of pages can be controlled by checking whether a user has permission to access a requested page.

The default setup of this demo uses user groups and privileges to restrict the example public user from accessing the Admin area, and the example moderator user from inserting, updating and deleting specific data within the Admin area.

» View Current Privilege Sources

The Flexi Auth config. setting 'privilege_sources' defines whether user privileges should be determined by individual privileges assigned per user, or via privileges assigned to a users user group.

According to the current settings:

	                <?php
	                    if (in_array('user', $privilege_sources))
	                    {
	                        echo '
User privileges are considered.
';
	                    }
	                    else
	                    {
	                        echo '
User privileges are NOT considered.
';
	                    }

	                    if (in_array('group', $privilege_sources))
	                    {
	                        echo '
Group privileges are considered.
';
	                    }
	                    else
	                    {
	                        echo '
User Group privileges are NOT considered.
';
	                    }
	                ?>

<?php echo lang("update_user_privileges_for"); ?> '<?php echo $user['upro_first_name'].' '.$user['upro_last_name']; ?>', Member of Group '<?php echo $user['ugrp_name']; ?>'

				<a href="<?php echo $base_url;?>auth_admin/manage_user_accounts">Manage User Accounts |
				<a href="<?php echo $base_url;?>auth_admin/update_user_account/<?php echo $user['upro_uacc_fk']; ?>">Update Users Account

			<?php if (! empty($message)) { ?>

					<?php echo $message; ?>

			<?php } ?>

				<?php echo form_open(current_url());	?>

									<?php echo lang("privilege_name"); ?>

									<?php echo lang("description"); ?>

									<?php echo lang("user_has_individual_privilege"); ?>

									<?php echo lang("has_privilege_from_user_group"); ?>

						<?php foreach ($privileges as $privilege) { ?>

									<input type="hidden" name="update[<?php echo $privilege[$this->flexi_auth->db_column('user_privileges', 'id')]; ?>][id]" value="<?php echo $privilege[$this->flexi_auth->db_column('user_privileges', 'id')]; ?>"/>
									<?php echo $privilege[$this->flexi_auth->db_column('user_privileges', 'name')];?>

								<?php echo $privilege[$this->flexi_auth->db_column('user_privileges', 'description')];?>

									<?php
										// Define form input values.
										$current_status = (in_array($privilege[$this->flexi_auth->db_column('user_privileges', 'id')], $user_privileges)) ? 1 : 0;
										$new_status = (in_array($privilege[$this->flexi_auth->db_column('user_privileges', 'id')], $user_privileges)) ? 'checked="checked"' : NULL;
									?>
									<input type="hidden" name="update[<?php echo $privilege[$this->flexi_auth->db_column('user_privileges', 'id')];?>][current_status]" value="<?php echo $current_status ?>"/>
									<input type="hidden" name="update[<?php echo $privilege[$this->flexi_auth->db_column('user_privileges', 'id')];?>][new_status]" value="0"/>
									<input type="checkbox" name="update[<?php echo $privilege[$this->flexi_auth->db_column('user_privileges', 'id')];?>][new_status]" value="1" <?php echo $new_status ?>/>

									<?php echo (in_array($privilege[$this->flexi_auth->db_column('user_privileges', 'id')], $group_privileges) ? 'Yes' : 'No'); ?>

						<?php } ?>

									<input type="submit" name="update_user_privilege" value="<?php echo lang("update_user_privileges"); ?>" class="link_button large"/>

				<?php echo form_close();?>

	<?php $this->load->view('includes/footer'); ?>

<?php $this->load->view('includes/scripts'); ?>


text:
```plpgsql
CREATE OR REPLACE FUNCTION account.can_register_with_google()
RETURNS boolean
```
* Schema : [account](../../schemas/account.md)
* Function Name : can_register_with_google
* Arguments :
* Owner : frapid_db_user
* Result Type : boolean
* Description :

**Source:**
```sql
CREATE OR REPLACE FUNCTION account.can_register_with_google()
 RETURNS boolean
 LANGUAGE plpgsql
AS $function$
BEGIN
    IF EXISTS
    (
        SELECT 1
		FROM account.configuration_profiles
        WHERE account.configuration_profiles.is_active
        AND account.configuration_profiles.allow_registration
        AND account.configuration_profiles.allow_google_registration
		AND NOT account.configuration_profiles.deleted
    ) THEN
        RETURN true;
    END IF;

    RETURN false;
END
$function$

```

### Related Contents
* [Schema List](../../schemas.md)
* [Function List](../../functions.md)
* [Trigger List](../../triggers.md)
* [Table of Contents](../../README.md)


text:
reset-bls-entries
=================

This is an element which will run a script on first boot to rename
`/boot/loader/entries` filenames to match the new value of `/etc/machine-id`.
This is required for `grub2-mkconfig` calls to incorporate existing values in
the boot loader entry files.

It only runs when first-boot criteria is met, such as when `uninitialized` is
written to `/etc/machine-id`


text:
package org.kisoonlineapp.landingpage.ui;

import org.junit.After;
import org.junit.AfterClass;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

/**
 *
 * @author berni
 */
public class ImagesRotatorTest {

    private ImagesRotator instance;

    public ImagesRotatorTest() {
    }

    @BeforeClass
    public static void setUpClass() {
    }

    @AfterClass
    public static void tearDownClass() {
    }

    @Before
    public void setUp() {
        instance = new ImagesRotator();
        instance.onCreate();
    }

    @After
    public void tearDown() {
    }

    /**
     * Test of getNextImageName method, of class ImagesRotator.
     */
    @Test
    public void testGetNextImageName() {
        String result = instance.getNextImageName();
        assertNotNull(result);
        asserKisoJpgString(result);

        //
        for (int i = 0; i < 100; i++) {
            result = instance.getNextImageName();
            assertNotNull(result);
            asserKisoJpgString(result);
        }
    }

    private void asserKisoJpgString(String result) {
        String m = "Result is " + result;

        assertTrue(m, result.startsWith("Kiso"));
        assertTrue(m, result.endsWith("512x354.jpg"));
    }

}


text:
Organization units (OU) can be used to **hierarchically group users and
entities**.

### OrganizationUnit Entity

An OU is represented by the **OrganizationUnit** entity. Fundamental
properties of this entity are;

-   **TenantId**: Tenant's Id of this OU. Can be null for host OUs.
-   **ParentId**: Parent OU's Id. Can be null if this is a root OU.
-   **Code**: A hierarchical string code that is unique for a tenant.
-   **DisplayName**: Shown name of the OU.

OrganizationUnit entitiy's primary key (Id) is **long** and it derives
from [**FullAuditedEntity**](/Pages/Documents/Entities#auditing)
which provides audit information and implements
[**ISoftDelete**](/Pages/Documents/Data-Filters#isoftdelete) interface
(so, OUs are not deleted from database, they are just marked as
deleted).

#### Organization Tree

Since an OU can have a parent, all OUs of a tenant are in a **tree**
structure. There are some rules for this tree;

-   There can be more than one root (which have null ParentId).
-   Maximum deep of tree is defined as a constant as
    OrganizationUnit.**MaxDepth**, which is **16**.
-   There is a limit for first-level children count of an OU (because of
    fixed OU Code unit length explained below).

#### OU Code

OU code is automatically generated and maintained by OrganizationUnit
Manager. It's a string something like:

"**00001.00042.00005**"

This code can be used to easily query database for all children
(recursively) of an OU. There are some rules for this code;

-   It's **unique** for a [tenant](/Pages/Documents/Multi-Tenancy).
-   All children of same OU have codes **start with parent OU's code**.
-   It's **fixed length** based on level of OU in the tree, as shown in
    the sample.
-   While OU code is unique, it can be **changable** if you move an OU.
    So, we should reference an OU by Id, not Code.

### OrganizationUnit Manager

**OrganizationUnitManager** class can be
[injected](/Pages/Documents/Dependency-Injection) and used to manage
OUs. Common use cases are:

-   Create, Update or Delete an OU
-   Move an OU in OU tree.
-   Getting information about OU tree and items.

#### Multi Tenancy

OrganizationUnitManager is designed to work for a **single tenant** in a
time. It works for the **current tenant** as default.

### Common Use Cases

Here, we will see common use cases for OUs. You can find source code of
the samples
[here](https://github.com/aspnetboilerplate/aspnetboilerplate-samples/tree/master/OrganizationUnitsDemo).

#### Creating Entity Belongs To An Organization Unit

Most obvious usage of OUs is to assign an entity to an OU. Let's see a
sample entity:

    public class Product : Entity, IMustHaveTenant, IMustHaveOrganizationUnit
    {
        public virtual int TenantId { get; set; }

        public virtual long OrganizationUnitId { get; set; }

        public virtual string Name { get; set; }

        public virtual float Price { get; set; }
    }

We simple created **OrganizationUnitId** property to assign this entity
to an OU. **IMustHaveOrganizationUnit** defines the OrganizationUnitId
property. We don't have to implement it, but it's suggested to provide
standardization. There is also an IMayHaveOrganizationId which has a
**nullable** OrganizationUnitId property.

Now, we can relate a Product to an OU and query products of a specific
OU.

**Notice that**; Product entity have a **TenantId** (which is a property
of IMustHaveTenant) to distinguish products of different tenants in a
multi-tenant application (see [multi tenancy
document](/Pages/Documents/Multi-Tenancy#data-filters)). If your
application is not multi-tenant, you don't need this interface and
property.

#### Get Entities In An Organization Unit

Getting Products of an OU is simple. Let's see this sample [domain
service](/Pages/Documents/Domain-Services):

    public class ProductManager : IDomainService
    {
        private readonly IRepository<Product> _productRepository;

        public ProductManager(IRepository<Product> productRepository)
        {
            _productRepository = productRepository;
        }

        public List<Product> GetProductsInOu(long organizationUnitId)
        {
            return _productRepository.GetAllList(p => p.OrganizationUnitId == organizationUnitId);
        }

    }

We can simply write a predicate against Product.OrganizationUnitId as
shown above.

#### Get Entities In An Organization Unit Including It's Child Organization Units

We may want to get Products of an organization unit including child
organization units. In this case, OU **Code** can help us:

    public class ProductManager : IDomainService
    {
        private readonly IRepository<Product> _productRepository;
        private readonly IRepository<OrganizationUnit, long> _organizationUnitRepository;

        public ProductManager(
            IRepository<Product> productRepository,
            IRepository<OrganizationUnit, long> organizationUnitRepository)
        {
            _productRepository = productRepository;
            _organizationUnitRepository = organizationUnitRepository;
        }

        [UnitOfWork]
        public virtual List<Product> GetProductsInOuIncludingChildren(long organizationUnitId)
        {
            var code = _organizationUnitRepository.Get(organizationUnitId).Code;

            var query =
                from product in _productRepository.GetAll()
                join organizationUnit in _organizationUnitRepository.GetAll() on product.OrganizationUnitId equals organizationUnit.Id
                where organizationUnit.Code.StartsWith(code)
                select product;

            return query.ToList();
        }
    }

First, we got **code** of the given OU. Then we created a LINQ with a
**join** and **StartsWith(code)** condition (StartsWith creates a
**LIKE** query in SQL). Thus, we can hierarchically get products of an
OU.

#### Filter Entities For A User

We may want to get all products those are in OUs of a specific user.
Example code:

    public class ProductManager : IDomainService
    {
        private readonly IRepository<Product> _productRepository;
        private readonly UserManager _userManager;

        public ProductManager(
            IRepository<Product> productRepository,
            UserManager userManager)
        {
            _productRepository = productRepository;
            _organizationUnitRepository = organizationUnitRepository;
            _userManager = userManager;
        }

        public async Task<List<Product>> GetProductsForUserAsync(long userId)
        {
            var user = await _userManager.GetUserByIdAsync(userId);
            var organizationUnits = await _userManager.GetOrganizationUnitsAsync(user);
            var organizationUnitIds = organizationUnits.Select(ou => ou.Id);

            return await _productRepository.GetAllListAsync(p => organizationUnitIds.Contains(p.OrganizationUnitId));
        }
    }

We simply found Ids of OUs of the user. Then used **Contains** condition
while getting products. Surely, we could create a LINQ query with join
to get the same list.

We may want to get products in user's OUs including their child OUs:

    public class ProductManager : IDomainService
    {
        private readonly IRepository<Product> _productRepository;
        private readonly IRepository<OrganizationUnit, long> _organizationUnitRepository;
        private readonly UserManager _userManager;

        public ProductManager(
            IRepository<Product> productRepository,
            IRepository<OrganizationUnit, long> organizationUnitRepository,
            UserManager userManager)
        {
            _productRepository = productRepository;
            _organizationUnitRepository = organizationUnitRepository;
            _userManager = userManager;
        }

        [UnitOfWork]
        public virtual async Task<List<Product>> GetProductsForUserIncludingChildOusAsync(long userId)
        {
            var user = await _userManager.GetUserByIdAsync(userId);
            var organizationUnits = await _userManager.GetOrganizationUnitsAsync(user);
            var organizationUnitCodes = organizationUnits.Select(ou => ou.Code);

            var query =
                from product in _productRepository.GetAll()
                join organizationUnit in _organizationUnitRepository.GetAll() on product.OrganizationUnitId equals organizationUnit.Id
                where organizationUnitCodes.Any(code => organizationUnit.Code.StartsWith(code))
                select product;

            return query.ToList();
        }
    }

We combined **Any** with **StartsWith** condition in a LINQ join
statement.

Surely, there may be much more complex requirements, but all can be done
with LINQ or SQL.

### Settings

You can inject and use **IOrganizationUnitSettings** interface to get
Organization Units setting values. Currently, there is just a single
setting that can be changed for your application needs:

-   **MaxUserMembershipCount**: Maximum allowed membership count for a
    user.
    Default value is **int.MaxValue** which allows a user to be member
    of unlimited OUs in same time.
    Setting name is a constant defined in
    *AbpZeroSettingNames.OrganizationUnits.MaxUserMembershipCount*.

You can change setting values using [setting
manager](/Pages/Documents/Setting-Management).


text:
<?php

namespace Fenchy\UserBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Fenchy\UserBundle\Entity\NotificationGroupInterval;

class NotificationGroupIntervalType extends AbstractType
{

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add(
                    'interval',
                    'choice',
                    array(
                        'choices' => NotificationGroupInterval::$intervalsMap,
                        'required' => TRUE,
                        'expanded' => TRUE,

            ))
        ;

    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'Fenchy\UserBundle\Entity\NotificationGroupInterval'
        ));
    }

    public function getName()
    {
        return 'fenchy_userbundle_usernotificationstype';
    }
}


text:
![Demo](https://raw.githubusercontent.com/yhpark/YHRoundBorderedButton/master/Example/demo.gif)

## Usage

To run the example project; clone the repo, and run `pod install` from the Example directory first.

## Requirements

## Installation

YHRoundBorderedButton is available through [CocoaPods](http://cocoapods.org), to install
it simply add the following line to your Podfile:

    pod "YHRoundBorderedButton"

## Author

Yeonghoon Park, me@yhpark.co

## License

Copyright (c) 2014 Yeonghoon Park <me@yhpark.co>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.


text:
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:2.0.50727.1378
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace System.Web.Resources {
    using System;

    /// <summary>
    ///   A strongly-typed resource class, for looking up localized strings, etc.
    /// </summary>
    // This class was auto-generated by the StronglyTypedResourceBuilder
    // class via a tool like ResGen or Visual Studio.
    // To add or remove a member, edit your .ResX file then rerun ResGen
    // with the /str option, or rebuild your VS project.
    [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "2.0.0.0")]
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
    [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
    internal class WCFModelStrings {

        private static global::System.Resources.ResourceManager resourceMan;

        private static global::System.Globalization.CultureInfo resourceCulture;

        [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
        internal WCFModelStrings() {
        }

        /// <summary>
        ///   Returns the cached ResourceManager instance used by this class.
        /// </summary>
        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
        internal static global::System.Resources.ResourceManager ResourceManager {
            get {
                if (object.ReferenceEquals(resourceMan, null)) {
                    global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("System.Web.Resources.WCFModelStrings", typeof(WCFModelStrings).Assembly);
                    resourceMan = temp;
                }
                return resourceMan;
            }
        }

        /// <summary>
        ///   Overrides the current thread's CurrentUICulture property for all
        ///   resource lookups using this strongly typed resource class.
        /// </summary>
        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
        internal static global::System.Globalization.CultureInfo Culture {
            get {
                return resourceCulture;
            }
            set {
                resourceCulture = value;
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to {0} Line {1}, position {2}..
        /// </summary>
        internal static string ReferenceGroup_AppendLinePosition {
            get {
                return ResourceManager.GetString("ReferenceGroup_AppendLinePosition", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to The type '{0}' is listed as a shared data contract type, but is also listed in the type sharing exclusion list..
        /// </summary>
        internal static string ReferenceGroup_DataContractExcludedAndIncluded {
            get {
                return ResourceManager.GetString("ReferenceGroup_DataContractExcludedAndIncluded", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to The global {0} ('{1}') has been defined in both '{2}' and '{3}'. They are different at '{4}'..
        /// </summary>
        internal static string ReferenceGroup_DuplicatedSchemaItems {
            get {
                return ResourceManager.GetString("ReferenceGroup_DuplicatedSchemaItems", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to The global {0} ('{1}') has been defined in both '{2}' and '{3}'. The difference between them ('{4}') is ignored..
        /// </summary>
        internal static string ReferenceGroup_DuplicatedSchemaItemsIgnored {
            get {
                return ResourceManager.GetString("ReferenceGroup_DuplicatedSchemaItemsIgnored", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Address must be specified..
        /// </summary>
        internal static string ReferenceGroup_EmptyAddress {
            get {
                return ResourceManager.GetString("ReferenceGroup_EmptyAddress", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Protocol must be specified..
        /// </summary>
        internal static string ReferenceGroup_EmptyProtocol {
            get {
                return ResourceManager.GetString("ReferenceGroup_EmptyProtocol", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Failed to generate code for the service reference '{0}'.
        ///{1}.
        /// </summary>
        internal static string ReferenceGroup_FailedToGenerateCode {
            get {
                return ResourceManager.GetString("ReferenceGroup_FailedToGenerateCode", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Shared assembly '{0}' could not be loaded. If this is a referenced project, please make sure that you have built the project first..
        /// </summary>
        internal static string ReferenceGroup_FailedToLoadAssembly {
            get {
                return ResourceManager.GetString("ReferenceGroup_FailedToLoadAssembly", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to The message part '{0}' in message contract '{1}' is different in '{2}' and '{3}'..
        /// </summary>
        internal static string ReferenceGroup_FieldDefinedDifferentlyInDuplicatedMessage {
            get {
                return ResourceManager.GetString("ReferenceGroup_FieldDefinedDifferentlyInDuplicatedMessage", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to The message contract '{0}' is defined in both '{1}' and '{2}', but only one contains message part '{3}'..
        /// </summary>
        internal static string ReferenceGroup_FieldDefinedInOneOfDuplicatedMessage {
            get {
                return ResourceManager.GetString("ReferenceGroup_FieldDefinedInOneOfDuplicatedMessage", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to '{0}' is invalid file name.  Absolute or relative path is not supported..
        /// </summary>
        internal static string ReferenceGroup_InvalidFileName {
            get {
                return ResourceManager.GetString("ReferenceGroup_InvalidFileName", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to SourceId of a metadata source should be a positive integer..
        /// </summary>
        internal static string ReferenceGroup_InvalidSourceId {
            get {
                return ResourceManager.GetString("ReferenceGroup_InvalidSourceId", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to The operation '{0}' in service contract '{1}' is different in '{2}' and '{3}'. Check the input, output and fault messages of the operation..
        /// </summary>
        internal static string ReferenceGroup_OperationDefinedDifferently {
            get {
                return ResourceManager.GetString("ReferenceGroup_OperationDefinedDifferently", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to The service contract '{0}' is defined in both '{1}' and '{2}', but only one of them contains the operation '{3}'..
        /// </summary>
        internal static string ReferenceGroup_OperationDefinedInOneOfDuplicatedServiceContract {
            get {
                return ResourceManager.GetString("ReferenceGroup_OperationDefinedInOneOfDuplicatedServiceContract", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to The type '{0}' in the service contract mapping has different TargetNamespace('{1}') and Name('{2}') than the TargetNamespace('{3}') and Name('{4}') in the service reference file..
        /// </summary>
        internal static string ReferenceGroup_ServiceContractMappingMissMatch {
            get {
                return ResourceManager.GetString("ReferenceGroup_ServiceContractMappingMissMatch", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to The type '{0}' cannot be used in type sharing because it is not public..
        /// </summary>
        internal static string ReferenceGroup_SharedTypeMustBePublic {
            get {
                return ResourceManager.GetString("ReferenceGroup_SharedTypeMustBePublic", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Two metadata items or extension items in the .svcmap file have the same file name '{0}'..
        /// </summary>
        internal static string ReferenceGroup_TwoExternalFilesWithSameName {
            get {
                return ResourceManager.GetString("ReferenceGroup_TwoExternalFilesWithSameName", resourceCulture);
            }
        }
    }
}


text:
'use strict';

const numAsString = '1234';

console.log(parseInt(numAsString) + 1);
console.log(parseFloat(numAsString) + 1);
console.log(+numAsString + 1);
console.log(numAsString * 1 + 1);
console.log((numAsString | 0) + 1);
console.log(Number(numAsString) + 1)

const invalidNumString = '435javascript';
console.log(parseInt(invalidNumString) + 1); // will parse whatever it can - 435
console.log(+invalidNumString); // NaN
console.log(Number(invalidNumString)); // NaN

const fractionString = '3.65';
console.log(parseFloat(fractionString) + 1);
console.log(Number(fractionString) + 1);
console.log(+fractionString + 1);