text:
(function() {

Dagaz.Model.invisible    = [];
Dagaz.Model.invisibleOld = [];

var doneFlag = false;

var checkVersion = Dagaz.Model.checkVersion;

Dagaz.Model.checkVersion = function(design, name, value) {
  if (name != "dark-alapo-view") {
      checkVersion(design, name, value);
  }
}

var checkStep = function(design, board, player, pos, dir, visible) {
  var p = design.navigate(player, pos, dir);
  if (p === null) return;
  var piece = board.getPiece(p);
  if (piece === null) {
     if (player == 1) visible.push(p);
  } else {
     if (piece.player != player) visible.push(p);
  }
}

var checkSlide = function(design, board, player, pos, dir, visible) {
  var p = design.navigate(player, pos, dir);
  while (p !== null) {
      var piece = board.getPiece(p);
      if (piece !== null) {
          if (piece.player != player) {
              visible.push(p);
          }
          return;
      }
      if (player == 1) visible.push(p);
      p = design.navigate(player, p, dir);
  }
}

Dagaz.Model.Done = function(design, board) {
  var visible = [];
  var n  = design.getDirection("n");  var w  = design.getDirection("w");
  var s  = design.getDirection("s");  var e  = design.getDirection("e");
  var nw = design.getDirection("nw"); var sw = design.getDirection("sw");
  var ne = design.getDirection("ne"); var se = design.getDirection("se");
  _.each(design.allPositions(), function(pos) {
      var piece = board.getPiece(pos);
      if (piece !== null) {
          if ((piece.type == 0) || (piece.type == 4)) {
              checkStep(design, board, piece.player, pos, n, visible);
              checkStep(design, board, piece.player, pos, e, visible);
              checkStep(design, board, piece.player, pos, w, visible);
              checkStep(design, board, piece.player, pos, s, visible);
          }
          if ((piece.type == 1) || (piece.type == 5)) {
              checkSlide(design, board, piece.player, pos, n, visible);
              checkSlide(design, board, piece.player, pos, e, visible);
              checkSlide(design, board, piece.player, pos, w, visible);
              checkSlide(design, board, piece.player, pos, s, visible);
          }
          if ((piece.type == 2) || (piece.type == 4)) {
              checkStep(design, board, piece.player, pos, nw, visible);
              checkStep(design, board, piece.player, pos, ne, visible);
              checkStep(design, board, piece.player, pos, sw, visible);
              checkStep(design, board, piece.player, pos, se, visible);
          }
          if ((piece.type == 3) || (piece.type == 5)) {
              checkSlide(design, board, piece.player, pos, nw, visible);
              checkSlide(design, board, piece.player, pos, ne, visible);
              checkSlide(design, board, piece.player, pos, sw, visible);
              checkSlide(design, board, piece.player, pos, se, visible);
          }
      }
  });
  Dagaz.Model.invisibleOld = [];
  _.each(Dagaz.Model.invisible, function(p) {
      if (board.getPiece(p) === null) {
          Dagaz.Model.invisibleOld.push(p);
      }
  });
  Dagaz.Model.invisible = [];
  _.each(design.allPositions(), function(pos) {
      var piece = board.getPiece(pos);
      if ((piece !== null) && (_.indexOf(visible, pos) < 0)) {
          Dagaz.Model.invisible.push(pos);
      }
  });
  var ko = [];
  _.each(design.allPositions(), function(pos) {
      if (_.indexOf(visible, pos) >= 0) return;
      var piece = board.getPiece(pos);
      if ((piece !== null) && (piece.player == 1)) return;
      ko.push(pos);
  });
  if (ko.length > 0) {
      board.ko = ko;
  }
}

Dagaz.Controller.Done = function(board) {
  board.ko = [];
  doneFlag = true;
}

Dagaz.View.showPiece = function(view, ctx, frame, pos, piece, model, x, y, setup) {
  var isSaved = false;
  if (!doneFlag && (_.indexOf(_.union(Dagaz.Model.invisible, Dagaz.Model.invisibleOld), setup.pos) >= 0)) {
      ctx.save();
      if (model.player == 1) {
          ctx.globalAlpha = 0.5;
      } else {
          ctx.globalAlpha = 0;
      }
      isSaved = true;
  }
  ctx.drawImage(piece.h, x, y, piece.dx, piece.dy);
  if (isSaved) {
      ctx.restore();
  }
}

})();


text:
import os
import re
import csv
import argparse
import subprocess
from pipelines.utils import PipelinesConfig, DataUtils, PipelineSchema, PipelineBuilder
from pipelines.paths import CLIENT_CONFIG_PATH

class PipelineStep(object):
	def __init__(self):
		self._pipelinesConfig = PipelinesConfig(CLIENT_CONFIG_PATH)
		self._step = None

	def get(self):
		return self._step

class FastQCStep(PipelineStep):
	def __init__(self, inputUrl, outputUrl, outputPrefix, diskSize, diskType, logsPath, container, scriptUrl, tag, cores, mem, preemptible):
		super(PipelineStep, self).__init__()

		inputFileName = os.path.basename(inputUrl)

		self._step = PipelineSchema("fastqc",
		                            self._pipelinesConfig,
		                            logsPath,
		                            container,
		                            scriptUrl=scriptUrl,
		                            diskSize=diskSize,
		                            diskType=diskType,
		                            mem=mem,
		                            cores=cores,
		                            inputs="{inputUrl}:{inputFileName}".format(inputUrl=inputUrl, inputFileName=inputFileName),
		                            outputs="*_fastqc.zip:{fastqcOutput},*_fastqc.html:{fastqcOutput}".format(fastqcOutput=outputUrl),
		                            env="INPUT_FILENAME={inputFileName},OUTPUT_PREFIX={outputPrefix}".format(inputFileName=inputFileName, outputPrefix=outputPrefix),
		                            tag=tag,
		                            preemptible=preemptible)

class SamtoolsIndexStep(PipelineStep):
	def __init__(self, bamUrl, outputUrl, diskSize, diskType, logsPath, container, scriptUrl, tag, cores, mem, preemptible):
		super(PipelineStep, self).__init__()

		bamFileName = os.path.basename(bamUrl)

		self._step = PipelineSchema("samtoolsIndex",
		                            self._pipelinesConfig,
		                            logsPath,
		                            container,
		                            scriptUrl=scriptUrl,
		                            diskSize=diskSize,
		                            diskType=diskType,
		                            mem=mem,
		                            cores=cores,
		                            inputs="{bamUrl}:{bamFileName}".format(bamUrl=bamUrl, bamFileName=bamFileName),
		                            outputs="*.bai:{outputUrl}".format(outputUrl=outputUrl),
		                            env="BAM_FILENAME={bamFileName}".format(bamFileName=bamFileName),
		                            tag=tag,
		                            preemptible=preemptible)

class SamtoolsFaidxStep(PipelineStep):
	def __init__(self, fastaUrl, outputUrl, diskSize, diskType, logsPath, container, scriptUrl, tag, cores, mem, preemptible):
		super(PipelineStep, self).__init__()

		fastaFileName = os.path.basename(fastaUrl)

		self._step = PipelineSchema("samtools-faidx",
		                            self._pipelinesConfig,
		                            logsPath,
									container,
		                            scriptUrl=scriptUrl,
		                            diskSize=diskSize,
		                            diskType=diskType,
		                            cores=cores,
		                            mem=mem,
		                            tag=tag,
		                            inputs="{fastaUrl}:{fastaFileName}".format(fastaUrl=fastaUrl, fastaFileName=fastaFileName),
		                            outputs="*.fai:{outputUrl}".format(outputUrl=outputUrl),
		                            preemptible=preemptible)

class BiobloommakerStep(PipelineStep):
	def __init__(self, fastaDirUrl, outputPrefix, outputUrl, diskSize, diskType, logsPath, container, scriptUrl, tag, cores, mem, preemptible):
		super(PipelineStep, self).__init__()

		try:
			fastaDirContents = subprocess.check_output(["gsutil", "ls", fastaDirUrl])

		except subprocess.CalledProcessError as e:
			print "ERROR: couldn't get a listing of reference files!  -- {reason}".format(reason=e)
			exit(-1)

		fastaInputs = [x for x in fastaDirContents.split('\n') if re.match('^.*\.fa$', x) or re.match('^.*\.fai$', x) or re.match('^.*\.fasta$', x)]
		inputs = ','.join(["{url}:{filename}".format(url=x, filename=os.path.basename(x)) for x in fastaInputs])
		outputs = "*.bf:{filterOutput},*.txt:{filterOutput}".format(filterOutput=outputUrl)
		env = "OUTPUT_PREFIX={outputPrefix},VIRAL_SEQUENCES={viralSequences}".format(outputPrefix=outputPrefix, viralSequences=' '.join(fastaInputs))

		self._step = PipelineSchema("biobloommaker",
		                            self._pipelinesConfig,
		                            logsPath,
		                            container,
		                            scriptUrl=scriptUrl,
		                            cores=cores,
		                            mem=mem,
		                            tag=tag,
		                            diskSize=diskSize,
		                            diskType=diskType,
		                            inputs=inputs,
		                            outputs=outputs,
		                            env=env,
		                            preemptible=preemptible)

class BiobloomcategorizerStep(PipelineStep):
	def __init__(self, fqArchiveUrl, filtersDir, outputPrefix, outputUrl, diskSize, diskType, logsPath, container, scriptUrl, tag, cores, mem, preemptible):
		super(PipelineStep, self).__init__()

		fqFileName = os.path.basename(fqArchiveUrl)
		fqInputs = "{fqArchive}:{fqFileName}".format(fqArchive=fqArchiveUrl, fqFileName=fqFileName)

		try:
			filtersDirContents = subprocess.check_output(["gsutil", "ls", filtersDir])

		except subprocess.CalledProcessError as e:
			print "ERROR: couldn't get a listing of filter files!  -- {reason}".format(reason=e)
			exit(-1)

		bfInputs = [x for x in filtersDirContents.split('\n') if re.match('^.*\.bf$', x) or re.match('^.*\.txt', x)]
		bfInputs.append(fqInputs)

		inputs = ",".join(["{url}:{filename}".format(url=x, filename=os.path.basename(x)) for x in bfInputs])
		outputs = "{outputPrefix}*:{outDir}".format(outputPrefix=outputPrefix, outDir=outputUrl)
		env = "INPUT_FILE={fqFileName},OUTPUT_PREFIX={outputPrefix},FILTERS_LIST={filtersList}".format(fqFileName=fqFileName, outputPrefix=outputPrefix, filtersList=','.join([os.path.basename(x) for x in bfInputs if re.match('^.*\.bf$', x)]))

		self._step = PipelineSchema("biobloomcategorizer",
		                                           self._pipelinesConfig,
		                                           logsPath,
		                                           container,
		                                           scriptUrl=scriptUrl,
		                                           cores=cores,
		                                           mem=mem,
		                                           diskSize=diskSize,
		                                           diskType=diskType,
		                                           inputs=inputs,
		                                           outputs=outputs,
		                                           env=env,
		                                           tag=tag,
		                                           preemptible=preemptible)

class GDCDownloadStep(PipelineStep):
	def __init__(self, fileUuid, tokenUrl, outputUrl, diskSize, diskType, logsPath, container, scriptUrl, tag, cores, mem, preemptible):
		super(PipelineStep, self).__init__()

		tokenFileName = os.path.basename(tokenUrl)

		self._step = PipelineSchema("gdcDownload",
		                            self._pipelinesConfig,
		                            logsPath,
		                            container,
		                            scriptUrl=scriptUrl,
		                            cores=cores,
		                            mem=mem,
		                            diskSize=diskSize,
		                            diskType=diskType,
		                            inputs="{tokenUrl}:{tokenFileName}".format(tokenUrl=tokenUrl, tokenFileName=tokenFileName),
		                            outputs="{fileUuid}/*:{outputUrl}".format(fileUuid=fileUuid, outputUrl=outputUrl),
		                            env="FILE_UUID={fileUuid},GDC_TOKEN={tokenFileName}".format(fileUuid=fileUuid, tokenFileName=tokenFileName),
		                            tag=tag,
		                            preemptible=preemptible)

class MitcrStep(PipelineStep):
	def __init__(self, fqArchiveUrl, psetFileUrl, outputFileName, outputUrl, diskSize, diskType, logsPath, container, scriptUrl, tag, cores, mem, preemptible):
		super(PipelineStep, self).__init__()

		fqFileName = os.path.basename(fqArchiveUrl)
		psetFileName = os.path.basename(psetFileUrl)

		self._step = PipelineSchema("mitcr",
		                            self._pipelinesConfig,
		                            logsPath,
		                            container,
		                            scriptUrl=scriptUrl,
		                            cores=cores,
		                            mem=mem,
		                            diskSize=diskSize,
		                            diskType=diskType,
		                            inputs="{fqArchiveUrl}:{fqFileName},{psetFileUrl}:{psetFileName}".format(fqArchiveUrl=fqArchiveUrl, fqFileName=fqFileName, psetFileUrl=psetFileUrl, psetFileName=psetFileName),
		                            outputs="{outputFileName}:{outputUrl}".format(outputFileName=outputFileName, outputUrl=outputUrl),
		                            env="INPUT_FILE={fqFileName},PSET_FILE={psetFileName},OUTPUT_FILE={outputFileName}".format(fqFileName=fqFileName, psetFileName=psetFileName, outputFileName=outputFileName),
		                            tag=tag,
		                            preemptible=preemptible)

class PicardStep(PipelineStep):
	def __init__(self, bamUrl, outputPrefix, outputUrl, diskSize, diskType, logsPath, container, scriptUrl, tag, cores, mem, preemptible):
		super(PipelineStep, self).__init__()

		bamFileName = os.path.basename(bamUrl)

		self._step = PipelineSchema("picard",
		                            self._pipelinesConfig,
		                            logsPath,
		                            container,
		                            scriptUrl=scriptUrl,
		                            cores=cores,
		                            mem=mem,
		                            diskSize=diskSize,
		                            diskType=diskType,
		                            inputs="{bamUrl}:{bamFileName},{bamUrl}.bai:{bamFileName}.bai".format(bamUrl=bamUrl, bamFileName=bamFileName),
		                            outputs="{outputPrefix}*:{outputUrl}".format(outputPrefix=outputPrefix, outputUrl=outputUrl),
		                            env="INPUT_FILENAME={bamFileName},OUTPUT_PREFIX={outputPrefix}".format(bamFileName=bamFileName, outputPrefix=outputPrefix),
		                            tag=tag,
		                            preemptible=preemptible)

redpajama_set_name: RedPajamaGithub


text:
.class final Landroid/view/textservice/SuggestionsInfo$1;
.super Ljava/lang/Object;
.source "SuggestionsInfo.java"

# interfaces
.implements Landroid/os/Parcelable$Creator;

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Landroid/view/textservice/SuggestionsInfo;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x8
    name = null
.end annotation

.annotation system Ldalvik/annotation/Signature;
    value = {
        "Ljava/lang/Object;",
        "Landroid/os/Parcelable$Creator",
        "<",
        "Landroid/view/textservice/SuggestionsInfo;",
        ">;"
    }
.end annotation

# direct methods
.method constructor <init>()V
    .locals 0

    .prologue
    .line 166
    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    return-void
.end method

# virtual methods
.method public createFromParcel(Landroid/os/Parcel;)Landroid/view/textservice/SuggestionsInfo;
    .locals 1
    .param p1, "source"    # Landroid/os/Parcel;

    .prologue
    .line 169
    new-instance v0, Landroid/view/textservice/SuggestionsInfo;

    invoke-direct {v0, p1}, Landroid/view/textservice/SuggestionsInfo;-><init>(Landroid/os/Parcel;)V

    return-object v0
.end method

.method public bridge synthetic createFromParcel(Landroid/os/Parcel;)Ljava/lang/Object;
    .locals 1
    .param p1, "source"    # Landroid/os/Parcel;

    .prologue
    .line 168
    invoke-virtual {p0, p1}, Landroid/view/textservice/SuggestionsInfo$1;->createFromParcel(Landroid/os/Parcel;)Landroid/view/textservice/SuggestionsInfo;

    move-result-object v0

    return-object v0
.end method

.method public newArray(I)[Landroid/view/textservice/SuggestionsInfo;
    .locals 1
    .param p1, "size"    # I

    .prologue
    .line 174
    new-array v0, p1, [Landroid/view/textservice/SuggestionsInfo;

    return-object v0
.end method

.method public bridge synthetic newArray(I)[Ljava/lang/Object;
    .locals 1
    .param p1, "size"    # I

    .prologue
    .line 173
    invoke-virtual {p0, p1}, Landroid/view/textservice/SuggestionsInfo$1;->newArray(I)[Landroid/view/textservice/SuggestionsInfo;

    move-result-object v0

    return-object v0
.end method


text:
title: "Plugins"
weight: 5
type: docs
aliases:
  - /zh/deployment/filesystems/plugins.html
  - /zh/ops/plugins.html
---

# Plugins

Plugins facilitate a strict separation of code through restricted classloaders. Plugins cannot
access classes from other plugins or from Flink that have not been specifically whitelisted. This
strict isolation allows plugins to contain conflicting versions of the same library without the need
to relocate classes or to converge to common versions. Currently, file systems and metric reporters are pluggable
but in the future, connectors, formats, and even user code should also be pluggable.

## Isolation and plugin structure

Plugins reside in their own folders and can consist of several jars. The names of the plugin folders
are arbitrary.

```
flink-dist
├── conf
├── lib
...
└── plugins
    ├── s3
    │   ├── aws-credential-provider.jar
    │   └── flink-s3-fs-hadoop.jar
    └── azure
        └── flink-azure-fs-hadoop.jar
```

Each plugin is loaded through its own classloader and completely isolated from any other plugin.
Hence, the `flink-s3-fs-hadoop` and `flink-azure-fs-hadoop` can depend on different conflicting
library versions. There is no need to relocate any class during the creation of fat jars (shading).

Plugins may access certain whitelisted packages from Flink's `lib/` folder. In particular, all
necessary service provider interfaces (SPI) are loaded through the system classloader, so that no
two versions of `org.apache.flink.core.fs.FileSystem` exist at any given time, even if users
accidentally bundle it in their fat jar. This singleton class requirement is strictly necessary so
that the Flink runtime has an entry point into the plugin. Service classes are discovered through
the `java.util.ServiceLoader`, so make sure to retain the service definitions in `META-INF/services`
during shading.

Note *Currently, more Flink core classes are still
accessible from plugins as we flesh out the SPI system.*

Furthermore, the most common logger frameworks are whitelisted, such that logging is uniformly
possible across Flink core, plugins, and user code.

## File Systems

All [file systems]({%link deployment/filesystems/index.md %}) **except MapR** are pluggable. That means they can and should
be used as plugins. To use a pluggable file system, copy the corresponding JAR file from the `opt`
directory to a directory under `plugins` directory of your Flink distribution before starting Flink,
e.g.

```bash
mkdir ./plugins/s3-fs-hadoop
cp ./opt/flink-s3-fs-hadoop-{{< version >}}.jar ./plugins/s3-fs-hadoop/
```

{{< hint warning >}}
The s3 file systems (`flink-s3-fs-presto` and
`flink-s3-fs-hadoop`) can only be used as plugins as we already removed the relocations. Placing them in libs/ will result in system failures.
{{< /hint >}}

{{< hint warning >}}
Because of the [strict isolation](#isolation-and-plugin-structure), file systems do not have access to credential providers in lib/
anymore. Please add any needed providers to the respective plugin folder.
{{< /hint >}}

## Metric Reporters

All [metric reporters]({{< ref "docs/deployment/metric_reporters" >}}) that Flink provides can be used as plugins.
See the [metrics]({{< ref "docs/ops/metrics" >}}) documentation for more details.

{{< top >}}


text:
responsive-php
==============

Framework PHP orientado a objetos


text:
<?xml version="1.0" encoding="utf-8"?>

<info><title>L'aide de vue HTML Object</title></info>

    <para>
        L'élément HTML <object> est utilisé pour inclure un média comme
        Flash ou QuickTime dans les pages Web. L'aide de vue Object vous aide à
        réaliser ceci avec un minimum d'effort.
    </para>

    <para>Il existe quatre aides de vue Object initiaux :</para>

    <itemizedlist>
        <listitem>
            <para>
                htmlFlash : génère le balisage pour l'inclusion de fichiers
                Flash.
            </para>
        </listitem>

        <listitem>
            <para>
                htmlObject : génère le balisage pour l'inclusion d'objets
                personnalisés.
            </para>
        </listitem>

        <listitem>
            <para>
                htmlPage : génère le balisage pour l'inclusion d'autres pages
                (X)HTML.
            </para>
        </listitem>

        <listitem>
            <para>
                htmlQuicktime : génère le balisage pour l'inclusion de fichiers
                QuickTime.
            </para>
        </listitem>
    </itemizedlist>

    <para>
        Toutes ces aides partagent une interface similaire. Pour cette raison, cette
        documentation ne présentera des exemples que pour deux de ces aides.
    </para>

    <example xml:id="zend.view.helpers.initial.object.flash"><info><title>Aide de vue Flash</title></info>

        <para>
            Inclure du Flash dans votre page est assez simple. Le seul argument requis est
            l'URI de la ressource.
        </para>

        <programlisting language="php"><![CDATA[
<?php echo $this->htmlFlash('/path/to/flash.swf'); ?>
]]></programlisting>

        <para>Ceci affichera le code HTML suivant :</para>

        <programlisting language="html"><![CDATA[
<object data="/path/to/flash.swf" type="application/x-shockwave-flash"
    classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"
    codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab">
</object>
]]></programlisting>
    </example>

    <para>
        Cependant vous pouvez aussi spécifier des attributs, des paramètres et du contenu qui
        peuvent être affichés avec la balise <object>. Ceci peut être montré avec
        l'aide de vue htmlObject.
    </para>

    <example xml:id="zend.view.helpers.initial.object.object"><info><title>Personnalisation d'un objet en fournissant des arguments additionnels</title></info>

        <para>
            Le premier argument de l'aide Object est toujours requis. Il s'agit
            de l'URI de la ressource à inclure. Le second argument est seulement requis par l'aide
            htmlObject. Les autres aides contiennent déjà la bonne valeur pour cet
            argument. Le troisième argument est utilisé pour fournir des attributs à l'élément
            object. Seul un tableau de paires clé/valeur est accepté.
            classid ou codebase sont des exemples de tels attributs. Le
            quatrième paramètre ne prend aussi qu'un tableau de paires clé/valeur est les utilise
            pour créer des éléments <param>. Enfin, vous avez la possibilité de
            fournir un contenu additionnel à l'objet en cinquième paramètre. Voici donc un exemple
            qui utilise tous le paramètres :
        </para>

        <programlisting language="php"><![CDATA[
<?php echo $this->htmlObject(
    '/path/to/file.ext',
    'mime/type',
    array(
        'attr1' => 'aval1',
        'attr2' => 'aval2'
    ),
    array(
        'param1' => 'pval1',
        'param2' => 'pval2'
    ),
    'some content'
); ?>
]]></programlisting>

        <para>Ceci affichera le code HTML suivant :</para>

        <para>
            <programlisting><![CDATA[
<object data="/path/to/file.ext" type="mime/type"
        attr1="aval1" attr2="aval2">
    <param name="param1" value="pval1" />
    <param name="param2" value="pval2" />
    some content
</object>
]]></programlisting></para>
        </example>


text:
''' Installation script for the fos package '''

from os.path import join as pjoin
from glob import glob
from distutils.core import setup
from distutils.extension import Extension
import numpy as np

from build_helpers import make_cython_ext

# we use cython to compile the module if we have it
try:
    import Cython
except ImportError:
    has_cython = False
else:
    has_cython = True

col_ext, cmdclass = make_cython_ext(
    'fos.core.collision',
    has_cython,
    include_dirs = [np.get_include()])

cgl_ext, cmdclass = make_cython_ext(
    'fos.core.cython_gl',
    has_cython,
    include_dirs = [np.get_include()])

setup(name='fos',
      version='0.2',
      description='Scientific 3d Engine',
      author='Fos Team',
      author_email='garyfallidis@gmail.com',
      url='http://github.com/Garyfallidis/Fos',
      packages=['fos','fos.core','fos.actor'],
      ext_modules = [col_ext],
      cmdclass    = cmdclass,
      )


text:
local utils = require 'pl.utils'

local append,format,strsub,strfind,strgsub = table.insert,string.format,string.sub,string.find,string.gsub

local APPENDER = "\n__R_size = __R_size + 1; __R_table[__R_size] = "

local function parseDollarParen(pieces, chunk, exec_pat, newline)
    local s = 1
    for term, executed, e in chunk:gmatch(exec_pat) do
        executed = '('..strsub(executed,2,-2)..')'
        append(pieces, APPENDER..format("%q", strsub(chunk,s, term - 1)))
        append(pieces, APPENDER..format("(%s or '')", executed))
        s = e
    end
    local r
    if newline then
        r = format("%q", strgsub(strsub(chunk,s),"\n",""))
    else
        r = format("%q", strsub(chunk,s))
    end
    if r ~= '""' then
        append(pieces, APPENDER..r)
    end
end

local function parseHashLines(chunk,inline_escape,brackets,esc,newline)
    local exec_pat = "()"..inline_escape.."(%b"..brackets..")()"

    local esc_pat = esc.."+([^\n]*\n?)"
    local esc_pat1, esc_pat2 = "^"..esc_pat, "\n"..esc_pat
    local  pieces, s = {"return function()\nlocal __R_size, __R_table = 0, {}", n = 1}, 1
    while true do
        local ss, e, lua = strfind(chunk,esc_pat1, s)
        if not e then
            ss, e, lua = strfind(chunk,esc_pat2, s)
            parseDollarParen(pieces, strsub(chunk,s, ss), exec_pat, newline)
            if not e then break end
        end
        append(pieces, "\n"..lua)
        s = e + 1
    end
    append(pieces, "\nreturn __R_table\nend")

    -- let's check for a special case where there is nothing to template, but it's
    -- just a single static string
    local short = false
    if (#pieces == 3) and (pieces[2]:find(APPENDER, 1, true) == 1) then
        pieces = { "return " .. pieces[2]:sub(#APPENDER+1,-1) }
        short = true
    end
    -- if short == true, the generated function will not return a table of strings,
    -- but a single string
    return table.concat(pieces), short
end

local template = {}

--- expand the template using the specified environment.
-- This function will compile and render the template. For more performant
-- recurring usage use the two step approach by using `compile` and `ct:render`.
-- There are six special fields in the environment table `env`
--
--   * `_parent`: continue looking up in this table (e.g. `_parent=_G`).
--   * `_brackets`: bracket pair that wraps inline Lua expressions,  default is '()'.
--   * `_escape`: character marking Lua lines, default is '#'
--   * `_inline_escape`: character marking inline Lua expression, default is '$'.
--   * `_chunk_name`: chunk name for loaded templates, used if there
--     is an error in Lua code. Default is 'TMP'.
--   * `_debug`: if truthy, the generated code will be printed upon a render error
--
-- @string str the template string
-- @tab[opt] env the environment
-- @return `rendered template + nil + source_code`, or `nil + error + source_code`. The last
-- return value (`source_code`) is only returned if the debug option is used.
function template.substitute(str,env)
    env = env or {}
    local t, err = template.compile(str, {
        chunk_name = rawget(env,"_chunk_name"),
        escape = rawget(env,"_escape"),
        inline_escape = rawget(env,"_inline_escape"),
        inline_brackets = rawget(env,"_brackets"),
        newline = nil,
        debug = rawget(env,"_debug")
    })
    if not t then return t, err end

    return t:render(env, rawget(env,"_parent"), rawget(env,"_debug"))
end

--- executes the previously compiled template and renders it.
-- @function ct:render
-- @tab[opt] env the environment.
-- @tab[opt] parent continue looking up in this table (e.g. `parent=_G`).
-- @bool[opt] db if thruthy, it will print the code upon a render error
-- (provided the template was compiled with the debug option).
-- @return `rendered template + nil + source_code`, or `nil + error + source_code`. The last return value
-- (`source_code`) is only returned if the template was compiled with the debug option.
-- @usage
-- local ct, err = template.compile(my_template)
-- local rendered , err = ct:render(my_env, parent)
local render = function(self, env, parent, db)
    env = env or {}
    if parent then  -- parent is a bit silly, but for backward compatibility retained
        setmetatable(env, {__index = parent})
    end
    setmetatable(self.env, {__index = env})

    local res, out = xpcall(self.fn, debug.traceback)
    if not res then
        if self.code and db then print(self.code) end
        return nil, out, self.code
    end
    return table.concat(out), nil, self.code
end

--- compiles the template.
-- Returns an object that can repeatedly be rendered without parsing/compiling
-- the template again.
-- The options passed in the `opts` table support the following options:
--
--   * `chunk_name`: chunk name for loaded templates, used if there
--     is an error in Lua code. Default is 'TMP'.
--   * `escape`: character marking Lua lines, default is '#'
--   * `inline_escape`: character marking inline Lua expression, default is '$'.
--   * `inline_brackets`: bracket pair that wraps inline Lua expressions, default is '()'.
--   * `newline`: string to replace newline characters, default is `nil` (not replacing newlines).
--   * `debug`: if truthy, the generated source code will be retained within the compiled template object, default is `nil`.
--
-- @string str the template string
-- @tab[opt] opts the compilation options to use
-- @return template object, or `nil + error + source_code`
-- @usage
-- local ct, err = template.compile(my_template)
-- local rendered , err = ct:render(my_env, parent)
function template.compile(str, opts)
    opts = opts or {}
    local chunk_name = opts.chunk_name or 'TMP'
    local escape = opts.escape or '#'
    local inline_escape = opts.inline_escape or '$'
    local inline_brackets = opts.inline_brackets or '()'

    local code, short = parseHashLines(str,inline_escape,inline_brackets,escape,opts.newline)
    local env = {}
    local fn, err = utils.load(code, chunk_name,'t',env)
    if not fn then return nil, err, code end

    if short then
        -- the template returns a single constant string, let's optimize for that
        local constant_string = fn()
        return {
            fn = fn(),
            env = env,
            render = function(self) -- additional params can be ignored
                -- skip the metatable magic and error handling in the render
                -- function above for this special case
                return constant_string, nil, self.code
            end,
            code = opts.debug and code or nil,
        }
    end

    return {
        fn = fn(),
        env = env,
        render = render,
        code = opts.debug and code or nil,
    }
end

return template


text:
using namespace renderer;

TEST_SUITE(Renderer_Kernel_Rendering_Progressive_SampleCounter)
{
    TEST_CASE(Constructor_InitializesSampleCountToZero)
    {
        SampleCounter sample_counter(3);

        EXPECT_EQ(0, sample_counter.read());
    }

    TEST_CASE(Clear_GivenThatOneSampleWasReserved_ResetSampleCountToZero)
    {
        SampleCounter sample_counter(3);
        sample_counter.reserve(1);

        sample_counter.clear();

        EXPECT_EQ(0, sample_counter.read());
    }

    TEST_CASE(Reserve_ReserveOneGivenMaxSampleCountIsZero_ReturnsZero)
    {
        SampleCounter sample_counter(0);

        EXPECT_EQ(0, sample_counter.reserve(1));
    }

    TEST_CASE(Reserve_ReserveOneGivenMaxSampleCountIsThree_ReturnsOne)
    {
        SampleCounter sample_counter(3);

        EXPECT_EQ(1, sample_counter.reserve(1));
    }

    TEST_CASE(Reserve_ReserveThreeGivenMaxSampleCountIsOne_ReturnsOne)
    {
        SampleCounter sample_counter(1);

        EXPECT_EQ(1, sample_counter.reserve(3));
    }

    TEST_CASE(Reserve_ReserveThreeAfterReserveThreeGivenMaxSampleCountIsOne_ReturnsZero)
    {
        SampleCounter sample_counter(1);
        sample_counter.reserve(3);

        EXPECT_EQ(0, sample_counter.reserve(3));
    }
}


text:
<resources>
	<string name="app_name">EasyLib</string>
</resources>


text:
<?php

$this->pageTitle = Yii::app()->name . ' - Blog';
$this->breadcrumbs = array(
    'Blog',
);
?>
<?php if (!empty($_GET['tag'])): ?>
    <?php echo BsHtml::alert(BsHtml::ALERT_COLOR_INFO, 'Wpisy oznaczone tagiem ' . BsHtml::italics(CHtml::encode($_GET['tag']) . '.')); ?>
<?php endif; ?>
<?php if (!empty($_GET['title'])): ?>
    <?php echo BsHtml::alert(BsHtml::ALERT_COLOR_INFO, 'Wpisy o tytule podobnym do  ' . BsHtml::italics(CHtml::encode($_GET['title']) . '.')); ?>
<?php endif; ?>
<?php if (!empty($_GET['year'])): ?>
    <?php echo BsHtml::alert(BsHtml::ALERT_COLOR_INFO, 'Wpisy archiwalne z roku ' . BsHtml::italics(CHtml::encode($_GET['year']) . '.')); ?>
<?php endif; ?>

<?php

Yii::app()->clientScript->registerScript('reInstallPostExpander', "
    function reInstallPostExpander()
    {
        $('div.postexpander').expander({
            slicePoint: 1500,
            expandPrefix: ' [...] ',
            expandText: 'Czytaj dalej',
            userCollapseText: '[^] Powrót',
            widow: 4,
            preserveWords: true,
            expandSpeed: 300,
            collapseSpeed: 300,
            //expandEffect: 'fadeIn',
            //collapseEffect: 'fadeOut',
        });
        $('.pop').popover({html:true});
        $('html, body').animate({ scrollTop: 0 }, 550);
    }
");
?>

<?php

$this->widget('bootstrap.widgets.BsListView', array(
    'dataProvider' => $dataProvider,
    'itemView' => '_view',
    'template' => "{items}\n{pager}",
    'enableHistory' => true,
    'afterAjaxUpdate' => "reInstallPostExpander",
));
?>


text:
package skycmd

import (
	"encoding/json"
	"errors"
	"fmt"

	"github.com/concourse/dex/connector/cf"
	"github.com/concourse/flag"
	multierror "github.com/hashicorp/go-multierror"
)

func init() {
	RegisterConnector(&Connector{
		id:         "cf",
		config:     &CFFlags{},
		teamConfig: &CFTeamFlags{},
	})
}

type CFFlags struct {
	ClientID           string      `long:"client-id" description:"(Required) Client id"`
	ClientSecret       string      `long:"client-secret" description:"(Required) Client secret"`
	APIURL             string      `long:"api-url" description:"(Required) The base API URL of your CF deployment. It will use this information to discover information about the authentication provider."`
	CACerts            []flag.File `long:"ca-cert" description:"CA Certificate"`
	InsecureSkipVerify bool        `long:"skip-ssl-validation" description:"Skip SSL validation"`
}

func (flag *CFFlags) Name() string {
	return "CloudFoundry"
}

func (flag *CFFlags) Validate() error {
	var errs *multierror.Error

	if flag.APIURL == "" {
		errs = multierror.Append(errs, errors.New("Missing api-url"))
	}

	if flag.ClientID == "" {
		errs = multierror.Append(errs, errors.New("Missing client-id"))
	}

	if flag.ClientSecret == "" {
		errs = multierror.Append(errs, errors.New("Missing client-secret"))
	}

	return errs.ErrorOrNil()
}

func (flag *CFFlags) Serialize(redirectURI string) ([]byte, error) {
	if err := flag.Validate(); err != nil {
		return nil, err
	}

	caCerts := []string{}
	for _, file := range flag.CACerts {
		caCerts = append(caCerts, file.Path())
	}

	return json.Marshal(cf.Config{
		ClientID:           flag.ClientID,
		ClientSecret:       flag.ClientSecret,
		APIURL:             flag.APIURL,
		RootCAs:            caCerts,
		InsecureSkipVerify: flag.InsecureSkipVerify,
		RedirectURI:        redirectURI,
	})
}

type CFTeamFlags struct {
	Users            []string `long:"user" description:"A whitelisted CloudFoundry user" value-name:"USERNAME"`
	Orgs             []string `long:"org" description:"A whitelisted CloudFoundry org" value-name:"ORG_NAME"`
	Spaces           []string `long:"space" description:"(Deprecated) A whitelisted CloudFoundry space for users with the 'developer' role" value-name:"ORG_NAME:SPACE_NAME"`
	SpacesAll        []string `long:"space-with-any-role" description:"A whitelisted CloudFoundry space for users with any role" value-name:"ORG_NAME:SPACE_NAME" mapstructure:"spaces_with_any_role"`
	SpacesDeveloper  []string `long:"space-with-developer-role" description:"A whitelisted CloudFoundry space for users with the 'developer' role" value-name:"ORG_NAME:SPACE_NAME" mapstructure:"spaces_with_developer_role"`
	SpacesAuditor    []string `long:"space-with-auditor-role" description:"A whitelisted CloudFoundry space for users with the 'auditor' role" value-name:"ORG_NAME:SPACE_NAME" mapstructure:"spaces_with_auditor_role"`
	SpacesManager    []string `long:"space-with-manager-role" description:"A whitelisted CloudFoundry space for users with the 'manager' role" value-name:"ORG_NAME:SPACE_NAME" mapstructure:"spaces_with_manager_role"`
	SpaceGuids       []string `long:"space-guid" description:"A whitelisted CloudFoundry space guid" value-name:"SPACE_GUID" mapstructure:"space_guids"`
	SpaceGuidsLegacy []string `mapstructure:"spaceguids"`
}

func (flag *CFTeamFlags) GetUsers() []string {
	return flag.Users
}

func (flag *CFTeamFlags) GetGroups() []string {
	var groups []string
	groups = append(groups, flag.Orgs...)
	groups = append(groups, flag.SpacesAll...)
	for _, space := range flag.Spaces {
		groups = append(groups, fmt.Sprintf("%s:developer", space))
	}
	for _, space := range flag.SpacesDeveloper {
		groups = append(groups, fmt.Sprintf("%s:developer", space))
	}
	for _, space := range flag.SpacesAuditor {
		groups = append(groups, fmt.Sprintf("%s:auditor", space))
	}
	for _, space := range flag.SpacesManager {
		groups = append(groups, fmt.Sprintf("%s:manager", space))
	}
	groups = append(groups, flag.SpaceGuids...)
	groups = append(groups, flag.SpaceGuidsLegacy...)
	return groups
}


text:
//
//  FMDataTableManager.h
//  FMDBDataTableDemo
//
//  Created by bing.hao on 15/8/28.
//  Copyright (c) 2015年 bing.hao. All rights reserved.
//

#import <Foundation/Foundation.h>
#import <FMDB.h>
#import "FMDataTableSchema.h"
#import "FMDataTableStatement.h"

#define DTM_SHARE [FMDataTableManager shared]

@interface FMDataTableManager : NSObject

+ (FMDataTableManager *)shared;

/**
 * @brief 是否输出日志
 */
@property (nonatomic, assign) BOOL logEnabled;

/**
 * @brief 缓存
 */
@property (nonatomic, strong, readonly) NSMutableDictionary *cache;

/**
 * @brief 获取当前模型的Schema
 */
- (FMDataTableSchema *)fetchSchema:(Class)ctype;
/**
 * @brief 获取当前模型的标准SQL语句
 */
- (FMDataTableStatement *)fetchStatement:(Class)ctype;

/**
 * @brief 绑定模型与数据据库的存储关系,并不是所有模型都必须要调用这个绑定方法的,
 *        这个只是为了实现一些自定义存储位置而开发的。如果不自动建立绑定关系,
 *        数据会存储在沙盒下的Library/Caches/{Bundle Identifier}.db
 *
 * @param classType 模型类型
 * @param dbName    数据库名称
 * @param dbPath    存储路径(默认存储在沙盒下的Library/Caches/)
 */
- (void)bindModelWithClass:(Class)classType dbName:(NSString *)dbName dbPath:(NSString *)dbPath;
- (void)bindModelWithClass:(Class)classType dbName:(NSString *)dbName;

/**
 * @brief 获取数据库存储路径
 */
- (NSString *)fetchPath:(Class)ctype;

/**
 * @brief 获取一个FMDatabase对象
 */
- (FMDatabase *)fetchDatabase:(Class)type;

/**
 * @brief 获取一个FMDatabaseQueue对象
 */
- (FMDatabaseQueue *)fetchDatabaseQueue:(Class)type;

/**
 * @brief 检查模型是否与物理数据库匹配完成
 */
- (void)checkModelIsReady:(Class)ctype;

@end


text:
package org.apache.flink.fs.osshadoop.writer;

import com.aliyun.oss.model.PartETag;
import org.hamcrest.Description;
import org.hamcrest.TypeSafeMatcher;
import org.junit.Test;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

import static org.hamcrest.MatcherAssert.assertThat;

/** Tests for the {@link OSSRecoverableSerializer}. */
public class OSSRecoverableSerializerTest {

    private final OSSRecoverableSerializer serializer = OSSRecoverableSerializer.INSTANCE;

    private static final String TEST_OBJECT_NAME = "TEST-OBJECT";

    private static final String TEST_UPLOAD_ID = "TEST-UPLOAD-ID";

    private static final String INCOMPLETE_OBJECT_NAME = "TEST-INCOMPLETE-PART";

    private static final String ETAG_PREFIX = "TEST-ETAG-";

    @Test
    public void testSerializeEmptyOSSRecoverable() throws IOException {
        OSSRecoverable originalEmptyRecoverable = createOSSRecoverable(false);

        byte[] serializedRecoverable = serializer.serialize(originalEmptyRecoverable);
        OSSRecoverable copiedEmptyRecoverable = serializer.deserialize(1, serializedRecoverable);

        assertThat(originalEmptyRecoverable, isEqualTo(copiedEmptyRecoverable));
    }

    @Test
    public void testSerializeOSSRecoverableOnlyWithIncompleteObject() throws IOException {
        OSSRecoverable originalEmptyRecoverable = createOSSRecoverable(true);

        byte[] serializedRecoverable = serializer.serialize(originalEmptyRecoverable);
        OSSRecoverable copiedEmptyRecoverable = serializer.deserialize(1, serializedRecoverable);

        assertThat(originalEmptyRecoverable, isEqualTo(copiedEmptyRecoverable));
    }

    @Test
    public void testSerializeOSSRecoverableWithIncompleteObject() throws IOException {
        OSSRecoverable originalEmptyRecoverable = createOSSRecoverable(true, 2, 4, 6);

        byte[] serializedRecoverable = serializer.serialize(originalEmptyRecoverable);
        OSSRecoverable copiedEmptyRecoverable = serializer.deserialize(1, serializedRecoverable);

        assertThat(originalEmptyRecoverable, isEqualTo(copiedEmptyRecoverable));
    }

    @Test
    public void testSerializeOSSRecoverableWithoutIncompleteObject() throws IOException {
        OSSRecoverable originalEmptyRecoverable = createOSSRecoverable(false, 2, 4, 6);

        byte[] serializedRecoverable = serializer.serialize(originalEmptyRecoverable);
        OSSRecoverable copiedEmptyRecoverable = serializer.deserialize(1, serializedRecoverable);

        assertThat(originalEmptyRecoverable, isEqualTo(copiedEmptyRecoverable));
    }

    // --------------------------------- Matchers ---------------------------------

    private static TypeSafeMatcher<OSSRecoverable> isEqualTo(OSSRecoverable expectedRecoverable) {
        return new TypeSafeMatcher<OSSRecoverable>() {

            @Override
            protected boolean matchesSafely(OSSRecoverable actualRecoverable) {

                return Objects.equals(
                                expectedRecoverable.getObjectName(),
                                actualRecoverable.getObjectName())
                        && Objects.equals(
                                expectedRecoverable.getUploadId(), actualRecoverable.getUploadId())
                        && expectedRecoverable.getNumBytesInParts()
                                == actualRecoverable.getNumBytesInParts()
                        && Objects.equals(
                                expectedRecoverable.getLastPartObject(),
                                actualRecoverable.getLastPartObject())
                        && expectedRecoverable.getLastPartObjectLength()
                                == actualRecoverable.getLastPartObjectLength()
                        && compareLists(
                                expectedRecoverable.getPartETags(),
                                actualRecoverable.getPartETags());
            }

            private boolean compareLists(final List<PartETag> first, final List<PartETag> second) {
                return Arrays.equals(
                        first.stream().map(PartETag::getETag).toArray(),
                        second.stream().map(PartETag::getETag).toArray());
            }

            @Override
            public void describeTo(Description description) {
                description.appendText(
                        expectedRecoverable + " with ignored LAST_PART_OBJECT_NAME.");
            }
        };
    }

    // --------------------------------- Test Utils ---------------------------------

    private static OSSRecoverable createOSSRecoverable(
            boolean withIncompletePart, int... partNumbers) {
        List<PartETag> etags = new ArrayList<>();
        for (int i : partNumbers) {
            etags.add(createEtag(i));
        }

        if (withIncompletePart) {
            return new OSSRecoverable(
                    TEST_UPLOAD_ID,
                    TEST_OBJECT_NAME,
                    etags,
                    INCOMPLETE_OBJECT_NAME,
                    12345L,
                    54321L);
        } else {
            return new OSSRecoverable(TEST_UPLOAD_ID, TEST_OBJECT_NAME, etags, null, 12345L, 0L);
        }
    }

    private static PartETag createEtag(int partNumber) {
        return new PartETag(partNumber, ETAG_PREFIX + partNumber);
    }
}


text:
package javaeetutorial.dukesbookstore.ejb;

import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javaeetutorial.dukesbookstore.entity.Book;
import javaeetutorial.dukesbookstore.exception.BookNotFoundException;
import javaeetutorial.dukesbookstore.exception.BooksNotFoundException;
import javaeetutorial.dukesbookstore.exception.OrderException;
import javaeetutorial.dukesbookstore.web.managedbeans.ShoppingCart;
import javaeetutorial.dukesbookstore.web.managedbeans.ShoppingCartItem;
import javax.ejb.EJBException;
import javax.ejb.Stateful;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

/**
 *
Stateful session bean for the bookstore example.

 */
@Stateful
public class BookRequestBean {

    @PersistenceContext
    private EntityManager em;
    private static final Logger logger =
            Logger.getLogger("dukesbookstore.ejb.BookRequestBean");

    public BookRequestBean() throws Exception {
    }

    public void createBook(String bookId, String surname, String firstname,
            String title, Double price, Boolean onsale, Integer calendarYear,
            String description, Integer inventory) {
        try {
            Book book = new Book(bookId, surname, firstname, title, price,
                    onsale, calendarYear, description, inventory);
            logger.log(Level.INFO, "Created book {0}", bookId);
            em.persist(book);
            logger.log(Level.INFO, "Persisted book {0}", bookId);
        } catch (Exception ex) {
            throw new EJBException(ex.getMessage());
        }
    }

    public List<Book> getBooks() throws BooksNotFoundException {
        try {
            return (List<Book>) em.createNamedQuery("findBooks").getResultList();
        } catch (Exception ex) {
            throw new BooksNotFoundException(
                    "Could not get books: " + ex.getMessage());
        }
    }

    public Book getBook(String bookId) throws BookNotFoundException {
        Book requestedBook = em.find(Book.class, bookId);

        if (requestedBook == null) {
            throw new BookNotFoundException("Couldn't find book: " + bookId);
        }

        return requestedBook;
    }

    public void buyBooks(ShoppingCart cart) throws OrderException {
        Collection<ShoppingCartItem> items = cart.getItems();
        Iterator<ShoppingCartItem> i = items.iterator();

        try {
            while (i.hasNext()) {
                ShoppingCartItem sci = (ShoppingCartItem) i.next();
                Book bd = (Book) sci.getItem();
                String id = bd.getBookId();
                int quantity = sci.getQuantity();
                buyBook(id, quantity);
            }
        } catch (OrderException ex) {
            throw new OrderException("Commit failed: " + ex.getMessage());
        }
    }

    public void buyBook(String bookId, int quantity)
            throws OrderException {
        try {
            Book requestedBook = em.find(Book.class, bookId);

            if (requestedBook != null) {
                int inventory = requestedBook.getInventory();

                if ((inventory - quantity) >= 0) {
                    int newInventory = inventory - quantity;
                    requestedBook.setInventory(newInventory);
                } else {
                    throw new OrderException(
                            "Not enough of " + bookId
                            + " in stock to complete order.");
                }
            }
        } catch (OrderException ex) {
            throw new OrderException(
                    "Couldn't purchase book: " + bookId + ex.getMessage());
        }
    }

    public void updateInventory(ShoppingCart cart) throws OrderException {
        try {
            buyBooks(cart);
        } catch (OrderException ex) {
            throw new OrderException("Inventory update failed: " + ex.getMessage());
        }
    }
}


text:
__author__ = "Simone Campagna"
__all__ = [
    'UpgraderMeta',
    'Upgrader',
    'MajorMinorUpgrader',
]

import abc
import inspect

from ...version import Version, VERSION

class UpgraderMeta(abc.ABCMeta):
    REGISTRY = []
    def __new__(mcls, class_name, class_bases, class_dict):
        cls = super().__new__(mcls, class_name, class_bases, class_dict)
        if not cls.isabstract():
            mcls.REGISTRY.append(cls())
        return cls

class Upgrader(metaclass=UpgraderMeta):
    @abc.abstractmethod
    def upgrade_accepts(self, version_from, version_to):
        """accepts(version_from, version_to) -> upgrade_version_to"""
        pass

    @abc.abstractmethod
    def downgrade_accepts(self, version_from, version_to):
        """downgrade_accepts(version_from, version_to) -> downgrade_version_to"""
        pass

    @classmethod
    def isabstract(cls):
        return inspect.isabstract(cls)

    def update_version(self, db, version_to, connection=None):
        with db.connect(connection) as connection:
            db.clear('version', connection=connection)
            db.write('version', [version_to], connection=connection)

    def upgrade(self, db, version_from, version_to, connection=None):
        db.logger.info("upgrade di versione da {} a {}".format(version_from, version_to))
        self.impl_upgrade(db, version_from, version_to, connection=connection)
        self.update_version(db, version_to, connection=connection)

    @abc.abstractmethod
    def impl_upgrade(db, version_from, version_to, connection=None):
        pass

    def downgrade(self, db, version_from, version_to, connection=None):
        db.logger.info("downgrade di versione da {} a {}".format(version_from, version_to))
        self.impl_downgrade(db, version_from, version_to, connection=connection)
        self.update_version(db, version_to, connection=connection)

    @abc.abstractmethod
    def impl_downgrade(db, version_from, version_to, connection=None):
        pass

    @classmethod
    def _full_upgrade_downgrade(cls, method_name, db, final_version=None):
        if method_name == 'upgrade':
            art = "l'"
            default_final_version = VERSION
            stop_condition = lambda version_from, final_version: version_from < final_version
        else:
            art = "il "
            default_final_version = Version(2, 0, 0)
            stop_condition = lambda version_from, final_version: version_from > final_version
        if final_version is None:
            final_version = default_final_version
        accepts_method_name = "{}_accepts".format(method_name)
        with db.connect() as connection:
            version_from = db.load_version(connection=connection)
            db.logger.info("full {} di versione da {} a {}".format(method_name, version_from, final_version))
            upgraders = []
            while stop_condition(version_from, final_version):
                valid_upgraders = []
                for upgrader in cls.REGISTRY:
                    accepts_method = getattr(upgrader, accepts_method_name)
                    version_to = accepts_method(version_from, final_version)
                    if version_to is not None:
                        valid_upgraders.append((version_to, upgrader))
                if valid_upgraders:
                    valid_upgraders.sort(key=lambda x: x[0], reverse=True)
                    version_to, upgrader = valid_upgraders[0]
                    upgraders.append((version_from, version_to, upgrader))
                    version_from = version_to
                else:
                    db.logger.warning("non è possibile eseguire {}{} dalla versione {} alla versione {}".format(art, method_name, version_from, final_version))
                    break
            for version_from, version_to, upgrader in upgraders:
                method = getattr(upgrader, method_name)
                method(db, version_from, version_to)

    @classmethod
    def full_upgrade(cls, db, final_version=None):
        return cls._full_upgrade_downgrade('upgrade', db=db, final_version=final_version)

    @classmethod
    def full_downgrade(cls, db, final_version=None):
        return cls._full_upgrade_downgrade('downgrade', db=db, final_version=final_version)

class MajorMinorUpgrader(Upgrader):
    VERSION_FROM_MAJOR_MINOR = Version(None, None, None)
    VERSION_TO_MAJOR_MINOR = Version(None, None, None)
    def upgrade_accepts(self, version_from, version_to):
        if version_from[:2] == self.VERSION_FROM_MAJOR_MINOR[:2]:
            return Version(
                major=self.VERSION_TO_MAJOR_MINOR.major,
                minor=self.VERSION_TO_MAJOR_MINOR.minor,
                patch=0,
            )
        else:
            return None

    def downgrade_accepts(self, version_from, version_to):
        if version_from[:2] == self.VERSION_TO_MAJOR_MINOR[:2]:
            return Version(
                major=self.VERSION_FROM_MAJOR_MINOR.major,
                minor=self.VERSION_FROM_MAJOR_MINOR.minor,
                patch=0,
            )
        else:
            return None

    def do_downgrade(self, db, table_name, old_table, new_table, new_to_old, version_from, version_to, connection=None):
        with db.connect(connection) as connection:
            cursor = connection.cursor()
            new_field_names = new_table.dict_type._fields
            sql = """SELECT {field_names} FROM {table_name};""".format(
                table_name=table_name,
                field_names=", ".join(new_field_names))
            new_values_list = list(db.execute(cursor, sql))
            db.drop(table_name, connection=connection)
            db.create_table(table_name, old_table.fields, connection=connection)
            old_field_names = old_table.dict_type._fields
            for new_values in new_values_list:
                new_data = {}
                for field_name, value in zip(new_field_names, new_values):
                    field_type = new_table.fields[field_name]
                    new_data[field_name] = field_type.db_from(value)
                new_data = dict(zip(new_field_names, new_values))
                old_values = []
                old_data = {}
                old_data.update(new_data)
                old_data.update(new_to_old(new_data))
                for field_name in old_field_names:
                    field_type = old_table.fields[field_name]
                    old_values.append(field_type.db_to(old_data[field_name]))
                sql = """INSERT INTO {table_name} ({field_names}) VALUES ({placeholders});""".format(
                    table_name=table_name,
                    field_names=', '.join(old_field_names),
                    placeholders=', '.join('?' for field in old_field_names),
                )
                db.execute(cursor, sql, old_values)

    def do_upgrade(self, db, table_name, old_table, new_table, old_to_new, version_from, version_to, connection=None):
        with db.connect(connection) as connection:
            cursor = connection.cursor()
            old_field_names = old_table.dict_type._fields
            sql = """SELECT {field_names} FROM {table_name};""".format(
                table_name=table_name,
                field_names=", ".join(old_field_names))
            old_values_list = list(db.execute(cursor, sql))
            db.drop(table_name, connection=connection)
            db.create_table(table_name, new_table.fields, connection=connection)
            new_field_names = new_table.dict_type._fields
            for old_values in old_values_list:
                old_data = {}
                for field_name, value in zip(old_field_names, old_values):
                    field_type = old_table.fields[field_name]
                    old_data[field_name] = field_type.db_from(value)
                new_values = []
                new_data = {}
                new_data.update(old_data)
                new_data.update(old_to_new(old_data))
                for field_name in new_field_names:
                    field_type = new_table.fields[field_name]
                    new_values.append(field_type.db_to(new_data[field_name]))
                sql = """INSERT INTO {table_name} ({field_names}) VALUES ({placeholders});""".format(
                    table_name=table_name,
                    field_names=', '.join(new_field_names),
                    placeholders=', '.join('?' for field in new_field_names),
                )
                db.execute(cursor, sql, new_values)


text:
namespace Kvasir {
//Digital-to-Analog Converter (DA)
    namespace Da1Cnt{    ///<DAC Control Register1
        using Addr = Register::Address<0x40055000,0xfffffffc,0x00000000,unsigned>;
        ///OP
        constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> op{};
        ///REFON
        constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> refon{};
    }
    namespace Da1Reg{    ///<DAC Data Register
        using Addr = Register::Address<0x40055004,0xffff003f,0x00000000,unsigned>;
        ///DAC
        constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,6),Register::ReadWriteAccess,unsigned> dac{};
    }
    namespace Da1Dctl{    ///<DAC Output Register
        using Addr = Register::Address<0x40055008,0xffe0f07c,0x00000000,unsigned>;
        ///WAVE
        constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,0),Register::ReadWriteAccess,unsigned> wave{};
        ///DMAEN
        constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,unsigned> dmaen{};
        ///TRGEN
        constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::ReadWriteAccess,unsigned> trgen{};
        ///TRGSEL
        constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,9),Register::ReadWriteAccess,unsigned> trgsel{};
        ///AMPSEL
        constexpr Register::FieldLocation<Addr,Register::maskFromRange(17,16),Register::ReadWriteAccess,unsigned> ampsel{};
        ///OFFSET
        constexpr Register::FieldLocation<Addr,Register::maskFromRange(20,18),Register::ReadWriteAccess,unsigned> offset{};
    }
    namespace Da1Tctl{    ///<DAC Trigger Register
        using Addr = Register::Address<0x4005500c,0xffff7ffe,0x00000000,unsigned>;
        ///SWTRG
        constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::Access<Register::AccessType::writeOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> swtrg{};
        ///DACCLR
        constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,15),Register::Access<Register::AccessType::writeOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> dacclr{};
    }
    namespace Da1Vctl{    ///<DAC Control Register2
        using Addr = Register::Address<0x40055010,0xffffff00,0x00000000,unsigned>;
        ///VHOLDCTF
        constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,0),Register::ReadWriteAccess,unsigned> vholdctf{};
        ///VHOLDCTB
        constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,4),Register::ReadWriteAccess,unsigned> vholdctb{};
    }
}


text:
import debug from 'debug';

const log = debug('service:tracking');

// Track mixpanel events only if Scope is running inside of Weave Cloud.
export function trackMixpanelEvent(name, props) {
  if (window.mixpanel && process.env.WEAVE_CLOUD) {
    window.mixpanel.track(name, props);
  } else {
    log('trackMixpanelEvent', name, props);
  }
}


text:
Package.describe({
  summary: "Bootstrap slider",
  version: "1.0.0"
});

Package.onUse(function(api) {
  api.versionsFrom('METEOR@1.0');
  api.addFiles('js/bootstrap-slider.js', 'client');
  api.addFiles('dist/css/bootstrap-slider.css', 'client');
});


text:
<?php

/**
 * @file
 *
 * WeChatCorpAPI
 * @see http://qydev.weixin.qq.com/wiki/index.php
 */

namespace Pyramid\Component\WeChat;

use Exception;

/**
 *
 *
 */
class WeChatCorpAPI {

    /**
     * 获取access_token
     */
    public function getAccessToken() {
        static $url = 'https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=%s&corpsecret=%s';
        $token = Utility::getCorpAccessToken($this);
        if (empty($token) || time() > $token['expired']) {
            $body= Utility::http(sprintf($url, $this->getConfig('appid'), $this->getConfig('appsecret')));
            $json = json_decode($body, true);
            if (!$json || !empty($json['errcode'])) {
                throw new Exception('Error - WeChatCorp Can not get AccessToken.');
            } else {
                $token['token']   = $json['access_token'];
                $token['expired'] = time() + $json['expires_in'] - 120;
                Utility::setCorpAccessToken($token, $this);
            }
        }

        return $token['token'];
    }

    /**
     * 验证配置
     */
    public function validateConfig() {
        static $url = 'https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=%s&corpsecret=%s';
        $body = Utility::http(sprintf($url, $this->getConfig('appid'), $this->getConfig('appsecret')));
        $json = json_decode($body, true);
        if (!$json || !empty($json['errcode'])) {
            return false;
        } else {
            return true;
        }
    }

}


text:
using System.Text.Json;
using Azure.Core;

namespace Azure.ResourceManager.CosmosDB.Models
{
    public partial class PrivateEndpointConnection : IUtf8JsonSerializable
    {
        void IUtf8JsonSerializable.Write(Utf8JsonWriter writer)
        {
            writer.WriteStartObject();
            writer.WritePropertyName("properties");
            writer.WriteStartObject();
            if (Optional.IsDefined(PrivateEndpoint))
            {
                writer.WritePropertyName("privateEndpoint");
                writer.WriteObjectValue(PrivateEndpoint);
            }
            if (Optional.IsDefined(PrivateLinkServiceConnectionState))
            {
                writer.WritePropertyName("privateLinkServiceConnectionState");
                writer.WriteObjectValue(PrivateLinkServiceConnectionState);
            }
            writer.WriteEndObject();
            writer.WriteEndObject();
        }

        internal static PrivateEndpointConnection DeserializePrivateEndpointConnection(JsonElement element)
        {
            Optional<string> id = default;
            Optional<string> name = default;
            Optional<string> type = default;
            Optional<PrivateEndpointProperty> privateEndpoint = default;
            Optional<PrivateLinkServiceConnectionStateProperty> privateLinkServiceConnectionState = default;
            foreach (var property in element.EnumerateObject())
            {
                if (property.NameEquals("id"))
                {
                    id = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("name"))
                {
                    name = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("type"))
                {
                    type = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("properties"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    foreach (var property0 in property.Value.EnumerateObject())
                    {
                        if (property0.NameEquals("privateEndpoint"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            privateEndpoint = PrivateEndpointProperty.DeserializePrivateEndpointProperty(property0.Value);
                            continue;
                        }
                        if (property0.NameEquals("privateLinkServiceConnectionState"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            privateLinkServiceConnectionState = PrivateLinkServiceConnectionStateProperty.DeserializePrivateLinkServiceConnectionStateProperty(property0.Value);
                            continue;
                        }
                    }
                    continue;
                }
            }
            return new PrivateEndpointConnection(id.Value, name.Value, type.Value, privateEndpoint.Value, privateLinkServiceConnectionState.Value);
        }
    }
}


text:
import re
import json

from .common import InfoExtractor

class WeiboIE(InfoExtractor):
    """
    The videos in Weibo come from different sites, this IE just finds the link
    to the external video and returns it.
    """
    _VALID_URL = r'https?://video\.weibo\.com/v/weishipin/t_(?P<id>.+?)\.htm'

    _TEST = {
        u'add_ie': ['Sina'],
        u'url': u'http://video.weibo.com/v/weishipin/t_zjUw2kZ.htm',
        u'file': u'98322879.flv',
        u'info_dict': {
            u'title': u'魔声耳机最新广告"All Eyes On Us"',
        },
        u'note': u'Sina video',
        u'params': {
            u'skip_download': True,
        },
    }

    # Additional example videos from different sites
    # Youku: http://video.weibo.com/v/weishipin/t_zQGDWQ8.htm
    # 56.com: http://video.weibo.com/v/weishipin/t_zQ44HxN.htm

    def _real_extract(self, url):
        mobj = re.match(self._VALID_URL, url, flags=re.VERBOSE)
        video_id = mobj.group('id')
        info_url = 'http://video.weibo.com/?s=v&a=play_list&format=json&mix_video_id=t_%s' % video_id
        info_page = self._download_webpage(info_url, video_id)
        info = json.loads(info_page)

        videos_urls = map(lambda v: v['play_page_url'], info['result']['data'])
        #Prefer sina video since they have thumbnails
        videos_urls = sorted(videos_urls, key=lambda u: u'video.sina.com' in u)
        player_url = videos_urls[-1]
        m_sina = re.match(r'https?://video.sina.com.cn/v/b/(\d+)-\d+.html', player_url)
        if m_sina is not None:
            self.to_screen('Sina video detected')
            sina_id = m_sina.group(1)
            player_url = 'http://you.video.sina.com.cn/swf/quotePlayer.swf?vid=%s' % sina_id
        return self.url_result(player_url)


text:
namespace SurgSim
{
namespace Physics
{

template <class T>
class MlcpMapping
{
public:
	MlcpMapping(){}

	/// Clear the mapping
	void clear()
	{
		m_indexMapping.clear();
	}

	/// Sets the key/value (add an entry if the key is not found, change the value otherwise)
	void setValue(const T* key, size_t value)
	{
		typename std::unordered_map<const T*, ptrdiff_t>::iterator found = m_indexMapping.find(key);
		if (found == m_indexMapping.end())
		{
			m_indexMapping.insert(std::make_pair(key, value));
		}
		else
		{
			(*found).second = value;
		}
	}

	/// Gets the value from a given key
	ptrdiff_t getValue(const T* key) const
	{
		typename std::unordered_map<const T*, ptrdiff_t>::const_iterator returnValue = m_indexMapping.find(key);
		return (returnValue == m_indexMapping.end() ? -1 : (*returnValue).second);
	}

private:

	/// The index mapping data structure
	std::unordered_map<const T*, ptrdiff_t> m_indexMapping;
};

}; // Physics
}; // SurgSim

#endif // SURGSIM_PHYSICS_MLCPMAPPING_H


text:
<!-- IBM_PROLOG_BEGIN_TAG                                                   -->
<!-- This is an automatically generated prolog.                             -->
<!--                                                                        -->
<!-- $Source: src/import/chips/p9/procedures/xml/error_info/p9_thread_control_errors.xml $ -->
<!--                                                                        -->
<!-- OpenPOWER HostBoot Project                                             -->
<!--                                                                        -->
<!-- Contributors Listed Below - COPYRIGHT 2015,2017                        -->
<!-- [+] International Business Machines Corp.                              -->
<!--                                                                        -->
<!--                                                                        -->
<!-- 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.                         -->
<!--                                                                        -->
<!-- IBM_PROLOG_END_TAG                                                     -->
<!-- @brief Error definitions for p9_thread_control procedure               -->
<hwpErrors>
  <!-- ********************************************************************* -->
  <hwpError>
    <sbeError/>
    <rc>RC_P9_THREAD_CONTROL_START_PRE_NOMAINT</rc>
    <description>Start command precondition not met: RAS STAT Maintenance bit is not set.</description>
    <ffdc>CORE_TARGET</ffdc>
    <ffdc>THREAD</ffdc>
    <ffdc>C_RAS_STATUS_REG</ffdc>
    <callout>
      <procedure>CODE</procedure>
      <priority>HIGH</priority>
    </callout>
  </hwpError>
  <!-- ********************************************************************* -->
  <hwpError>
    <sbeError/>
    <rc>RC_P9_THREAD_CONTROL_STOP_FAIL</rc>
    <description>Stop command issued to core PC, but RAS STAT maintenance bit is not set.</description>
    <ffdc>CORE_TARGET</ffdc>
    <ffdc>THREAD</ffdc>
    <ffdc>C_RAS_STATUS_REG</ffdc>
    <callout>
      <target>CORE_TARGET</target>
      <priority>HIGH</priority>
    </callout>
    <callout>
      <procedure>CODE</procedure>
      <priority>LOW</priority>
    </callout>
    <deconfigure>
      <target>CORE_TARGET</target>
    </deconfigure>
    <!-- Note:  FW will attempt to ensure instructions are stopped in many
         different cases with no interlock that we're in a reasonable state
         for the HWP to succeed.  Therefore, we should not gard out the HW,
         only deconfigure it.
    -->
  </hwpError>

  <!-- ********************************************************************* -->
  <hwpError>
    <sbeError/>
    <rc>RC_P9_THREAD_CONTROL_STEP_PRE_NOTSTOPPING</rc>
    <description>Step command precondition not met: Not all threads are stopped.</description>
    <ffdc>CORE_TARGET</ffdc>
    <ffdc>THREAD</ffdc>
    <ffdc>C_RAS_STATUS_REG</ffdc>
    <callout>
      <procedure>CODE</procedure>
      <priority>HIGH</priority>
    </callout>
  </hwpError>

  <!-- ********************************************************************* -->
  <hwpError>
    <sbeError/>
    <rc>RC_P9_THREAD_CONTROL_STEP_FAIL</rc>
    <description>Step command issued to core PC, but RAS STAT run bit is still set.</description>
    <ffdc>CORE_TARGET</ffdc>
    <ffdc>THREAD</ffdc>
    <ffdc>C_RAS_STATUS_REG</ffdc>
    <ffdc>PTC_STEP_COMP_POLL_LIMIT</ffdc>
    <callout>
      <target>CORE_TARGET</target>
      <priority>HIGH</priority>
    </callout>
    <callout>
      <procedure>CODE</procedure>
      <priority>LOW</priority>
    </callout>
    <!-- Note:  FW would only attempt to step in a debug support capacity,
         we don't want to remove (deconfig/gard) HW for a fail in this use case
    -->
  </hwpError>

  <!-- ********************************************************************* -->
  <hwpError>
    <sbeError/>
    <rc>RC_P9_THREAD_CONTROL_INVALID_COMMAND</rc>
    <description>p9_thread_control is called with an invalid command </description>
    <ffdc>CORE_TARGET</ffdc>
    <ffdc>THREAD</ffdc>
    <ffdc>COMMAND</ffdc>
    <callout>
      <procedure>CODE</procedure>
      <priority>HIGH</priority>
    </callout>
  </hwpError>

</hwpErrors>


text:
/*-----------------------------------------------------------
 GULP : Sprite Task
 -----------------------------------------------------------*/

var gulp = require('gulp');
var spritesmith = require('gulp.spritesmith');

gulp.task('sprite', function () {
  var spriteData = gulp.src('./img/for-sprite/*.png').pipe(spritesmith({
    imgName: 'sprite.png',
    cssName: 'sprite.scss',
    imgPath: '../img/sprite/sprite.png'
  }));

  spriteData.img.pipe(gulp.dest('./img/sprite/'));
  spriteData.css.pipe(gulp.dest('./css/sprites/'));

});


text:
package com.netflix.spinnaker.orca.clouddriver.tasks.servergroup;

import com.netflix.spinnaker.orca.api.pipeline.models.StageExecution;
import com.netflix.spinnaker.orca.clouddriver.CloudDriverService;
import com.netflix.spinnaker.orca.clouddriver.model.ServerGroup;
import com.netflix.spinnaker.orca.kato.pipeline.support.SourceResolver;
import com.netflix.spinnaker.orca.kato.pipeline.support.StageData;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class TitusInterestingHealthProviderNamesSupplier
    implements InterestingHealthProviderNamesSupplier {

  private final Logger log = LoggerFactory.getLogger(getClass());

  private static final String TITUS = "titus";
  private static final String INTERESTING_HEALTH_PROVIDER_NAMES = "interestingHealthProviderNames";
  private static final List<String> SUPPORTED_STAGES =
      Arrays.asList("cloneservergroup", "enableservergroup");

  private final CloudDriverService cloudDriverService;
  private final SourceResolver sourceResolver;

  @Autowired
  public TitusInterestingHealthProviderNamesSupplier(
      CloudDriverService cloudDriverService, SourceResolver sourceResolver) {
    this.cloudDriverService = cloudDriverService;
    this.sourceResolver = sourceResolver;
  }

  @Override
  public boolean supports(String cloudProvider, StageExecution stage) {
    if (!cloudProvider.equals(TITUS)) {
      return false;
    }

    return SUPPORTED_STAGES.contains(stage.getType().toLowerCase());
  }

  @Override
  public List<String> process(String cloudProvider, StageExecution stage) {
    try {
      StageData stageData = stage.mapTo(StageData.class);
      Optional<StageData.Source> sourceData = Optional.ofNullable(sourceResolver.getSource(stage));
      if (sourceData.isPresent()) {
        StageData.Source source = sourceData.get();
        String serverGroupName =
            source.getServerGroupName() != null ? source.getServerGroupName() : source.getAsgName();

        ServerGroup serverGroup =
            cloudDriverService.getServerGroupFromCluster(
                stageData.getApplication(),
                source.getAccount(),
                stageData.getCluster(),
                serverGroupName,
                source.getRegion(),
                cloudProvider);

        Map<String, String> titusServerGroupLabels = serverGroup.getLabels();

        if (titusServerGroupLabels != null
            && titusServerGroupLabels.containsKey(INTERESTING_HEALTH_PROVIDER_NAMES)) {
          String healthProviderNames =
              titusServerGroupLabels.get(INTERESTING_HEALTH_PROVIDER_NAMES);
          return Arrays.asList(healthProviderNames.split(","));
        }
      }
    } catch (Exception e) {
      log.error(
          "Failed to process interesting health provider names for cloud provider {} on stage {} ",
          cloudProvider,
          stage,
          e);
    }

    return null;
  }
}


text:
[![CI Status](http://img.shields.io/travis/xingheng/HUDHelper.svg?style=flat)](https://travis-ci.org/xingheng/HUDHelper)
[![Version](https://img.shields.io/cocoapods/v/HUDHelper.svg?style=flat)](http://cocoapods.org/pods/HUDHelper)
[![License](https://img.shields.io/cocoapods/l/HUDHelper.svg?style=flat)](http://cocoapods.org/pods/HUDHelper)
[![Platform](https://img.shields.io/cocoapods/p/HUDHelper.svg?style=flat)](http://cocoapods.org/pods/HUDHelper)

HUDHelper defines `Indicator` and `Toast` based on [MBProgressHUD](https://github.com/jdg/MBProgressHUD), the indicator acts as the default behaviour of MBProgressHUD, it won't hide until calling `hide` method explicitly, but the toast will hide automatically, that is, `indicator` is designed for progress to wait, `toast` is designed for showing tips.

## Usage

#### Toast

Show a simple toast:

```objective-c
HUDHelper.toast(self.view).title(@"Got response successfully!").show();
```

with subtitles:

```objective-c
HUDHelper.toast(self.view).title(@"Got response successfully!").subtitle(@"There are some additional info you should know...").show();
```

By default, its show time depends on the *main title* and *secondary title*'s length, distinguished by different languages' and common users' reading speed, you could configure it in the `HUDHelperPreferences`, or specify the constant interval for a single HUD:

```objective-c
HUDHelper.toast(self.view).title(@"...").interval(3).show();
```

Changing the main title or secondary title's features may be a independent for some cases, so you could change configure their font and foreground color:

```objective-c
HUDHelper.toast(self.view).title(@"...").titleFont([UIFont boldSystemFontOfSize:20]).titleColor(UIColor.blueColor).show();
```

Or uniform the default HUDs' feature in a global place without inheriting:

```objective-c
// Make sure it executed before initializing all the HUDs.
HUDHelper.preferences.configuration = ^(HUDHelper *_Nonnull hud) {
    // ...
};
```

Not only for the common `UIView`, there are also a default global `UIWindow` retained in `HUDHelperPreferences` class, its default value is the current application's `keyWindow`, you could attach the HUD there:

```objective-c
HUDHelper.toastInWindow().title(@"...").show();
```

By default, the HUD won't block the user interactions below the HUD views, but if you want:

```objective-c
HUDHelper.toastInWindow().title(@"...").interactionEnabled(YES).show();
```

We don't suppress the original functional from `MBProgressHUD`, actually, the main class `HUDHelper` is a subclass of `MBProgressHUD`, you could custom any native features including `mode`, `progress`, `customView`, etc.

#### Indicator

Show a simple indicator:

```objective-c
HUDHelper.indicator(self.view).title(@"Processing...").show();
```

Of course, `subtitle`, `titleFont`, `titleColor`, `actionButton` are available for indicators, too. The key differences is `hide`:

If the `hud` instance is available in both showing and hiding situations:

```objective-c
HUDHelper *hud = HUDHelper.indicatorInWindow().title(@"...").show();
// some asyn operations or related...
hud.hide();
```

This is the most direct solution to hide it, if the state changes happen in different method or class, you could get the showing one by:

```objective-c
HUDHelper.lastest(nil).hide();
// Passing the containing view if you know it:
HUDHelper.lastest(self.view).hide();
```

Or if want to hide all the HUDs directly:

```objective-c
HUDHelper.hideAll(YES);
```

Find more settings from documentation in source code.

## Example

To run the example project, clone the repo, and run `pod install` from the Example directory and run the only app scheme, or you could check out more code examples from [here](https://github.com/xingheng/HUDHelper/blob/master/Example/HUDHelper/HUDViewController.m).

## Installation

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

```ruby
pod "HUDHelper"
```

## Author

[Will Han](mailto://xingheng.hax@qq.com)

## License

HUDHelper is available under the MIT license. See the LICENSE file for more info.


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

    <title>ParkingSpotFactory</title>
    <meta name="date" content="2015-01-18">
    <link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

parking.api.business.parkingspot

Interface ParkingSpotFactory

All Known Implementing Classes:

                        SimpleParkingSpotFactory

public interface ParkingSpotFactory

Created by SKNZ on 29/12/2014.

Method Summary

All Methods Instance
                                Methods Abstract Methods

                                Modifier and Type
                                Method and Description

                                ParkingSpot

                                createParkingSpot()

                                void
                                setIdProvider(ParkingSpotIdProvider provider)

Create a new parking

Method Detail

setIdProvider

void setIdProvider(ParkingSpotIdProvider provider)

Create a new parking

Parameters:

provider - id provider which will be used during the creation of
                                        the parking spot

createParkingSpot

ParkingSpot createParkingSpot()

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
package org.copperengine.core;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

@Retention(RetentionPolicy.RUNTIME)
public @interface WorkflowDescription {
    String alias();

    long majorVersion() default 1;

    long minorVersion() default 0;

    long patchLevelVersion() default 0;
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  ~ Licensed to the Apache Software Foundation (ASF) under one
  ~ or more contributor license agreements.  See the NOTICE file
  ~ distributed with this work for additional information
  ~ regarding copyright ownership.  The ASF licenses this file
  ~ to you under the Apache License, Version 2.0 (the
  ~ "License"); you may not use this file except in compliance
  ~ with the License.  You may obtain a copy of the License at
  ~
  ~   http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing,
  ~ software distributed under the License is distributed on an
  ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  ~ KIND, either express or implied.  See the License for the
  ~ specific language governing permissions and limitations
  ~ under the License.
  -->

<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/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>org.apache.archiva</groupId>
    <artifactId>archiva-repository-admin</artifactId>
    <version>3.0.0-SNAPSHOT</version>
  </parent>
  <artifactId>archiva-repository-admin-api</artifactId>
  <name>Archiva Base :: Repository Admin Api</name>

  <properties>
    <site.staging.base>${project.parent.parent.parent.basedir}</site.staging.base>
  </properties>

  <dependencies>
    <dependency>
      <groupId>javax.xml.bind</groupId>
      <artifactId>jaxb-api</artifactId>
    </dependency>
    <dependency>
      <groupId>org.apache.archiva</groupId>
      <artifactId>archiva-storage-api</artifactId>
    </dependency>
    <dependency>
      <groupId>org.apache.archiva</groupId>
      <artifactId>archiva-repository-api</artifactId>
    </dependency>
    <dependency>
      <groupId>org.apache.archiva</groupId>
      <artifactId>archiva-proxy-api</artifactId>
    </dependency>
    <dependency>
      <groupId>org.apache.commons</groupId>
       <artifactId>commons-collections4</artifactId>
    </dependency>
    <dependency>
      <groupId>org.apache.commons</groupId>
      <artifactId>commons-lang3</artifactId>
    </dependency>
    <dependency>
      <groupId>org.apache.archiva.redback</groupId>
      <artifactId>redback-users-api</artifactId>
    </dependency>
    <!--
    <dependency>
      <groupId>org.apache.maven.indexer</groupId>
      <artifactId>indexer-core</artifactId>
      <classifier>shaded-lucene</classifier>
      <exclusions>
        <exclusion>
          <groupId>org.codehaus.plexus</groupId>
          <artifactId>plexus-container-default</artifactId>
        </exclusion>
        <exclusion>
          <groupId>classworlds</groupId>
          <artifactId>classworlds</artifactId>
        </exclusion>
        <exclusion>
          <groupId>commons-logging</groupId>
          <artifactId>commons-logging</artifactId>
        </exclusion>
        <exclusion>
          <groupId>velocity</groupId>
          <artifactId>velocity-dep</artifactId>
        </exclusion>
        <exclusion>
          <groupId>org.apache.maven</groupId>
          <artifactId>maven-plugin-registry</artifactId>
        </exclusion>
        <exclusion>
          <groupId>org.apache.maven</groupId>
          <artifactId>maven-settings</artifactId>
        </exclusion>
        <exclusion>
          <groupId>com.google.code.atinject</groupId>
          <artifactId>atinject</artifactId>
        </exclusion>
        <exclusion>
          <groupId>org.apache.lucene</groupId>
          <artifactId>lucene-queryparser</artifactId>
        </exclusion>
        <exclusion>
          <groupId>org.apache.lucene</groupId>
          <artifactId>lucene-analyzers-common</artifactId>
        </exclusion>
      </exclusions>
    </dependency>
    -->
  </dependencies>

  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-source-plugin</artifactId>
        <executions>
          <execution>
            <id>bind-sources</id>
            <goals>
              <goal>jar-no-fork</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>

</project>


text:
package resources

import (
	"fmt"

	"github.com/aws/aws-sdk-go/aws/session"
	"github.com/aws/aws-sdk-go/service/appstream"
)

type AppStreamFleetState struct {
	svc   *appstream.AppStream
	name  *string
	state *string
}

func init() {
	register("AppStreamFleetState", ListAppStreamFleetStates)
}

func ListAppStreamFleetStates(sess *session.Session) ([]Resource, error) {
	svc := appstream.New(sess)
	resources := []Resource{}

	params := &appstream.DescribeFleetsInput{}

	for {
		output, err := svc.DescribeFleets(params)
		if err != nil {
			return nil, err
		}

		for _, fleet := range output.Fleets {
			resources = append(resources, &AppStreamFleetState{
				svc:   svc,
				name:  fleet.Name,
				state: fleet.State,
			})
		}

		if output.NextToken == nil {
			break
		}

		params.NextToken = output.NextToken
	}

	return resources, nil
}

func (f *AppStreamFleetState) Remove() error {

	_, err := f.svc.StopFleet(&appstream.StopFleetInput{
		Name: f.name,
	})

	return err
}

func (f *AppStreamFleetState) String() string {
	return *f.name
}

func (f *AppStreamFleetState) Filter() error {
	if *f.state == "STOPPED" {
		return fmt.Errorf("already stopped")
	} else if *f.state == "DELETING" {
		return fmt.Errorf("already being deleted")
	}

	return nil
}


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

<title>Shape (libgdx API)</title>
<meta name="date" content="2013-11-03">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

				libgdx API

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

com.badlogic.gdx.physics.box2d

Class Shape

java.lang.Object

com.badlogic.gdx.physics.box2d.Shape

Direct Known Subclasses:

ChainShape, CircleShape, EdgeShape, PolygonShape

public abstract class Shape
extends java.lang.Object

A shape is used for collision detection. You can create a shape however you like. Shapes used for simulation in b2World are
 created automatically when a b2Fixture is created. Shapes may encapsulate a one or more child shapes.

 NOTE: YOU NEED TO DISPOSE SHAPES YOU CREATED YOURSELF AFTER YOU NO LONGER USE THEM! E.g. after calling body.createFixture();

Author:

mzechner

Nested Class Summary

Nested Classes

Modifier and Type
Class and Description

static class
Shape.Type

Enum describing the type of a shape

Field Summary

Fields

Modifier and Type
Field and Description

protected long
addr

the address of the shape

Constructor Summary

Constructors

Constructor and Description

Shape()

Method Summary

Methods

Modifier and Type
Method and Description

void
dispose()

Needs to be called when the shape is no longer used, e.g.

int
getChildCount()

Get the number of child primitives.

float
getRadius()

Returns the radius of this shape

abstract Shape.Type
getType()

Get the type of this shape.

protected static int
jniGetType(long addr)

void
setRadius(float radius)

Sets the radius of this shape

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

addr

protected long addr

the address of the shape

Constructor Detail

Shape

public Shape()

Method Detail

getType

public abstract Shape.Type getType()

Get the type of this shape. You can use this to down cast to the concrete shape.

Returns:

the shape type.

getRadius

public float getRadius()

Returns the radius of this shape

setRadius

public void setRadius(float radius)

Sets the radius of this shape

dispose

public void dispose()

Needs to be called when the shape is no longer used, e.g. after a fixture was created based on the shape.

jniGetType

protected static int jniGetType(long addr)

getChildCount

public int getChildCount()

Get the number of child primitives.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

libgdx API

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

				Copyright © 2010-2013 Mario Zechner (contact@badlogicgames.com), Nathan Sweet (admin@esotericsoftware.com)


text:
package com.ricky.codelab.eventbus;

import org.junit.Test;

import com.ricky.codelab.eventbus.annotation.Subscribe;

/**
 * Unit test for simple App.
 */
public class AppTest {

	@Test
	public void testEventBus(){

		EventBus eventBus = EventBus.getDefault();

		HelloEventListener listener = new HelloEventListener();

		eventBus.register(new HelloEventListener());

		eventBus.post(new HelloEvent(3, "ricky"));

		eventBus.unregister(listener);
	}
}

class HelloEventListener{

    @Subscribe
    public void listen(HelloEvent event) {
        System.out.println("receive msg:"+event.getMsg());
    }
}

class HelloEvent{
	private int id;
	private String msg;

	public HelloEvent(){
	}
	public HelloEvent(int id, String msg) {
		super();
		this.id = id;
		this.msg = msg;
	}

	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getMsg() {
		return msg;
	}
	public void setMsg(String msg) {
		this.msg = msg;
	}

}