text:
module Music.Dynamics.Literal (
        -- * IsDynamics class
        DynamicsL(..),
        IsDynamics(..),

        -- * Literal values

        -- ** Standard dynamics
        pppppp, ppppp, pppp, ppp, pp, _p,
        mp, mf,
        _f, ff, fff, ffff, fffff, ffffff,

        -- ** Other dynamics
        sffz, sfz, fz, rfz, fp
  ) where

import           Control.Applicative
import           Data.Fixed
import           Data.Ratio
import           Data.Semigroup

-- |
-- Dynamics literal.
--
-- First value is start value, second is end value.
--
-- * @(Just x, Nothing)@ is a constant dynamic of @x@
-- * @(Just x, Just y)@ is a dynamic varying from @x@ to @y@
-- * @(Nothing, Just y)@ is a dynamic varying from the previous level to @y@
-- * @(Nothing, Nothing)@ is a dynamic varying from the previous level to the next.
--
-- For levels, we use @-0.5@ for /mp/, @0.5@ for /mf/ and add or remove one for each level.
-- @0@ is an unspecified middle level dynamic.
--
newtype DynamicsL = DynamicsL { getDynamicsL :: (Maybe Double, Maybe Double) }
    deriving (Eq, Show, Ord)

-- Like Num can be expressed using arabic numerals, instances
-- of IsDynamics can be expressed using Western pitch names (c, c sharp, c flat etc)
class IsDynamics a where
    fromDynamics :: DynamicsL -> a

instance IsDynamics DynamicsL where
    fromDynamics = id

instance IsDynamics a => IsDynamics (Maybe a) where
    fromDynamics = pure . fromDynamics

instance (Monoid b, IsDynamics a) => IsDynamics (b, a) where
    fromDynamics = pure . fromDynamics

instance IsDynamics a => IsDynamics [a] where
    fromDynamics = pure . fromDynamics

instance IsDynamics Float where
    fromDynamics x = realToFrac (fromDynamics x :: Double)

instance HasResolution a => IsDynamics (Fixed a) where
    fromDynamics x = realToFrac (fromDynamics x :: Double)

instance Integral a => IsDynamics (Ratio a) where
    fromDynamics x = realToFrac (fromDynamics x :: Double)

instance IsDynamics Double where
    fromDynamics (DynamicsL (Just x, _)) = x
    fromDynamics (DynamicsL (Nothing, _)) = error "IsDynamics Double: No dynamics"

pppppp, ppppp, pppp, ppp, pp, _p, mp, mf, _f, ff, fff, ffff, fffff, ffffff ::  IsDynamics a => a
sffz, sfz, fz, rfz, fp ::  IsDynamics a => a

pppppp  = fromDynamics $ DynamicsL (Just $ -6.5, Nothing)
ppppp   = fromDynamics $ DynamicsL (Just $ -5.5, Nothing)
pppp    = fromDynamics $ DynamicsL (Just $ -4.5, Nothing)
ppp     = fromDynamics $ DynamicsL (Just $ -3.5, Nothing)
pp      = fromDynamics $ DynamicsL (Just $ -2.5, Nothing)
_p      = fromDynamics $ DynamicsL (Just $ -1.5, Nothing)
mp      = fromDynamics $ DynamicsL (Just $ -0.5, Nothing)
mf      = fromDynamics $ DynamicsL (Just $  0.5, Nothing)
_f      = fromDynamics $ DynamicsL (Just $  1.5, Nothing)
ff      = fromDynamics $ DynamicsL (Just $  2.5, Nothing)
fff     = fromDynamics $ DynamicsL (Just $  3.5, Nothing)
ffff    = fromDynamics $ DynamicsL (Just $  4.5, Nothing)
fffff   = fromDynamics $ DynamicsL (Just $  5.5, Nothing)
ffffff  = fromDynamics $ DynamicsL (Just $  6.5, Nothing)

sffz    = error "Not supported yet"
sfz     = error "Not supported yet"
fz      = error "Not supported yet"
rfz     = error "Not supported yet"
fp      = error "Not supported yet"


text:
using System;
using System.Dynamic;

namespace Simple.Data.Commands
{
    class QueryByCommand : ICommand
    {
        public bool IsCommandFor(string method)
        {
            return method.StartsWith("QueryBy") || method.StartsWith("query_by_", StringComparison.InvariantCultureIgnoreCase);
        }

        public object Execute(DataStrategy dataStrategy, DynamicTable table, InvokeMemberBinder binder, object[] args)
        {
            return CreateSimpleQuery(table, binder, args, dataStrategy);
        }

        private static object CreateSimpleQuery(DynamicTable table, InvokeMemberBinder binder, object[] args, DataStrategy dataStrategy)
        {
            var criteriaExpression = ExpressionHelper.CriteriaDictionaryToExpression(table.GetQualifiedName(), MethodNameParser.ParseFromBinder(binder, args));
            return new SimpleQuery(dataStrategy, table.GetQualifiedName()).Where(criteriaExpression);
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
<!doctype html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0">
    <meta name="description" content="SuperEnalotto - Sitema vincente numeri!">
    <meta name="author" content="">

    <title>SuperEnalotto Sistema vincente</title>

    <link href="css/bootstrap.min.css" rel="stylesheet">

    <link href="font-awesome/css/font-awesome.min.css" rel="stylesheet">
    <link href='//fonts.googleapis.com/css?family=Lato:100,300,400,700,900,100italic,300italic,400italic,700italic,900italic' rel='stylesheet' type='text/css'>
	<link href='//fonts.googleapis.com/css?family=Arvo:400,700' rel='stylesheet' type='text/css'>

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

    <link href="css/custom.css" rel="stylesheet">
	<link href="css/owl.carousel.css" rel="stylesheet">
    <link href="css/owl.theme.css" rel="stylesheet">
	<link href="css/style.css" rel="stylesheet">
	<link href="css/animate.css" rel="stylesheet">
    <link href="css/loader.css" rel="stylesheet">

	<link rel="stylesheet" href="css/magnific-popup.css">

SuperJEnalotto

Finalmente il sistema matematico per generare i numeri vincenti!

Genera i miei numeri!

Come funziona

				<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-ex1-collapse">
					Toggle navigation

				</button>
				SuperJenalotto

Come Funziona?

Genera la tua giocata!

Come funziona?

Il primo sistema matematico/statistico per generare le migliori giocate al SuperEnalotto!

Strategico!

                        SuperJenalotto si basa sulla
 Legge Dei Grandi Numeri .

                        Le giocate proposte sono univoche dal 1997!

Vincente!

Nell'ultimo concorso sono stati vinti più di € 3 milioni al SuperEnalotto!

                       Che aspetti a vincere pure te?

Intelligente!

                        Qual'è la probabilità che vengano estratti i numeri già usciti?

                        Risparmia i tuoi soldi evitando le giocate più improbabili!

Performante!

Grazie alla potenza del cloud computing il SuperJenalotto è in grado di generare una giocata valida in pochi secondi!

Gratis!

Questo servizio è GRATUITO!
 Gioca subito i numeri generati dal sistema, potresti essere tu il vincitore del jackpot di oltre €130 milioni!!

Anonimo!

                     Non ti chiediamo di registrarti, nè raccogliamo dati su di te. Ogni giocata è anonima ed univoca!

Crea la tua giocata!

                        Genera la tua giocata! Un algoritmo genetico genererà una
                        sequenza numerica univoca, mai estratta da quando esiste il SuperEnalotto (3 dicembre 1997!!!)

                        In pochi secondi, grazie alla potenza del cloud computing, il sistema analizzerà tutti i numeri estratti fino ad oggi, ed individuerà una tra le giocate più singolari tra tutto il pool di giocate possibili!

Ottieni una giocata

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

La tua giocata

<canvas id="chart_div" width="130" height="130"></canvas>

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

Dicono di noi

Please enable JavaScript to view the comments powered by Disqus.


text:
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Rayleigh Distribution</title>
<link rel="stylesheet" href="../../../../../../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.77.1">
<link rel="home" href="../../../../index.html" title="Math Toolkit">
<link rel="up" href="../dists.html" title="Distributions">
<link rel="prev" href="poisson_dist.html" title="Poisson Distribution">
<link rel="next" href="skew_normal_dist.html" title="Skew Normal Distribution">

Home
Libraries
People
FAQ
More

Rayleigh
          Distribution

#include <boost/math/distributions/rayleigh.hpp>

namespace boost{ namespace math{

template <class RealType = double,
          class Policy   = policies::policy<> >
class rayleigh_distribution;

typedef rayleigh_distribution<> rayleigh;

template <class RealType, class Policy>
class rayleigh_distribution
{
public:
   typedef RealType value_type;
   typedef Policy   policy_type;
   // Construct:
   rayleigh_distribution(RealType sigma = 1)
   // Accessors:
   RealType sigma()const;
};

}} // namespaces

            The Rayleigh
            distribution is a continuous distribution with the probability
            density function:

            f(x; sigma) = x * exp(-x2/2 σ2) / σ2

            For sigma parameter σ   > 0, and x > 0.

            The Rayleigh distribution is often used where two orthogonal components
            have an absolute value, for example, wind velocity and direction may
            be combined to yield a wind speed, or real and imaginary components may
            have absolute values that are Rayleigh distributed.

            The following graph illustrates how the Probability density Function(pdf)
            varies with the shape parameter σ:

            and the Cumulative Distribution Function (cdf)

            Related
            distributions

            The absolute value of two independent normal distributions X and Y, √ (X2 +
            Y2) is a Rayleigh distribution.

            The Chi,
            Rice
            and Weibull
            distributions are generalizations of the Rayleigh
            distribution.

            Member
            Functions

rayleigh_distribution(RealType sigma = 1);

            Constructs a Rayleigh
            distribution with σ sigma.

            Requires that the σ parameter is greater than zero, otherwise calls domain_error.

RealType sigma()const;

            Returns the sigma parameter of this distribution.

            Non-member
            Accessors

            All the usual non-member
            accessor functions that are generic to all distributions are supported:
            Cumulative Distribution Function,
            Probability Density Function, Quantile, Hazard
            Function, Cumulative Hazard Function,
            mean, median,
            mode, variance,
            standard deviation, skewness,
            kurtosis, kurtosis_excess,
            range and support.

            The domain of the random variable is [0, max_value].

            Accuracy

            The Rayleigh distribution is implemented in terms of the standard library
            sqrt and exp and as such should have very low
            error rates. Some constants such as skewness and kurtosis were calculated
            using NTL RR type with 150-bit accuracy, about 50 decimal digits.

            Implementation

            In the following table σ   is the sigma parameter of the distribution, x
            is the random variate, p is the probability and
            q = 1-p.

<colgroup>
<col>
<col>
</colgroup>

                      Function

                      Implementation Notes

                      pdf

                      Using the relation: pdf = x * exp(-x2)/2 σ2

                      cdf

                      Using the relation: p = 1 - exp(-x2/2) σ2   = -expm1(-x2/2)
                      σ2

                      cdf complement

                      Using the relation: q = exp(-x2/ 2) * σ2

                      quantile

                      Using the relation: x = sqrt(-2 * σ 2) * log(1 - p)) = sqrt(-2
                      * σ 2) * log1p(-p))

                      quantile from the complement

                      Using the relation: x = sqrt(-2 * σ 2) * log(q))

                      mean

                      σ * sqrt(π/2)

                      variance

                      σ2 * (4 - π/2)

                      mode

                      σ

                      skewness

                      Constant from Weisstein,
                      Eric W. "Weibull Distribution." From MathWorld--A
                      Wolfram Web Resource.

                      kurtosis

                      Constant from Weisstein,
                      Eric W. "Weibull Distribution." From MathWorld--A
                      Wolfram Web Resource.

                      kurtosis excess

                      Constant from Weisstein,
                      Eric W. "Weibull Distribution." From MathWorld--A
                      Wolfram Web Resource.

            References

                http://en.wikipedia.org/wiki/Rayleigh_distribution

                Weisstein,
                Eric W. "Rayleigh Distribution." From MathWorld--A Wolfram
                Web Resource.

Copyright © 2006-2010, 2012 John Maddock, Paul A. Bristow, Hubert Holin, Xiaogang
      Zhang, Bruno Lalande, Johan Råde, Gautam Sewani, Thijs van den Berg and Benjamin
      Sobotta

        Distributed under the Boost Software License, Version 1.0. (See accompanying
        file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)


text:
<project name="CUSTOM-imports">

	<property environment="env"/>

	<!--
		below sets default value for AUNIT_IGNORE_IMPORTS,
		if env variable already exists it will not override
	-->
	<if>
	<equals arg1="${env.AUNIT_IMPORT_CMF}" arg2="true"/>
	<then>
    	<import file="${env.APAMA_FOUNDATION_HOME}/ant_macros/CMF-macros.xml" />
	</then>
	</if>
</project>


text:
from logging import getLogger, StreamHandler, DEBUG
import os
import tempfile
from io import BytesIO
from datetime import datetime
#
from serializer import Serializer
from ocrengine import OCREngine
from naivebayes import NaiveBayes
from dataprocessor import DataProcessor, ImageType

logger = getLogger('myapp.tweetbot')
if __name__ == "__main__":
    handler = StreamHandler()
    handler.setLevel(DEBUG)
    logger.setLevel(DEBUG)
    logger.addHandler(handler)

class Ranking(object):
    def __init__(self, config):
        self.ocr = OCREngine()
        self.naivebayes = NaiveBayes()
        self.naivebayes.human_labels = self.ocr.settings['translate']['country']

    def create_TemporyFile(self, buffer, verbose=False):
        """

            @param {io.BytesIO}buffer
                   {bool}verbose
            @return {string}create file tempory file
        """
        temp_file_name = ''
        with tempfile.NamedTemporaryFile(delete=False) as temp:
            temp.write(buffer.getvalue())
            temp_file_name = temp.name
            if verbose:
                logger.info(temp_file_name)
        return temp_file_name

    def getResult(self, src, save_image=False):
        """
            @param {string} src
                   {bool}save_image output debug image
            @return {OCRDocument} doucument
        """
        pro = DataProcessor(src, ImageType.RAW, save_image=save_image)
        if pro.prepare() is None:
            logger.error('image error:{0}'.format(src))
            return None
        buffer = pro.tobinary(pro.batch())
        temp_file_name = self.create_TemporyFile(buffer, True)

        document = self.ocr.recognize(temp_file_name)
        os.remove(temp_file_name)

        output = '#' + datetime.now().strftime('%F %T.%f')[:-3] + '\n'
        output += '\n'.join(document.names()) + '\n'
        with Serializer.open_stream('../temp/corpus.txt', mode='a') as file:
            file.write(output)

        # ocr corpus data -> NaiveBayes classifier
        # ranking name swap
        change = self.naivebayes.predict_all(document.names())
        #doucument.changeNames(change)

        document.dump()
        return document

def main():
    config = Serializer.load_json('../resource/setting.json')
    r = Ranking(config)
    # benchMark
    ele = ['../backup/hints/201702190825_0565e4fcbc166f00577cbd1f9a76f8c7.png',
           #'../images/backup/2017-03-12_0443_Geburand.png',
        #     '../backup/test/201702192006_2e268d7508c20aa00b22dfd41639d65e.png',
        ] * 1
    for media in ele:
        logger.info(media)
        document = r.getResult(media, True)
        logger.info(document.ranking)
if __name__ == "__main__":
    main()


text:
<?php

namespace Funstaff\RefLibRis;

/**
 * RisFieldsMappingInterface
 *
 * @author Bertrand Zuchuat <bertrand.zuchuat@gmail.com>
 */
interface RisFieldsMappingInterface
{
    /**
     * @param string $field
     * @return null|string
     */
    public function findRisFieldByFieldName(string $field);

    /**
     * @return array
     */
    public function getAllRisFields();
}


text:
package brooklyn.clocker.example;

import brooklyn.catalog.Catalog;
import brooklyn.catalog.CatalogConfig;
import brooklyn.entity.basic.AbstractApplication;
import brooklyn.entity.container.DockerAttributes;
import brooklyn.entity.java.UsesJmx;
import brooklyn.entity.java.UsesJmx.JmxAgentModes;
import brooklyn.entity.messaging.activemq.ActiveMQBroker;
import brooklyn.entity.proxying.EntitySpec;
import brooklyn.event.basic.PortAttributeSensorAndConfigKey;
import brooklyn.location.basic.PortRanges;

@Catalog(name="ActiveMQ Broker",
        description="Single ActiveMQ message broker",
        iconUrl="classpath://activemq-logo.png")
public class ActiveMQApplication extends AbstractApplication {

    @CatalogConfig(label="OpenWire Port", priority=0)
    public static final PortAttributeSensorAndConfigKey OPEN_WIRE_PORT = ActiveMQBroker.OPEN_WIRE_PORT;

    @CatalogConfig(label="Jetty Port", priority=0)
    public static final PortAttributeSensorAndConfigKey AMQ_JETTY_PORT = ActiveMQBroker.AMQ_JETTY_PORT;

    @Override
    public void initApp() {
        addChild(EntitySpec.create(ActiveMQBroker.class)
                .displayName("ActiveMQ Broker")
                .configure(DockerAttributes.DOCKERFILE_URL, "https://s3-eu-west-1.amazonaws.com/brooklyn-docker/UsesJavaDockerfile")
                .configure(UsesJmx.USE_JMX, Boolean.TRUE)
                .configure(UsesJmx.JMX_AGENT_MODE, JmxAgentModes.JMXMP)
                .configure(UsesJmx.JMX_PORT, PortRanges.fromString("30000+"))
                .configure(ActiveMQBroker.OPEN_WIRE_PORT, getConfig(OPEN_WIRE_PORT))
                .configure(ActiveMQBroker.AMQ_JETTY_PORT, getConfig(AMQ_JETTY_PORT)));
    }
}


text:
#ifndef __USBHW_H_SAM3U
#define __USBHW_H_SAM3U

/* USB Hardware Variables */
extern volatile BOOL USB_HighSpeed;

/* USB Hardware Functions */
extern void USB_Init        (void);
extern void USB_Connect     (BOOL con);
extern void USB_Reset       (void);
extern void USB_Suspend     (void);
extern void USB_Resume      (void);
extern void USB_WakeUp      (void);
extern void USB_WakeUpCfg   (BOOL cfg);
extern void USB_SetAddress  (U32  adr);
extern void USB_Configure   (BOOL cfg);
extern void USB_ConfigEP    (USB_ENDPOINT_DESCRIPTOR *pEPD);
extern void USB_DirCtrlEP   (U32  dir);
extern void USB_EnableEP    (U32  EPNum);
extern void USB_DisableEP   (U32  EPNum);
extern void USB_ResetEP     (U32  EPNum);
extern void USB_SetStallEP  (U32  EPNum);
extern void USB_ClrStallEP  (U32  EPNum);
extern void USB_ClearEPBuf  (U32  EPNum);
extern U32  USB_ReadEP      (U32  EPNum, U8 *pData);
extern U32  USB_WriteEP     (U32  EPNum, U8 *pData, U32 cnt);
extern U32  USB_GetFrame    (void);

#endif  /* __USBHW_H_SAM3U */


text:
Nash equilibria noncooperative games.

This tool serves to computing [Nash equilibrium](http://en.wikipedia.org/wiki/Nash_equilibrium) in
[noncooperative games](http://en.wikipedia.org/wiki/Non-cooperative_game).
## Installation ##

    python setup.py install

## Usage ##

### Command-line ###

You can invoke the Nash equilibria computing with this parameters:
```
usage: neng [-h] -f FILE [-m {L-BFGS-B,SLSQP,CMAES,support_enumeration,pne}]
            [-e] [-p] [-c] [-t {normalization,penalization}]
            [-l {DEBUG,INFO,WARNING,ERROR,CRITICAL}] [--log-file LOG_FILE]

NenG - Nash Equilibrium Noncooperative Games.
Tool for computing Nash equilibria in noncooperative games.
Specifically:
All pure Nash equilibria in all games (--method=pne).
All mixed Nash equilibria in two-players games (--method=support_enumeration).
One sample mixed Nash equilibria in n-players games (--method={CMAES,L-BFGS-B,SLSQP}).

optional arguments:
  -h, --help            show this help message and exit
  -f FILE, --file FILE  File where game in nfg format is saved.
  -m {L-BFGS-B,SLSQP,CMAES,support_enumeration,pne},
        --method {L-BFGS-B,SLSQP,CMAES,support_enumeration,pne}
                        Method to use for computing Nash equlibria.
  -e, --elimination     Use Iterative Elimination of Strictly Dominated
                        Strategies before computing NE.
  -p, --payoff          Print also players payoff with each Nash equilibrium.
  -c, --checkNE         After computation check if found strategy profile is
                        really Nash equilibrium.
  -t {normalization,penalization}, --trim {normalization,penalization}
                        Method for keeping strategy profile in probability
                        distribution universum.
  -l {DEBUG,INFO,WARNING,ERROR,CRITICAL}, --log {DEBUG,INFO,WARNING,ERROR,CRITICAL}
                        Level of logs to save/print
  --log-file LOG_FILE   Log file. If omitted log is printed to stdout.
```

File format comes from [gambit file formats](http://www.gambit-project.org/doc/formats.html)

### Python API ###
You can find current API documentation at [readthedocs](https://neng.readthedocs.org/en/latest/).

### Travis CI ###
Every commit neng is built and tested using Travis CI. You can see result at [neng travis page](https://travis-ci.org/Artimi/neng).

## Bachelor thesis ##
This program result from my [bachelor thesis](https://www.fit.vutbr.cz/study/DP/BP.php?id=15471&y=2012) (in czech). In thesis are described basic math rules of Game theory and algorithms used in the program. It also contains some experiments and testing. But naturally development is moving forward and thesis is becoming obsolete with every commit.

## License ##
This program is licensed under MIT license.


text:
@interface RootViewController : RDVTabBarController

@end


text:
<?xml version="1.0" encoding="ascii"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
          "DTD/xhtml1-transitional.dtd">

  <title>web2py.gluon.serializers</title>
  <link rel="stylesheet" href="epydoc.css" type="text/css" />

         Home

         Trees

         Indices

         Help

web2py Web Framework

        Package web2py ::
        Package gluon ::
        Module serializers

[hide private]

[frames] | no frames]

Module serializers
source code

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)

        Functions
        [hide private]

          custom_json(o)

            source code

          xml_rec(value,
        key)

            source code

          xml(value,
        encoding='UTF-8',
        key='document')

            source code

          json(value,
        default=<function custom_json at 0x108c0c8>)

            source code

          csv(value)

            source code

          rss(feed)

            source code

         Home

         Trees

         Indices

         Help

web2py Web Framework

    Generated by Epydoc 3.0beta1 on Mon Apr 25 15:04:05 2011

      http://epydoc.sourceforge.net


text:
SUFFIXES:

default: dist

include environment.mk

JAVA_SOURCES := \
    $(filter-out $(SOURCES_TO_EXCLUDE:%=$(SRC_DIR)/%),$(shell find $(SRC_DIR) -name *.java))

JAVA_SOURCES_MANIFEST = $(BUILD_DIR)/java_sources.mf
OBJC_SOURCES_MANIFEST = $(BUILD_DIR)/objc_sources.mf

CLASSPATH = $(DIST_JAR_DIR)/$(GUAVA_JAR):$(DIST_JAR_DIR)/j2objc_joda_convert.jar:$(DIST_JAR_DIR)/j2objc_annotations.jar
SOURCEPATH = $(SRC_DIR)

INCLUDE_DIRS = $(GEN_OBJC_DIR)

J2OBJCC = $(ARCH_BIN_DIR)/j2objcc -c -fobjc-abi-version=2 -fobjc-legacy-dispatch \
  $(INCLUDE_DIRS:%=-I%)

TRANSLATE_JAVA_FULL = $(JAVA_SOURCES)
TRANSLATE_JAVA_RELATIVE = $(JAVA_SOURCES:$(SRC_DIR)/%=%)
TRANSLATE_ARGS = --segmented-headers --extract-unsequenced --batch-translate-max=300 \
    -cp $(CLASSPATH) -sourcepath $(SOURCEPATH) -encoding UTF-8 -J-Xmx2G \
    --hide-private-members --final-methods-as-functions -q
include ../make/translate.mk

FAT_LIB_NAME = joda_time
FAT_LIB_SOURCES_RELATIVE = $(TRANSLATE_SOURCES:$(GEN_OBJC_DIR)/%=%)
FAT_LIB_SOURCE_DIRS = $(GEN_OBJC_DIR)
FAT_LIB_COMPILE = $(J2OBJCC)
include ../make/fat_lib.mk

fat_lib_dependencies: jre_emul_dist joda_convert_dist

DIST_LIBRARY = $(ARCH_LIB_DIR)/libjoda_time.a
JAR = $(BUILD_DIR)/j2objc_joda_time.jar
DIST_JAR = $(DIST_JAR_DIR)/j2objc_joda_time.jar
DIST_RESOURCES_DIR = $(DIST_JAR_DIR)/resources
DIST_RESOURCES_JT_DIR = $(DIST_RESOURCES_DIR)/joda_time

JAR_STAGE_DIR = /tmp/j2objc_joda_time

dist: $(DIST_LIBRARY) $(DIST_JAR)
	@(cd $(GEN_OBJC_DIR) && tar cf - $(TRANSLATE_HEADERS:$(GEN_OBJC_DIR)/%=%)) \
	    | (cd $(ARCH_INCLUDE_DIR); tar xfp -)

test: $(FAT_LIB_LIBRARY)
	@$(MAKE) -f tests.mk test

clean:
	@rm -rf $(BUILD_DIR) $(DIST_LIBRARY) $(ARCH_INCLUDE_DIR)/org/joda $(DIST_JAR)

java: $(DIST_JAR)

# TODO(kstanger): Add -Xlint:unchecked once warnings are fixed.
$(JAR): $(JAVA_SOURCES) | $(BUILD_DIR) java_deps_dist annotations_dist
	@echo "building j2objc_joda_time.jar"
	@rm -rf $(JAR_STAGE_DIR)
	@mkdir $(JAR_STAGE_DIR)
	@cp -R $(RESOURCES_DIR)/* $(JAR_STAGE_DIR)
	@mkdir $(DIST_RESOURCES_DIR)
	@mkdir $(DIST_RESOURCES_JT_DIR)
	@cp -R $(RESOURCES_DIR)/* $(DIST_RESOURCES_JT_DIR)
	@$(JAVAC) -sourcepath $(SOURCEPATH) -cp $(CLASSPATH) -encoding UTF-8 \
	    -d $(JAR_STAGE_DIR) -source 1.7 -target 1.7 \
	    -bootclasspath $(DIST_JAR_DIR)/jre_emul.jar $^
	@jar cf $@ -C $(JAR_STAGE_DIR) .

$(DIST_JAR): $(JAR) | $(DIST_JAR_DIR)
	@install -m 0644 $< $@

$(DIST_LIBRARY): $(FAT_LIB_LIBRARY) | $(ARCH_LIB_DIR)
	install -m 0644 $< $@

$(JAVA_SOURCES_MANIFEST): $(JAVA_SOURCES) | $(BUILD_DIR)
	@echo "Building $$(basename $@)"
	@if [ -e $@ ]; then rm $@; fi
	@files='$^' && for i in $$files; do echo $$i >> $@; done

java_sources_manifest: $(JAVA_SOURCES_MANIFEST)
	@:

$(OBJC_SOURCES_MANIFEST): $(TRANSLATE_JAVA_FULL) | $(BUILD_DIR)
	@echo "Building $$(basename $@)"
	@if [ -e $@ ]; then rm $@; fi
	@files='$(sort $(TRANSLATE_OBJC))' && for i in $$files; do \
	  echo $$i >> $@; \
	done

objc_sources_manifest: $(OBJC_SOURCES_MANIFEST)
	@:

find_cycles: $(JAVA_SOURCES_MANIFEST) | cycle_finder_dist jre_emul_java_manifest
	$(DIST_DIR)/cycle_finder -sourcepath $(SOURCEPATH) -cp $(CLASSPATH) \
	  -w ../jre_emul/cycle_whitelist.txt -w cycle_whitelist \
	  -s ../jre_emul/$(BUILD_DIR_NAME)/java_sources.mf -s $(JAVA_SOURCES_MANIFEST)


text:
package org.apache.hadoop.hbase.replication.regionserver;

import java.io.IOException;
import java.util.concurrent.atomic.AtomicLong;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseClassTestRule;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.HBaseTestingUtility;
import org.apache.hadoop.hbase.HColumnDescriptor;
import org.apache.hadoop.hbase.HConstants;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.HTestConst;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Admin;
import org.apache.hadoop.hbase.client.ConnectionFactory;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.ResultScanner;
import org.apache.hadoop.hbase.client.Scan;
import org.apache.hadoop.hbase.client.Table;
import org.apache.hadoop.hbase.replication.ReplicationPeerConfig;
import org.apache.hadoop.hbase.testclassification.LargeTests;
import org.apache.hadoop.hbase.testclassification.ReplicationTests;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.hbase.util.EnvironmentEdgeManager;
import org.apache.hadoop.hbase.util.Threads;
import org.apache.hadoop.hbase.zookeeper.MiniZooKeeperCluster;
import org.apache.hadoop.hbase.zookeeper.ZKWatcher;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.rules.TestName;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Category({ ReplicationTests.class, LargeTests.class })
public class TestGlobalReplicationThrottler {

  @ClassRule
  public static final HBaseClassTestRule CLASS_RULE =
      HBaseClassTestRule.forClass(TestGlobalReplicationThrottler.class);

  private static final Logger LOG = LoggerFactory.getLogger(TestGlobalReplicationThrottler.class);
  private static final int REPLICATION_SOURCE_QUOTA = 200;
  private static int numOfPeer = 0;
  private static Configuration conf1;
  private static Configuration conf2;

  private static HBaseTestingUtility utility1;
  private static HBaseTestingUtility utility2;

  private static final byte[] famName = Bytes.toBytes("f");
  private static final byte[] VALUE = Bytes.toBytes("v");
  private static final byte[] ROW = Bytes.toBytes("r");
  private static final byte[][] ROWS = HTestConst.makeNAscii(ROW, 100);

  @Rule
  public TestName name = new TestName();

  @BeforeClass
  public static void setUpBeforeClass() throws Exception {
    conf1 = HBaseConfiguration.create();
    conf1.set(HConstants.ZOOKEEPER_ZNODE_PARENT, "/1");
    conf1.setLong("replication.source.sleepforretries", 100);
    // Each WAL is about 120 bytes
    conf1.setInt(HConstants.REPLICATION_SOURCE_TOTAL_BUFFER_KEY, REPLICATION_SOURCE_QUOTA);
    conf1.setLong("replication.source.per.peer.node.bandwidth", 100L);

    utility1 = new HBaseTestingUtility(conf1);
    utility1.startMiniZKCluster();
    MiniZooKeeperCluster miniZK = utility1.getZkCluster();
    new ZKWatcher(conf1, "cluster1", null, true);

    conf2 = new Configuration(conf1);
    conf2.set(HConstants.ZOOKEEPER_ZNODE_PARENT, "/2");

    utility2 = new HBaseTestingUtility(conf2);
    utility2.setZkCluster(miniZK);
    new ZKWatcher(conf2, "cluster2", null, true);

    ReplicationPeerConfig rpc = new ReplicationPeerConfig();
    rpc.setClusterKey(utility2.getClusterKey());

    utility1.startMiniCluster();
    utility2.startMiniCluster();

    Admin admin1 = ConnectionFactory.createConnection(conf1).getAdmin();
    admin1.addReplicationPeer("peer1", rpc);
    admin1.addReplicationPeer("peer2", rpc);
    admin1.addReplicationPeer("peer3", rpc);
    numOfPeer = admin1.listReplicationPeers().size();
  }

  @AfterClass
  public static void tearDownAfterClass() throws Exception {
    utility2.shutdownMiniCluster();
    utility1.shutdownMiniCluster();
  }

  volatile private boolean testQuotaPass = false;
  volatile private boolean testQuotaNonZero = false;
  @Test
  public void testQuota() throws IOException {
    final TableName tableName = TableName.valueOf(name.getMethodName());
    HTableDescriptor table = new HTableDescriptor(tableName);
    HColumnDescriptor fam = new HColumnDescriptor(famName);
    fam.setScope(HConstants.REPLICATION_SCOPE_GLOBAL);
    table.addFamily(fam);
    utility1.getAdmin().createTable(table);
    utility2.getAdmin().createTable(table);

    Thread watcher = new Thread(()->{
      Replication replication = (Replication)utility1.getMiniHBaseCluster()
          .getRegionServer(0).getReplicationSourceService();
      AtomicLong bufferUsed = replication.getReplicationManager().getTotalBufferUsed();
      testQuotaPass = true;
      while (!Thread.interrupted()) {
        long size = bufferUsed.get();
        if (size > 0) {
          testQuotaNonZero = true;
        }
        //the reason here doing "numOfPeer + 1" is because by using method addEntryToBatch(), even the
        // batch size (after added last entry) exceeds quota, it still keeps the last one in the batch
        // so total used buffer size can be one "replication.total.buffer.quota" larger than expected
        if (size > REPLICATION_SOURCE_QUOTA * (numOfPeer + 1)) {
          // We read logs first then check throttler, so if the buffer quota limiter doesn't
          // take effect, it will push many logs and exceed the quota.
          testQuotaPass = false;
        }
        Threads.sleep(50);
      }
    });
    watcher.start();

    try(Table t1 = utility1.getConnection().getTable(tableName);
        Table t2 = utility2.getConnection().getTable(tableName)) {
      for (int i = 0; i < 50; i++) {
        Put put = new Put(ROWS[i]);
        put.addColumn(famName, VALUE, VALUE);
        t1.put(put);
      }
      long start = EnvironmentEdgeManager.currentTime();
      while (EnvironmentEdgeManager.currentTime() - start < 180000) {
        Scan scan = new Scan();
        scan.setCaching(50);
        int count = 0;
        try (ResultScanner results = t2.getScanner(scan)) {
          for (Result result : results) {
            count++;
          }
        }
        if (count < 50) {
          LOG.info("Waiting all logs pushed to slave. Expected 50 , actual " + count);
          Threads.sleep(200);
          continue;
        }
        break;
      }
    }

    watcher.interrupt();
    Assert.assertTrue(testQuotaPass);
    Assert.assertTrue(testQuotaNonZero);
  }

}


text:
namespace arm
{

namespace pipe
{

constexpr inline uint32_t EncodeVersion(uint32_t major, uint32_t minor, uint32_t patch)
{
    return (major << 22) | (minor << 12) | patch;
}

// Encodes a semantic version https://semver.org/ into a 32 bit integer in the following fashion
//
// bits 22:31 major: Unsigned 10-bit integer. Major component of the schema version number.
// bits 12:21 minor: Unsigned 10-bit integer. Minor component of the schema version number.
// bits 0:11  patch: Unsigned 12-bit integer. Patch component of the schema version number.
//
class Version
{
public:
    Version(uint32_t encodedValue)
    {
        m_Major = (encodedValue >> 22) & 1023;
        m_Minor = (encodedValue >> 12) & 1023;
        m_Patch = encodedValue & 4095;
    }

    Version(uint32_t major, uint32_t minor, uint32_t patch) :
        m_Major(major),
        m_Minor(minor),
        m_Patch(patch)
    {}

    uint32_t GetEncodedValue()
    {
        return EncodeVersion(m_Major, m_Minor, m_Patch);
    }

    uint32_t GetMajor() { return m_Major; }
    uint32_t GetMinor() { return m_Minor; }
    uint32_t GetPatch() { return m_Patch; }

    bool operator==(const Version& other) const
    {
        return m_Major == other.m_Major && m_Minor == other.m_Minor && m_Patch == other.m_Patch;
    }

    std::string ToString() const
    {
        constexpr char separator = '.';

        std::stringstream stringStream;
        stringStream << m_Major << separator << m_Minor << separator << m_Patch;

        return stringStream.str();
    }

private:
    uint32_t m_Major;
    uint32_t m_Minor;
    uint32_t m_Patch;
};

inline std::ostream& operator<<(std::ostream& os, const Version& version)
{
    os << version.ToString();
    return os;
}

} // namespace pipe

} // namespace arm


text:
package quant

import (
	"time"
)

func ExampleCounter() {
	registry := NewRegistry("my-registry")
	counter := registry.NewCounter("my-counter")

	// use the counter
	counter.Increment() // or counter.Decrement()

	// write the counter value to stdout
	registry.Report(StdoutReporter)
}

func readMemoryUsageInMB() float64 {
	return 0
}

func ExampleGauge() {
	registry := NewRegistry("my-registry")
	registry.NewGauge("my-gauge", readMemoryUsageInMB)

	// write the gauge value to stdout
	registry.Report(StdoutReporter)
}

func ExampleTimer() {
	registry := NewRegistry("my-registry")
	timer := registry.NewTimer("my-timer", Milliseconds)

	stopwatch := timer.Start()
	// execute a task
	stopwatch.Record()

	// write the timer value to stout
	registry.Report(StdoutReporter)
}

func ExampleRegistry_report() {
	registry := NewRegistry("my-registry")
	// create and use some metrics

	registry.Report(StdoutReporter)
}

func ExampleReporting() {
	registry := NewRegistry("my-registry")

	// write the metrics of registry every five seconds to stdout
	reporting := StartReporting(5*time.Second, StdoutReporter)
	reporting.Attach(registry)

	// create and use some metric objects
}


text:
"""
Common routines for entering and classifiying opcodes. Inspired by,
limited by, and somewhat compatible with the corresponding
Python opcode.py structures
"""

from copy import deepcopy
from xdis.cross_dis import (
    findlinestarts, findlabels, get_jump_target_maps, get_jump_targets
)
from xdis import wordcode
from xdis import IS_PYPY, PYTHON_VERSION

cmp_op = ('<', '<=', '==', '!=', '>', '>=', 'in', 'not-in', 'is',
        'is-not', 'exception-match', 'BAD')

# Opcodes greater than 90 take an instruction operand or "argument"
# as opcode.py likes to call it.
HAVE_ARGUMENT = 90

fields2copy = """
hascompare hascondition
hasconst hasfree hasjabs hasjrel haslocal
hasname hasnargs hasstore hasvargs oppop oppush
nofollow
""".split()

def init_opdata(l, from_mod, version=None, is_pypy=False):
    """Sets up a number of the structures found in Python's
    opcode.py. Python opcode.py routines assign attributes to modules.
    In order to do this in a modular way here, the local dictionary
    for the module is passed.
    """

    if version:
        l['python_version'] = version
    l['is_pypy'] = is_pypy
    l['cmp_op'] = cmp_op
    l['HAVE_ARGUMENT'] = HAVE_ARGUMENT
    l['findlinestarts'] = findlinestarts
    if version <= 3.5:
        l['findlabels']     = findlabels
        l['get_jump_targets'] = get_jump_targets
        l['get_jump_target_maps']  = get_jump_target_maps
    else:
        l['findlabels']     = wordcode.findlabels
        l['get_jump_targets'] = wordcode.get_jump_targets
        l['get_jump_target_maps']  = wordcode.get_jump_target_maps

    l['opmap'] = deepcopy(from_mod.opmap)
    l['opname'] = deepcopy(from_mod.opname)

    for field in fields2copy:
        l[field] = list(getattr(from_mod, field))

def compare_op(l, name, op, pop=2, push=1):
    def_op(l, name, op, pop, push)
    l['hascompare'].append(op)

def conditional_op(l, name, op):
    l['hascompare'].append(op)

def const_op(l, name, op, pop=0, push=1):
    def_op(l, name, op, pop, push)
    l['hasconst'].append(op)

def def_op(l, op_name, opcode, pop=-2, push=-2, fallthrough=True):
    l['opname'][opcode] = op_name
    l['opmap'][op_name] = opcode
    l['oppush'][opcode] = push
    l['oppop'][opcode] = pop
    if not fallthrough:
        l['nofollow'].append(opcode)

def free_op(l, name, op, pop=0, push=1):
    def_op(l, name, op, pop, push)
    l['hasfree'].append(op)

def jabs_op(l, name, op, pop=0, push=0, conditional=False, fallthrough=True):
    def_op(l, name, op, pop, push, fallthrough=fallthrough)
    l['hasjabs'].append(op)
    if conditional:
        l['hascondition'].append(op)

def jrel_op(l, name, op, pop=0, push=0, conditional=False, fallthrough=True):
    def_op(l, name, op, pop, push)
    l['hasjrel'].append(op)
    if conditional:
        l['hascondition'].append(op)

def local_op(l, name, op, pop=0, push=1):
    def_op(l, name, op, pop, push)
    l['haslocal'].append(op)

def name_op(l, op_name, op_code, pop=-2, push=-2):
    def_op(l, op_name, op_code, pop, push)
    l['hasname'].append(op_code)

def nargs_op(l, name, op, pop=-2, push=-2, fallthrough=True):
    def_op(l, name, op, pop, push, fallthrough=fallthrough)
    l['hasnargs'].append(op)

def rm_op(l, name, op):
    """Remove an opcode. This is used when basing a new Python release off
    of another one, and there is an opcode that is in the old release
    that was removed in the new release.
    We are pretty aggressive about removing traces of the op.
    """

    # opname is an array, so we need to keep the position in there.
    l['opname'][op] = '<%s>' % op

    if op in l['hasconst']:
       l['hasconst'].remove(op)
    if op in l['hascompare']:
       l['hascompare'].remove(op)
    if op in l['hascondition']:
       l['hascondition'].remove(op)
    if op in l['hasfree']:
       l['hasfree'].remove(op)
    if op in l['hasjabs']:
       l['hasjabs'].remove(op)
    if op in l['hasname']:
       l['hasname'].remove(op)
    if op in l['hasjrel']:
       l['hasjrel'].remove(op)
    if op in l['haslocal']:
       l['haslocal'].remove(op)
    if op in l['hasname']:
       l['hasname'].remove(op)
    if op in l['hasnargs']:
       l['hasnargs'].remove(op)
    if op in l['hasvargs']:
       l['hasvargs'].remove(op)
    if op in l['nofollow']:
       l['nofollow'].remove(op)

    assert l['opmap'][name] == op
    del l['opmap'][name]

def store_op(l, name, op, pop=0, push=1, is_type="def"):
    if is_type == "name":
        name_op(l, name, op, pop, push)
    elif is_type == "local":
        local_op(l, name, op, pop, push)
    elif is_type == "free":
        free_op(l, name, op, pop, push)
    else:
        assert is_type == "def"
        def_op(l, name, op, pop, push)
    l['hasstore'].append(op)

# This is not in Python. The operand indicates how
# items on the pop from the stack. BUILD_TUPLE_UNPACK
# is line this.
def varargs_op(l, op_name, op_code, pop=-1, push=1):
    def_op(l, op_name, op_code, pop, push)
    l['hasvargs'].append(op_code)

# Some of the convoluted code below reflects some of the
# many Python idiocies over the years.

def finalize_opcodes(l):

    # Not sure why, but opcode.py address has opcode.EXTENDED_ARG
    # as well as opmap['EXTENDED_ARG']
    l['EXTENDED_ARG'] = l['opmap']['EXTENDED_ARG']

    # In Python 3.6+ this is 8, but we expect
    # those opcodes to set that
    if 'EXTENDED_ARG_SHIFT' not in l:
        l['EXTENDED_ARG_SHIFT'] = 16

    l['ARG_MAX_VALUE'] = (1 << l['EXTENDED_ARG_SHIFT']) - 1
    l['EXTENDED_ARG']  = l['opmap']['EXTENDED_ARG']

    l['opmap'] = fix_opcode_names(l['opmap'])

    # Now add in the attributes into the module
    for op in l['opmap']:
        l[op] = l['opmap'][op]
    l['JUMP_OPs'] = frozenset(l['hasjrel'] + l['hasjabs'])
    l['NOFOLLOW'] = frozenset(l['nofollow'])
    opcode_check(l)
    return

def fix_opcode_names(opmap):
    """
    Python stupidly named some OPCODES with a + which prevents using opcode name
    directly as an attribute, e.g. SLICE+3. So we turn that into SLICE_3 so we
    can then use opcode_23.SLICE_3.  Later Python's fix this.
    """
    return dict([(k.replace('+', '_'), v)
                  for (k, v) in opmap.items()])

def update_pj3(g, l):
    g.update({'PJIF': l['opmap']['POP_JUMP_IF_FALSE']})
    g.update({'PJIT': l['opmap']['POP_JUMP_IF_TRUE']})
    update_sets(l)

def update_pj2(g, l):
    g.update({'PJIF': l['opmap']['JUMP_IF_FALSE']})
    g.update({'PJIT': l['opmap']['JUMP_IF_TRUE']})
    update_sets(l)

def update_sets(l):
    l['COMPARE_OPS']     = frozenset(l['hascompare'])
    l['CONDITION_OPS']   = frozenset(l['hascondition'])
    l['CONST_OPS']       = frozenset(l['hasconst'])
    l['FREE_OPS']        = frozenset(l['hasfree'])
    l['JREL_OPS']        = frozenset(l['hasjrel'])
    l['JABS_OPS']        = frozenset(l['hasjabs'])
    l['JUMP_UNCONDITONAL']    = frozenset([l['opmap']['JUMP_ABSOLUTE'],
                                           l['opmap']['JUMP_FORWARD']])
    if l['python_version'] < 3.8:
        l['LOOP_OPS']        = frozenset([l['opmap']['SETUP_LOOP']])
    else:
        l['LOOP_OPS']        = frozenset()

    l['LOCAL_OPS']       = frozenset(l['haslocal'])
    l['JUMP_OPS']        = (l['JABS_OPS']
                              | l['JREL_OPS']
                              | l['LOOP_OPS']
                              | l['JUMP_UNCONDITONAL'])
    l['NAME_OPS']        = frozenset(l['hasname'])
    l['NARGS_OPS']       = frozenset(l['hasnargs'])
    l['VARGS_OPS']       = frozenset(l['hasvargs'])
    l['STORE_OPS']       = frozenset(l['hasstore'])

def extended_format_CALL_FUNCTION(opc, instructions):
    """call_function_inst should be a "CALL_FUNCTION_KW" instruction. Look in
    `instructions` to see if we can find a method name.  If not we'll
    return None.

    """
    # From opcode description: argc indicates the total number of positional and keyword arguments.
    # Sometimes the function name is in the stack arg positions back.
    call_function_inst = instructions[0]
    assert call_function_inst.opname == "CALL_FUNCTION"
    argc = call_function_inst.arg
    name_default, pos_args, = divmod(argc, 256)
    function_pos = pos_args + name_default*2 + 1
    assert len(instructions) >= function_pos + 1
    for i, inst in enumerate(instructions[1:]):
        if i + 1 == function_pos:
            i += 1
            break
        if inst.is_jump_target:
            i += 1
            break
        # Make sure we are in the same basic block
        # and ... ?
        opcode = inst.opcode
        if inst.optype in ("nargs", "vargs"):
            break
        if inst.opname == "LOAD_ATTR" or inst.optype != "name":
            function_pos += (opc.oppop[opcode] - opc.oppush[opcode]) + 1
        if inst.opname in ("CALL_FUNCTION", "CALL_FUNCTION_KW"):
            break
        pass

    s = ""
    if i == function_pos:
        if instructions[function_pos].opname in ("LOAD_CONST", "LOAD_GLOBAL",
                                                 "LOAD_ATTR", "LOAD_NAME"):
            s = resolved_attrs(instructions[function_pos:])
            s += ": "
            pass
        pass
    s += format_CALL_FUNCTION_pos_name_encoded(call_function_inst.arg)
    return s

def resolved_attrs(instructions):
    resolved = []
    for inst in instructions:
        name = inst.argrepr
        if name:
            if name[0] == "'" and name[-1] == "'":
                name = name[1:-1]
        else:
            name = ""
        resolved.append(name)
        if inst.opname != "LOAD_ATTR":
            break
    return ".".join(reversed(resolved))

def extended_format_ATTR(opc, instructions):
    if instructions[1].opname in ("LOAD_CONST", "LOAD_GLOBAL",
                                  "LOAD_ATTR", "LOAD_NAME"):
        return "%s.%s" % (instructions[1].argrepr, instructions[0].argrepr)

def extended_format_MAKE_FUNCTION_older(opc, instructions):
    """make_function_inst should be a "MAKE_FUNCTION" or "MAKE_CLOSURE" instruction. TOS
    should have the function or closure name.
    """
    # From opcode description: argc indicates the total number of positional and keyword arguments.
    # Sometimes the function name is in the stack arg positions back.
    assert len(instructions) >= 2
    inst = instructions[0]
    assert inst.opname in ("MAKE_FUNCTION", "MAKE_CLOSURE")
    s = ""
    code_inst = instructions[1]
    if code_inst.opname == "LOAD_CONST" and hasattr(code_inst.argval, "co_name"):
        s += "%s: " % code_inst.argval.co_name
        pass
    s += format_MAKE_FUNCTION_default_argc(inst.arg)
    return s

def extended_format_RAISE_VARARGS_older(opc, instructions):
    raise_inst = instructions[0]
    assert raise_inst.opname == "RAISE_VARARGS"
    assert len(instructions) >= 1
    if instructions[1].opname in ("LOAD_CONST", "LOAD_GLOBAL",
                                  "LOAD_ATTR", "LOAD_NAME"):
        return resolved_attrs(instructions[1:])
    return format_RAISE_VARARGS_older(raise_inst.argval)

def extended_format_RETURN_VALUE(opc, instructions):
    return_inst = instructions[0]
    assert return_inst.opname == "RETURN_VALUE"
    assert len(instructions) >= 1
    if instructions[1].opname in ("LOAD_CONST", "LOAD_GLOBAL",
                                  "LOAD_ATTR", "LOAD_NAME"):
        return resolved_attrs(instructions[1:])
    return None

def format_extended_arg(arg):
    return str(arg * (1 << 16))

def format_CALL_FUNCTION_pos_name_encoded(argc):
    """Encoded positional and named args. Used to
    up to about 3.6 where wordcodes are used and
    a different encoding occurs. Pypy36 though
    sticks to this encoded version though."""
    name_default, pos_args = divmod(argc, 256)
    return ("%d positional, %d named" % (pos_args, name_default))

# After Python 3.2
def format_MAKE_FUNCTION_arg(argc):
    name_and_annotate, pos_args = divmod(argc, 256)
    annotate_args, name_default = divmod(name_and_annotate, 256)
    return ("%d positional, %d name and default, %d annotations" %
            (pos_args, name_default, annotate_args))

# Up to and including Python 3.2
def format_MAKE_FUNCTION_default_argc(argc):
    return ("%d default parameters" % argc)

# Up until 3.7
def format_RAISE_VARARGS_older(argc):
    assert 0 <= argc <= 3
    if argc == 0:
        return "reraise"
    elif argc == 1:
        return "exception"
    elif argc == 2:
        return "exception, parameter"
    elif argc == 3:
        return "exception, parameter, traceback"

def opcode_check(l):
    """When the version of Python we are running happens
    to have the same opcode set as the opcode we are
    importing, we perform checks to make sure our opcode
    set matches exactly.
    """
    # Python 2.6 reports 2.6000000000000001
    if (abs(PYTHON_VERSION - l['python_version']) <= 0.01
        and IS_PYPY == l['is_pypy']):
        try:
            import dis
            opmap = fix_opcode_names(dis.opmap)
            # print(set(opmap.items()) - set(l['opmap'].items()))
            # print(set(l['opmap'].items()) - set(opmap.items()))

            assert all(item in opmap.items() for item in l['opmap'].items())
            assert all(item in l['opmap'].items() for item in opmap.items())
        except:
            pass

def dump_opcodes(opmap):
    """Utility for dumping opcodes"""
    op2name = {}
    for k in opmap.keys():
        op2name[opmap[k]] = k
    for i in sorted(op2name.keys()):
        print("%-3s %s" % (str(i), op2name[i]))


text:
using (FileStream fs = new FileStream("abc.txt", FileMode.Create)) {
    // Algum código...
}

{
    FileStream fs = new FileStream("abc.txt", FileMode.Create);
    try {
       // Algum código...
    } finally {
        if (fs != null)
            ((IDisposable)fs).Dispose();
    }
}

using var fs = new FileStream("abc.txt", FileMode.Create);

//https://pt.stackoverflow.com/q/163768/101


text:
import logging

from django.utils.deprecation import MiddlewareMixin

logger = logging.getLogger(__name__)

class TracebackLoggingMiddleware(MiddlewareMixin):
    """Middleware that logs exceptions.

    See http://djangosnippets.org/snippets/421/.

    To enable it, add
    'yourapp.middleware.TracebackLoggingMiddleware' to
    your setting.py's MIDDLEWARE.

    """
    def process_exception(self, request, exception):
        logger.exception(repr(request))


text:
require 'digest/md5'
require 'base64'

class User < ActiveRecord::Base
  self.table_name = "simplesecuritymanager_user"
	self.primary_key = "userID"

	# Relationships
	has_one :person, :foreign_key => 'fk_ssmUserId'
	has_many :authentications
	has_many :activity_bookmarks, -> { where(Bookmark.table_name + ".name = 'activity'") }, :class_name => 'Bookmark'
	has_many :activities, -> { order(TargetArea.table_name + ".name").includes(:target_area) }, :through => :activity_bookmarks
  has_one :balance_bookmark, -> { where(Bookmark.table_name + ".name = 'balance'") }, :class_name => 'Bookmark'

  # Virtual attribute for the unencrypted password
  attr_accessor :plain_password, :plain_password_confirmation

  validates_format_of       :username, :message => "must be an email address", :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i
  #validates_presence_of     :plain_password,                   :if => :password_required?
  #validates_presence_of     :plain_password_confirmation,      :if => :password_required?
  #validates_length_of       :plain_password, :within => 6..80, :if => :password_required?
  # validates_format_of       :plain_password, :message => "isn't secure enough (you must include upper and lower case letters)", :with => /[a-z]+.*[A-Z]+|[A-Z]+.*[a-z]+/, :if => :password_required?
  #validates_confirmation_of :plain_password,                   :if => :password_required?
  # validates_presence_of     :secret_question,                  :if => :password_required?
  # validates_presence_of     :secret_answer,                    :if => :password_required?
  validates_uniqueness_of   :username, :case_sensitive => false, :message => "is already registered in our system.  This may have occurred when you registered for a Campus Crusade related conference; therefore, you do not need to create a new account. If you need help with your password, please click on the appropriate link at the login screen.  If you still need assistance, please send an email to help@campuscrusadeforchrist.com describing your problem."

  before_save :encrypt_password
  before_create :stamp_created_on

  def secret_question() self[:passwordQuestion]; end
  def secret_question=(val) self[:passwordQuestion] = val; end
  def secret_answer() self[:passwordAnswer]; end
  def secret_answer=(val) self[:passwordAnswer] = val; end

  def self.find_by_id(id) self.find_by_userID(id); end

  # Authenticates a user by their login name and unencrypted password.  Returns the user or nil.
#  def self.authenticate(username, plain_password)
#    u = find_by_username(username) # need to get the salt
#    ret_val = u && u.authenticated?(plain_password) ? u : nil
#    u.stamp_last_login if ret_val
#    return ret_val
#  end

  def self.find_or_create_from_cas(atts)
    # Look for a user with this guid
    guid = att_from_receipt(atts, 'ssoGuid')
    first_name = att_from_receipt(atts, 'firstName')
    last_name = att_from_receipt(atts, 'lastName')
    email = atts['username']
    find_or_create_from_guid_or_email(guid, email, first_name, last_name)
  end

  def self.find_or_create_from_guid_or_email(guid, email, first_name, last_name, secure = true)
    if guid
      u = ::User.where(:globallyUniqueID => guid).first
    end

    # if we have a user by this method, great! update the email address if it doesn't match
    # We also need to make sure there isn't already another user with this email
    if u
      u.username = email if u.username != email && !User.find_by_username(email)
    else
      # If we didn't find a user with the guid, do it by email address and stamp the guid
      u = ::User.where(:username => email).first
      if u
        u.globallyUniqueID = guid
      else
        # If we still don't have a user in SSM, we need to create one.
        u = ::User.create!(:username => email, :globallyUniqueID => guid)
      end
    end
    # Update the password to match their gcx password too. This will save a round-trip later
    # u.plain_password = params[:plain_password]
    u.save(:validate => false) if secure

    # make sure we have a person
    unless u.person
      # Try to find a person with the same email address.  If multiple people are found, use
      # the one who's logged in most recently
      address = ::CurrentAddress.joins(:person => :user)
                                .where(:email => email)
                                .order("lastLogin DESC")
                                .first
      person = address.try(:person)

      # Attach the found person to the user, or create a new person
      u.person = person || ::Person.create!(:firstName => first_name,
                                          :lastName => last_name)
      u.person.fk_ssmUserId = u.id

      # Create a current address record if we don't already have one.
      u.person.current_address ||= ::CurrentAddress.create!(:fk_PersonID => u.person.id, :email => email)
      u.person.save(:validate => false)
    end
    u
  end

  def generate_password_key!
    self.update_attribute(:password_reset_key, Digest::MD5.hexdigest(username + 'yo mama' + Time.now.to_s) + '_' + username)
  end

  # Encrypts some data with the salt.
  def self.encrypt(plain_password)
    md5_password = Digest::MD5.digest(plain_password)
  	base64_password = Base64.encode64(md5_password).chomp
  	base64_password
  end

  # Encrypts the password with the user salt
  def encrypt(plain_password)
    self.class.encrypt(plain_password)
  end

  def authenticated?(plain_password)
    password == encrypt(plain_password)
  end

  def remember_token?
    remember_token_expires_at && Time.now < remember_token_expires_at
  end

  # These create and unset the fields required for remembering users between browser closes
  def remember_me
    self.remember_token_expires_at = 2.weeks.from_now
    self.remember_token            = encrypt("#{username}--#{remember_token_expires_at}")
    save(:validate => false)
  end

  def forget_me
    self.remember_token_expires_at = nil
    self.remember_token            = nil
    save(:validate => false)
  end

  def apply_omniauth(omniauth)
    self.username = omniauth['info']['email'] if username.blank?
    unless Authentication.find_by_provider_and_uid(omniauth['provider'], omniauth['uid'])
      authentication = authentications.build(:provider => omniauth['provider'], :uid => omniauth['uid'])
      authentication.token = omniauth['credentials']['token'] if omniauth['credentials']
    end
  end

	def stamp_last_login
	  self.lastLogin = Time.now
	  save!
	end

	# A generic method for stamping a user has logged into a tool
	def stamp_column(column)
		if(person = self.person)
			person[column] = Time.new.to_s
			person.save!
		end
	end

  def create_person_and_address(person_attributes = {})
    unless person
      new_hash = {:dateCreated => Time.now, :dateChanged => Time.now,
                  :createdBy => ApplicationController.application_name,
                  :changedBy => ApplicationController.application_name}
  	  person = Person.new(person_attributes.merge(new_hash))
  	  person.user = self
      person.save!
      address = Address.new(new_hash.merge({:email => self.username,
                                             :addressType => 'current'}))
      address.person = person
      address.save!
    end
    person
	end

	def create_person_from_omniauth(omniauth)
    unless person
      new_hash = {:dateCreated => Time.now, :dateChanged => Time.now,
                  :createdBy => ApplicationController.application_name,
                  :changedBy => ApplicationController.application_name}
  	  person = Person.new(new_hash.merge({:firstName => omniauth['first_name'], :lastName => omniauth['last_name']}))
  	  person.user = self
      person.save!
      address = Address.new(new_hash.merge({:email => self.username,
                                             :addressType => 'current'}))
      address.person = person
      address.save!
    end
    person
	end

	def self.create_new_user_from_cas(username, cas_extra_attributes)
    # Look for a user with this guid
    guid = cas_extra_attributes['ssoGuid']
    first_name = cas_extra_attributes['firstName']
    last_name = cas_extra_attributes['lastName']
    u = User.find(:first, :conditions => ["globallyUniqueID = ?", guid])
    # if we have a user by this method, great! update the email address if it doesn't match
    if u
      u.username = username
    else
      # If we didn't find a user with the guid, do it by email address and stamp the guid
      u = User.find(:first, :conditions => ["username = ?", username])
      if u
        u.globallyUniqueID = guid
      else
        # If we still don't have a user in SSM, we need to create one.
        u = User.new(:username => username.downcase, :globallyUniqueID => guid)
      end
    end
    # Update the password to match their gcx password too. This will save a round-trip later
    # u.plain_password = params[:plain_password]
    u.save(:validate => false)
    # make sure we have a person
    unless u.person
      u.create_person_and_address(firstName: first_name, lastName: last_name)
    end
    u
  end

  def password_required?
    (authentications.empty? && password.blank? && globallyUniqueID.blank?) || !plain_password.blank?
  end
  def remember_me
    remember_me_for 2.weeks
  end

  def remember_me_for(time)
    remember_me_until time.from_now.utc
  end

  def refresh_token
    remember_me_until 1.year.from_now
  end

  # Useful place to put the login methods
  def remember_me_until(time)
    self.lastLogin = ::Time.now
    self.remember_token_expires_at = time
    self.remember_token = encrypt("#{username}--#{remember_token_expires_at}")
    save(:validate => false)
  end

  protected
    # before filter
    def encrypt_password
      return if plain_password.blank?
  		self.password = encrypt(plain_password)
  	end

  	def stamp_created_on
  	  begin
    	  self.createdOn = Time.now
    	rescue; end
  	end

    # not sure why but cas sometimes sends the extra attributes as underscored
    def self.att_from_receipt(atts, key)
      atts[key] || atts[key.underscore]
    end
end


text:
<?php
namespace app\controllers;

use Yii;
use yii\web\Controller;
use yii\filters\AccessControl;
use app\components\Role;
use app\models\Employee;
use app\models\Leaves;
use app\models\LeaveBalance;
use yii\base\Model;

class ToolController extends Controller {
	/**
	 * Behaviour Function
	 * Control Access Control Rule
	 */
	public function behaviors() {
		return [
			'access' => [
				'class' => AccessControl::className(),
				'ruleConfig' => [
					'class' => Role::className(),
				],
				'only' => ['index', 'beginning-balance'],
				'rules' => [
					[
						'allow' => true,
						'actions' => ['beginning-balance'],
						'roles' => [
							Employee::ROLE_SENIOR_HRD,
							Employee::ROLE_MANAGER_HRD
						],
					],
				],
				'denyCallback' => function ($rule, $action) {
					echo ('You are not allowed to access this page');
				},
			],
		];
	}

	/**
	 *  Action Beginning Balance
	 * @return string
	 */
	public function actionBeginningBalance() {
		$users = Employee::getAllEmployee();
		$multipleModel = new Model();
		//$model = new \app\models\Leaves(['scenario' => 'search']);
		if (($multipleModel->loadMultiple($users, Yii::$app->request->post())) && ($multipleModel->validateMultiple($users))) {
			//only checklist will update
			if(isset($user->employee_id)) {
				$count = 0;
				$active_date =  preg_replace('!(\d+)/(\d+)/(\d+)!', '\3-\2-\1',$user->employee_date_from);
				$balanced = new LeaveBalance();
				$balanced->leave_balance_date = $active_date;
				$balanced->leave_balance_total = $user->EmployeeLeaveTotal;
				$balanced->leave_balance_description = "Saldo Awal Per Tanggal " .$user->employee_date_from;

				$updated = $balanced->findOne(['employee_id' => $user->employee_id,'leave_balance_date' => $active_date]);
				if($update) {
					$balanced = $updated;
					$balanced->update();
				} else {
					$balanced->insert();
				}
				$count++;
			}
			Yii::$app->session->setFlash('message','
 '.Yii::t('app','success').'! '.Yii::t('app/message','msg request has been saved').'
');
			return $this->redirect("report/balanced-card",301);

		}

		return $this->render('beginning-balance',[
				'title' => Yii::t('app','bulk beginning balance'),
				'users' => $users,
				//'model' => $model,
				//'dataProvider' => $model->getOutstandingLeaveDataProvider(Yii::$app->request->queryParams)
		]);
	}

}


text:
#import <UIKit/UIKit.h>

@import MaterialComponents;

@class MLKResult;

NS_ASSUME_NONNULL_BEGIN

/** Cell that shows details of a search result. */
@interface MLKResultCell : MDCBaseCell

/** Thumbnail of the result. */
@property(nonatomic, readonly) UIImageView *thumbnailImage;

/** Label showing the title of the result. */
@property(nonatomic, readonly) UILabel *titleLabel;

/** Label showing the details of the results. */
@property(nonatomic, readonly) UILabel *detailsLabel;

/** Label showing the item number of the result. */
@property(nonatomic, readonly) UILabel *itemNumberLabel;

/** Label showing the price of the result. */
@property(nonatomic, readonly) UILabel *priceLabel;

/**
 * Populates the content of the cell with a `Result` model.
 *
 * @param result The result info to populate the cell with.
 * @return YES if product is not nil, otherwise, NO.
 */
- (BOOL)isCellPopulatedWithResult:(nullable MLKResult *)result;

@end

NS_ASSUME_NONNULL_END


text:
<?xml version="1.0" encoding="UTF-8"?>
<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>cn.hybris</groupId>
	<artifactId>config-client</artifactId>
	<version>1.0.0-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>config-client</name>
	<description>Demo project for Spring Boot</description>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>1.5.14.RELEASE</version>
		<relativePath/>
	</parent>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
		<java.version>1.8</java.version>
		<spring-cloud.version>Edgware.SR5</spring-cloud.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-config</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-amqp</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-actuator</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>

	<dependencyManagement>
		<dependencies>
			<dependency>
				<groupId>org.springframework.cloud</groupId>
				<artifactId>spring-cloud-dependencies</artifactId>
				<version>${spring-cloud.version}</version>
				<type>pom</type>
				<scope>import</scope>
			</dependency>
		</dependencies>
	</dependencyManagement>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>

			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-surefire-plugin</artifactId>
				<configuration>
					<skipTests>true</skipTests>
					<useSystemClassLoader>false</useSystemClassLoader>
				</configuration>
			</plugin>
		</plugins>
	</build>

</project>


text:
@class CCTeamServerModel;

NS_ASSUME_NONNULL_BEGIN

@interface CCTeamCoreDataModel : NSManagedObject

- (void)updateWithServerModel:(CCTeamServerModel *)serverModel;

@end

NS_ASSUME_NONNULL_END

#import "CCTeamCoreDataModel+CoreDataProperties.h"


text:
package system

// ModuleManager manuals all Modules & it's goroutines.
// ModuleManager use one direct chan sending SIGNAL to sub module.
// More Module control methods can be added here, like ReloadModule(), etc.
// @AUTHOR tangyang

import(
    "fmt"
    "time"
    "sync"

    c "veronica/common"
)

// Manager all system & custome modules.
// Go map(search instance)&array(priority defines) are used to Manual.
// One direct chan can send SINGAL to module main goroutines.
type ModuleManager struct {
    mu         *sync.Mutex
    stopDelay  time.Duration               // module force shutdown waiting time
    priority   []string                    // module priority list
    pipes      map[string]chan c.SIGNAL    // module pipe map
    appModules map[string]c.Module         // module map
}

func NewModuleManager() *ModuleManager {
    mg := ModuleManager{
        mu         : new(sync.Mutex),
        stopDelay  : time.Duration(30) * time.Second,
        priority   : []string{},
        pipes      : map[string](chan c.SIGNAL){},
        appModules : map[string]c.Module{},
    }
    // auto regist monitor & ticker task
    mg.Init("Monitor", NewMonitor())
    mg.Init("TickerTask", NewTickerTask())
    return &mg
}

// init module to module manager
func (p *ModuleManager) Init(name string, inst c.Module) {
    p.appModules[name] = inst

    p.priority    = append(p.priority, name)
    p.pipes[name] = make(chan c.SIGNAL, 1)          // init signal chan
    inst.Init(p.pipes[name])
}

// Sending broadcast signal to all modules.
// Custome SIGNAL can be defined.
func (p *ModuleManager) SendBoardcast(sg c.SIGNAL) {
    for _, pipe := range p.pipes {
        pipe<- sg
    }
}

// Send SIGNAL to module
func (p *ModuleManager) SendSignal(sg c.SIGNAL, name string) error {
    if _, ok := p.appModules[name]; !ok {
        return fmt.Errorf("module %s not exist", name)
    }
    p.pipes[name]<- sg
    return nil
}

// Start all modules.
// Method used SendBoardcast() sending START SIGNAL.
// Also here can be changed in sequence as expected.
// Module should start in time, or panic will be throwned.
func (p *ModuleManager) Start() error {
    if len(p.appModules) == 0 {
        return fmt.Errorf("failed, no valid modules")
    }
    for name, inst := range p.appModules {
        p.SendSignal(c.SIGSTART, name)
        for inst.Status() != c.Running {            // wait module to startup
            time.Sleep(c.DefaultSleepDur)
        }

        c.Logger.WithFields(c.LogFields{
            "module" : name,
        }).Infof("%s, ready to work", name)
    }
    return nil
}

// Stop all modules.
// Stop work will follow the defined priority in sequence.
func (p *ModuleManager) Stop() {
    pri := make([]string, len(p.priority))
    copy(pri, p.priority)
    for _, name := range pri {
        if err  := p.stopModule(name); err != nil {
            c.Logger.WithFields(c.LogFields{
                "module" : name,
                "errmsg" : err.Error(),
            }).Errorf("%s, stop failed", name)
        } else {
            c.Logger.WithFields(c.LogFields{
                "module" : name,
            }).Infof("%s, stopped", name)
        }
    }
}

// Get app module list
func (p *ModuleManager) GetAppModules() map[string]c.Module {
    return p.appModules
}

// Get Started module quantity.
func (p *ModuleManager) runModuleNum() int {
    cnt := 0
    for _, module := range p.appModules {
        if module.Status() == c.Running {
            cnt++
        }
    }
    return cnt
}

// Get Stopped module qunatity.
func (p *ModuleManager) stopModuleNum() int {
    cnt := 0
    for _, inst := range p.appModules {
        if inst.Status() == c.Stopped {
            cnt++
        }
    }
    return cnt
}

// Stop one module.
// Send STOP SIGNAL to module and wait module stop.
// If stopping used more than this.moduleStopDelay time,
// ModuleManager will forget this module status and flag it stopped.
func (p *ModuleManager) stopModule(name string) error {
    inst, ok := p.appModules[name]
    if ok == false {
        return fmt.Errorf("%s not exist", name)
    }

    p.SendSignal(c.SIGSTOP, name)
    timer := time.NewTimer(p.stopDelay)
    stop  := false
    for !stop {
        select {
        case <-timer.C:
            p.unload(name)
            stop = true
            return fmt.Errorf("can not stop in 30s, abandon")
        default:
            if inst.Status() == c.Stopped {
                p.unload(name)
                stop = true
            } else {
                time.Sleep(c.DefaultSleepDur)
            }
        }
    }
    return nil
}

// Unload module, used to stop module.(just delete module from map and priority)
func (p *ModuleManager) unload(name string) {
    p.mu.Lock()
    defer p.mu.Unlock()

    if _, ok := p.appModules[name]; ok {
        delete(p.appModules, name)
    }

    for i, moduleName := range p.priority {     // delete module from array
        if moduleName == name {                 // delete
            p.priority = append(p.priority[: i], p.priority[(i + 1) : ]...)
            break
        } else {
            continue
        }
    }
}

/* vim: set expandtab ts=4 sw=4 sts=4 tw=100: */


text:
def current_user
  @user ||= User.find(session[:user_id]) if session[:user_id]
end

def user_logout
  session[:user_id] = nil
end


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

package com.google.gerrit.mail;

import static com.google.common.truth.Truth.assertThat;

import com.google.gerrit.reviewdb.client.Account;
import com.google.gerrit.reviewdb.client.Comment;
import java.sql.Timestamp;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import org.junit.Ignore;

@Ignore
public class AbstractParserTest {
  protected static final String CHANGE_URL =
      "https://gerrit-review.googlesource.com/c/project/+/123";

  protected static void assertChangeMessage(String message, MailComment comment) {
    assertThat(comment.fileName).isNull();
    assertThat(comment.message).isEqualTo(message);
    assertThat(comment.inReplyTo).isNull();
    assertThat(comment.type).isEqualTo(MailComment.CommentType.CHANGE_MESSAGE);
  }

  protected static void assertInlineComment(
      String message, MailComment comment, Comment inReplyTo) {
    assertThat(comment.fileName).isNull();
    assertThat(comment.message).isEqualTo(message);
    assertThat(comment.inReplyTo).isEqualTo(inReplyTo);
    assertThat(comment.type).isEqualTo(MailComment.CommentType.INLINE_COMMENT);
  }

  protected static void assertFileComment(String message, MailComment comment, String file) {
    assertThat(comment.fileName).isEqualTo(file);
    assertThat(comment.message).isEqualTo(message);
    assertThat(comment.inReplyTo).isNull();
    assertThat(comment.type).isEqualTo(MailComment.CommentType.FILE_COMMENT);
  }

  protected static Comment newComment(String uuid, String file, String message, int line) {
    Comment c =
        new Comment(
            new Comment.Key(uuid, file, 1),
            new Account.Id(0),
            new Timestamp(0L),
            (short) 0,
            message,
            "",
            false);
    c.lineNbr = line;
    return c;
  }

  protected static Comment newRangeComment(String uuid, String file, String message, int line) {
    Comment c =
        new Comment(
            new Comment.Key(uuid, file, 1),
            new Account.Id(0),
            new Timestamp(0L),
            (short) 0,
            message,
            "",
            false);
    c.range = new Comment.Range(line, 1, line + 1, 1);
    c.lineNbr = line + 1;
    return c;
  }

  /** Returns a MailMessage.Builder with all required fields populated. */
  protected static MailMessage.Builder newMailMessageBuilder() {
    MailMessage.Builder b = MailMessage.builder();
    b.id("id");
    b.from(new Address("Foo Bar", "foo@bar.com"));
    b.dateReceived(Instant.now());
    b.subject("");
    return b;
  }

  /** Returns a List of default comments for testing. */
  protected static List<Comment> defaultComments() {
    List<Comment> comments = new ArrayList<>();
    comments.add(newComment("c1", "gerrit-server/test.txt", "comment", 0));
    comments.add(newComment("c2", "gerrit-server/test.txt", "comment", 2));
    comments.add(newComment("c3", "gerrit-server/test.txt", "comment", 3));
    comments.add(newComment("c3", "gerrit-server/test.txt", "comment", 115));
    comments.add(newRangeComment("c5", "gerrit-server/readme.txt", "comment", 3));
    return comments;
  }
}


text:
package uk.ac.ncl.openlab.intake24.services.foodindex

import uk.ac.ncl.openlab.intake24.api.data.{UserCategoryHeader, UserFoodHeader}
import uk.ac.ncl.openlab.intake24.api.data.admin.{CategoryV2, FoodRecord}

sealed trait IndexEntry

case class CategoryEntry(header: UserCategoryHeader) extends IndexEntry
case class FoodEntry(header: UserFoodHeader) extends IndexEntry

object Util {
  def mkHeader(category: CategoryV2) = UserCategoryHeader(category.code, category.description)
  def mkHeader(food: FoodRecord) = UserFoodHeader(food.main.code, food.main.englishDescription)
}


text:
<?php
namespace ApplicationInsights\Channel\Contracts;
/**
* Enum Message_Severity_Level.
*/
abstract class Message_Severity_Level
{
	const VERBOSE = 'Verbose';
	const INFORMATION = 'Information';
	const WARNING = 'Warning';
	const ERROR = 'Error';
	const CRITICAL = 'Critical';
}


text:
#pragma once

#include "soa/service/zmq_endpoint.h"
#include "rtbkit/core/router/router_types.h"
#include "soa/gc/rcu_protected.h"

namespace RTBKIT {

/*****************************************************************************/
/* AGENT CONFIG ENTRY                                                        */
/*****************************************************************************/

/** A single entry in the agent info structure. */
struct AgentConfigEntry {
    std::string name;
    std::shared_ptr<const AgentConfig> config;

    bool valid() const { return !!config; }

    /** JSON version for debugging. */
    Json::Value toJson() const;
};

/** A read-only structure with information about all of the agents so
    that auctions can scan them without worrying about data dependencies.
    Uses RCU.
*/
struct AllAgentConfig : public std::vector<AgentConfigEntry> {
    std::unordered_map<std::string, int> agentIndex;
    std::unordered_map<AccountKey, std::vector<int> > accountIndex;
};

/*****************************************************************************/
/* AGENT CONFIGURATION LISTENER                                              */
/*****************************************************************************/

struct AgentConfigurationListener: public MessageLoop {

    AgentConfigurationListener(std::shared_ptr<zmq::context_t> context)
        : allAgents(new AllAgentConfig()), configEndpoint(context)
    {
    }

    ~AgentConfigurationListener()
    {
        delete allAgents;
        shutdown();
    }

    /** Type of function to be called on a configuration change.  If an agent
        has disappeared, the config pointer will be null.
    */
    typedef std::function<void (std::string, std::shared_ptr<const AgentConfig>)>
    OnConfigChange;

    OnConfigChange onConfigChange;

    void init(std::shared_ptr<ConfigurationService> config)
    {
        configEndpoint.init(config);
        configEndpoint.connectToServiceClass("rtbAgentConfiguration",
                                             "listen");
        configEndpoint.messageHandler
            = [=] (const std::vector<std::string> & message)
            {
                if (message.size() > 1) {
                    using namespace std;
                    cerr << "got configuration message " << message[1] << endl;
                }
                this->onMessage(message);
            };
        addSource("AgentConfigurationListener::configEndpoint", configEndpoint);
    }

    void start()
    {
        MessageLoop::start();
    }

    void shutdown()
    {
        MessageLoop::shutdown();
        configEndpoint.shutdown();
    }

    /*************************************************************************/
    /* AGENT INTERACTIONS                                                    */
    /*************************************************************************/

    typedef std::function<void (const AgentConfigEntry & info)> OnAgentFn;
    /** Call the given callback for each agent. */
    void forEachAgent(const OnAgentFn & onAgent) const;

    /** Call the given callback for each agent that is bidding on the given
        account.
    */
    void forEachAccountAgent(const AccountKey & account,
                             const OnAgentFn & onAgent) const;

    /** Find the information entry for the given agent.  All elements are
        guaranteed to be valid until the object is destroyed.
    */
    AgentConfigEntry getAgentEntry(const std::string & agent) const;

private:
    void onMessage(const std::vector<std::string> & message);

    AllAgentConfig * allAgents;
    mutable GcLock allAgentsGc;

    ZmqNamedClientBusProxy configEndpoint;
};

struct AgentBridge {
    AgentBridge(std::shared_ptr<zmq::context_t> context) :
        agents(context) {
    }

    void shutdown() {
        agents.shutdown();
    }

    /// Messages to the agents go out on this
    ZmqNamedClientBus agents;

    /** Send the given message to the given bidding agent. */
    template<typename... Args>
    void sendAgentMessage(const std::string & agent,
                          const std::string & messageType,
                          const Date & date,
                          Args... args)
    {
        agents.sendMessage(agent, messageType, date,
                           std::forward<Args>(args)...);
    }

    /** Send the given message to the given bidding agent. */
    template<typename... Args>
    void sendAgentMessage(const std::string & agent,
                          const std::string & eventType,
                          const std::string & messageType,
                          const Date & date,
                          Args... args)
    {
        agents.sendMessage(agent, eventType, messageType, date,
                           std::forward<Args>(args)...);
    }
};

} // namespace RTBKIT


text:
using System;

namespace Sandwich.Core.ValueConverters
{
    public class DecimalConverter : NullableTypeConverterBase<decimal, decimal?>
    {
        public DecimalConverter(IFormatProvider formatProvider)
            : base(formatProvider)
        {
        }

        protected override object InternalConvert(string value)
        {
            return decimal.Parse(value, FormatProvider);
        }
    }
}


text: Alternating split of a given Singly Linked List


text:
import FWCore.ParameterSet.Config as cms
import pickle
process = pickle.load(open('PSet.pkl', 'rb'))


text:
using FinancialData.Shared;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace BarsBuilder.Shared {
  public interface IBarsCreator {
    void AddQuote(DateTime dateTime, decimal price);

    int BarsCount { get; }

    //void Save(string filePath);

    string StoragePath { get; }

    void Finish();

    List<IBar> GetBars();
  }
}


text:
id: 974
title: Blazing the Trail
date: 2013-11-08T12:39:31+00:00
author_name: Adrianna Tan
layout: post
guid: http://popagandhi.com/?p=974
permalink: /2013/11/blazing-the-trail/
dsq_thread_id:
  - 1946784156
categories:
  - Uncategorized
format: link
---
I got a mention in the [Singapore International Foundation's magazine](http://singaporemagazine.sif.org.sg/blazing-the-trail/) for some of the stuff I do on the side.


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">MQ重開機</string>
    <string name="button_cancel">取消</string>
    <string name="button_ok">確定</string>
</resources>


text:
package com.welyab.ayszu.util.collections;

import com.google.common.base.Predicate;

public class AyszuArrays {

	public static <T> boolean contains(T[] array, Predicate<T> test) {
		for (T t : array) {
			if (test.apply(t)) {
				return true;
			}
		}
		return false;
	}
}


text:
using System.Diagnostics.Contracts;
using System;

namespace System.ComponentModel
{

    public class GuidConverter
    {

        public GuidConverter () {

          return default(GuidConverter);
        }
        public object ConvertTo (ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type! destinationType) {
            Contract.Requires(destinationType != null);

          return default(object);
        }
        public object ConvertFrom (ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) {

          return default(object);
        }
        public bool CanConvertTo (ITypeDescriptorContext context, Type destinationType) {

          return default(bool);
        }
        public bool CanConvertFrom (ITypeDescriptorContext context, Type sourceType) {
          return default(bool);
        }
    }
}


text:
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>R-tree free functions (boost::geometry::index::)</title>
<link rel="stylesheet" href="../../../../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.79.1">
<link rel="home" href="../../../index.html" title="Chapter 1. Geometry">
<link rel="up" href="../spatial_indexes.html" title="Spatial Indexes">
<link rel="prev" href="boost__geometry__index__rtree/get_allocator__.html" title="get_allocator()">
<link rel="next" href="group__rtree__functions/insert_rtree_________value_const___.html" title="insert(rtree<...> &, Value const &)">

Home
Libraries
People
FAQ
More

R-tree
        free functions (boost::geometry::index::)

insert(rtree<...>
          &, Value const &)

insert(rtree<...>
          &, Iterator, Iterator)

insert(rtree<...>
          &, ConvertibleOrRange const &)

remove(rtree<...>
          &, Value const &)

remove(rtree<...>
          &, Iterator, Iterator)

remove(rtree<...>
          &, ConvertibleOrRange const &)

query(rtree<...>
          const &, Predicates const &, OutIter)

qbegin(rtree<...>
          const &, Predicates const &)

qend(rtree<...>
          const &)

begin(rtree<...>
          const &)

end(rtree<...>
          const &)

clear(rtree<...>
          &)

size(rtree<...>
          const &)

empty(rtree<...>
          const &)

bounds(rtree<...>
          const &)

swap(rtree<...>
          &, rtree<...> &)

          Functions

<colgroup>
<col>
<col>
</colgroup>

                    Function

                    Description

                    insert(rtree<...>
                    &, Value
                    const &)

                    Insert a value to the index.

                    insert(rtree<...>
                    &, Iterator, Iterator)

                    Insert a range of values to the index.

                    insert(rtree<...>
                    &, ConvertibleOrRange
                    const &)

                    Insert a value created using convertible object or a range of
                    values to the index.

                    remove(rtree<...>
                    &, Value
                    const &)

                    Remove a value from the container.

                    remove(rtree<...>
                    &, Iterator, Iterator)

                    Remove a range of values from the container.

                    remove(rtree<...>
                    &, ConvertibleOrRange
                    const &)

                    Remove a value corresponding to an object convertible to it or
                    a range of values from the container.

                    query(rtree<...>
                    const &,
                    Predicates const
                    &, OutIter)

                    Finds values meeting passed predicates e.g. nearest to some Point
                    and/or intersecting some Box.

                    qbegin(rtree<...>
                    const &,
                    Predicates const
                    &)

                    Returns the query iterator pointing at the begin of the query
                    range.

                    qend(rtree<...>
                    const &)

                    Returns the query iterator pointing at the end of the query range.

                    begin(rtree<...>
                    const &)

                    Returns the iterator pointing at the begin of the rtree values
                    range.

                    end(rtree<...>
                    const &)

                    Returns the iterator pointing at the end of the rtree values
                    range.

                    clear(rtree<...>
                    &)

                    Remove all values from the index.

                    size(rtree<...>
                    const &)

                    Get the number of values stored in the index.

                    empty(rtree<...>
                    const &)

                    Query if there are no values stored in the index.

                    bounds(rtree<...>
                    const &)

                    Get the box containing all stored values or an invalid box if
                    the index has no values.

                    swap(rtree<...>
                    &, rtree<...> &)

                    Exchanges the contents of the container with those of other.

Copyright © 2009-2015 Barend Gehrels, Bruno Lalande,
      Mateusz Loskot, Adam Wulkiewicz, Oracle and/or its affiliates

        Distributed under the Boost Software License, Version 1.0. (See accompanying
        file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)


text:
package com.intellij.vcs.log.graph.utils;

import com.intellij.vcs.log.graph.utils.Flags;
import com.intellij.vcs.log.graph.utils.impl.BitSetFlags;
import org.jetbrains.annotations.NotNull;
import org.junit.Test;

import static junit.framework.TestCase.assertEquals;

public class BitSetFlagsTest {

  private static char bitToChar(boolean bit) {
    return bit ? '1' : '0';
  }

  private static String toStr(@NotNull Flags flags) {
    StringBuilder s = new StringBuilder();
    for(int i = 0; i < flags.size(); i++)
      s.append(bitToChar(flags.get(i)));
    return s.toString();
  }

  @Test
  public void initTest() {
    BitSetFlags flags = new BitSetFlags(5);
    assertEquals("00000", toStr(flags));
    assertEquals(5, flags.size());
  }

  @Test
  public void setTest() {
    BitSetFlags flags = new BitSetFlags(6);
    assertEquals("000000", toStr(flags));

    flags.set(0, true);
    assertEquals("100000", toStr(flags));

    flags.set(0, false);
    assertEquals("000000", toStr(flags));

    flags.set(4, true);
    assertEquals("000010", toStr(flags));

    flags.set(2, true);
    assertEquals("001010", toStr(flags));
  }

  @Test
  public void setAllTest() {
    BitSetFlags flags = new BitSetFlags(6);
    assertEquals("000000", toStr(flags));

    flags.setAll(false);
    assertEquals("000000", toStr(flags));

    flags.setAll(true);
    assertEquals("111111", toStr(flags));
  }

  @Test
  public void size1Test() {
    BitSetFlags flags = new BitSetFlags(1);
    assertEquals("0", toStr(flags));
    assertEquals(1, flags.size());

    flags.set(0, true);
    assertEquals("1", toStr(flags));

    flags.set(0, false);
    assertEquals("0", toStr(flags));

    flags.setAll(true);
    assertEquals("1", toStr(flags));
  }

  @Test
  public void emptyFlagsTest() {
    BitSetFlags flags = new BitSetFlags(0);
    assertEquals(0, flags.size());
    flags.setAll(true);
    assertEquals(0, flags.size());
  }
}


text:
package org.elasticsearch.gradle.transform;

import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
import org.apache.commons.compress.compressors.gzip.GzipCompressorInputStream;
import org.gradle.api.artifacts.transform.TransformOutputs;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.function.Function;

import static org.elasticsearch.gradle.util.PermissionUtils.chmod;

public abstract class SymbolicLinkPreservingUntarTransform implements UnpackTransform {

    private static final Path CURRENT_DIR_PATH = Paths.get(".");

    public void unpack(File tarFile, File targetDir, TransformOutputs outputs, boolean asFiletreeOutput) throws IOException {
        Function<String, Path> pathModifier = pathResolver();
        TarArchiveInputStream tar = new TarArchiveInputStream(new GzipCompressorInputStream(new FileInputStream(tarFile)));
        final Path destinationPath = targetDir.toPath();
        TarArchiveEntry entry = tar.getNextTarEntry();
        while (entry != null) {
            final Path relativePath = pathModifier.apply(entry.getName());
            if (relativePath == null || relativePath.getFileName().equals(CURRENT_DIR_PATH)) {
                entry = tar.getNextTarEntry();
                continue;
            }

            final Path destination = destinationPath.resolve(relativePath);
            final Path parent = destination.getParent();
            if (Files.exists(parent) == false) {
                Files.createDirectories(parent);
            }
            if (entry.isDirectory()) {
                Files.createDirectory(destination);
            } else if (entry.isSymbolicLink()) {
                Files.createSymbolicLink(destination, Paths.get(entry.getLinkName()));
            } else {
                // copy the file from the archive using a small buffer to avoid heaping
                Files.createFile(destination);
                try (FileOutputStream fos = new FileOutputStream(destination.toFile())) {
                    tar.transferTo(fos);
                }
                if (asFiletreeOutput) {
                    outputs.file(destination.toFile());
                }
            }
            if (entry.isSymbolicLink() == false) {
                // check if the underlying file system supports POSIX permissions
                chmod(destination, entry.getMode());
            }
            entry = tar.getNextTarEntry();
        }
    }
}


text:
import React from 'react';
import {ActivityIndicator, StyleProp, View, ViewStyle} from 'react-native';

import {useTheme} from '@context/theme';

type LoadingProps = {
    containerStyle?: StyleProp<ViewStyle>;
    size?: number | 'small' | 'large';
    color?: string;
    themeColor?: keyof Theme;
}

const Loading = ({containerStyle, size, color, themeColor}: LoadingProps) => {
    const theme = useTheme();
    const indicatorColor = themeColor ? theme[themeColor] : color;

    return (
        <View style={containerStyle}>
            <ActivityIndicator
                color={indicatorColor}
                size={size}
            />
        </View>
    );
};

export default Loading;