text:
/***************************************************************************
 //            Modified by Kishora Nayak - 14/06/2016
 //            Modified by Enrico Fragiacomo - 15/01/2014
 //            Modified by Kunal Garg - 13/05/2018 (kgarg@cern.ch)
               Modified by Sudipan De - 01/04/2019 (sde@cern.ch)
               Modified by Dukhishyam Mallick- 01/04/2019 (dmallick@cern.ch)
	       Modified by Prottay           -31/08/2020
	       //Based on AddAnalysisTaskRsnMini
	       //pPb specific settings from AddTaskKStarPPB.C
	       //
	       // Macro to configure the KStarPlusMinus analysis task
	       // It calls all configs desired by the user, by means
	       // of the boolean switches defined in the first lines.
	       // ---
	       // Inputs:
	       //  1) flag to know if running on MC or data
	       //  2) collision system, whether pp, pPb or PbPb
	       // --
	       // Returns:
	       //  kTRUE  --> initialization successful
	       //  kFALSE --> initialization failed (some config gave errors)
	       //
	       ****************************************************************************/

//enum ERsnCollType_t { kPP=0,      kPPb,      kPbPb};

enum pairYCutSet { kPairDefault,    // USED ONLY FOR pA
    kNegative,       // USED ONLY FOR pA
    kCentral         // USED ONLY FOR pA
};

enum eventCutSet { kEvtDefault=0,
    kNoPileUpCut, //=1
    kDefaultVtx12,//=2
    kDefaultVtx8, //=3
    kDefaultVtx5, //=4
    kMCEvtDefault, //=5
    kSpecial1, //=6
    kSpecial2, //=7
    kNoEvtSel, //=8
    kSpecial3, //=9
    kSpecial4, //=10
    kSpecial5 //=11
};

enum eventMixConfig { kDisabled = -1,
    kMixDefault,     //=0 //10 events, Dvz = 1cm, DC = 10
    k5Evts,          //=1 //5 events, Dvz = 1cm, DC = 10
    k5Cent,          //=2 //10 events, Dvz = 1cm, DC = 5
};

AliRsnMiniAnalysisTask *AddTaskKStarPlusMinusPbPb2018
(
 Bool_t      isMC,
 Bool_t      enableMonitor=kTRUE,
 TString     monitorOpt="PbPb",
 Float_t     piPIDCut = 2.0,
 Float_t     nsigmaTOF = 3.0,
 Float_t     vtxZcut = 10.0,
 Int_t       customQualityCutsID=1,
 AliRsnCutSetDaughterParticle::ERsnDaughterCutSet cutPiCandidate = AliRsnCutSetDaughterParticle::kTPCpidTOFveto3s,
 Float_t     pi_k0s_PIDCut = 3.0,
 Bool_t      rejectPileUp=kTRUE,
 Bool_t      UseArmentousCut = kFALSE,
 Float_t     ArmentousParameter = 0.2,
 Float_t     massTol = 0.03,
 Float_t     massTolVeto = 0.0043,
 Int_t       tol_switch = 1,
 Double_t    tol_sigma = 6,
 Float_t     pLife = 12,
 Float_t     radiuslow = 5,
 Bool_t      Switch = kTRUE,
 Float_t     k0sDCA = 0.3,
 Float_t     k0sCosPoinAn = 0.99,
 Float_t     k0sDaughDCA = 0.3,
 Int_t       NTPCcluster = 70,
 TString     outNameSuffix = "KStarPlusMinus_V0Mass_Pt",
 Float_t     DCAxy = 0.1,
 Bool_t      enableSys = kFALSE,
 Float_t     crossedRows = 70,
 Int_t       Sys= 0,
 UInt_t      triggerMask=AliVEvent::kINT7,
 Int_t       nmix=10,
 Int_t                    imbin,
 Float_t                  limbin,
 Float_t                  himbin,
 Int_t                    ptbin,
 Float_t                  lptbin,
 Float_t                  hptbin,
 Int_t                    multbin,
 Float_t                  lmultbin,
 Float_t                  hmultbin,
 Bool_t    timeRangeCut      = kTRUE

 )
{
    //-------------------------------------------
    // event cuts
    //-------------------------------------------

  Float_t     maxDiffAngleMixDeg = 20.0;
  Float_t     maxDiffVzMix = 1.0;
  Float_t     maxDiffMultMix = 5.0;
  Bool_t      isPP=0;
  Float_t     v0rapidity= 0.5;
  Float_t     rowsbycluster = 0.8;
  Int_t aodFilterBit=0;

  Int_t       MultBins=aodFilterBit/100;
    //   cout<<"EVENTCUTID is    "<<evtCutSetID<<endl;

    /*if(evtCutSetID==eventCutSet::kDefaultVtx12) vtxZcut=12.0; //cm
    if(evtCutSetID==eventCutSet::kDefaultVtx8) vtxZcut=8.0; //cm
    if(evtCutSetID==eventCutSet::kDefaultVtx5) vtxZcut=5.0; //cm
    if(evtCutSetID==eventCutSet::kNoPileUpCut) rejectPileUp=kFALSE;
    */

    //if(isMC) rejectPileUp=kFALSE;

    //-------------------------------------------
    //mixing settings
    //-------------------------------------------

    //Int_t       nmix = 10;
    /*if (mixingConfigID == eventMixConfig::kMixDefault) nmix = 10;
    if (mixingConfigID == eventMixConfig::k5Evts)      nmix = 5;
    if (mixingConfigID == eventMixConfig::k5Cent)      maxDiffMultMix = 5;
    */
    //
    // -- INITIALIZATION ----------------------------------------------------------------------------
    // retrieve analysis manager
    //

    AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
    if (!mgr) {
        ::Error("AddTaskKStarPlusMinus", "No analysis manager to connect to.");
        return NULL;
    }

    // create the task and configure
    TString taskName = Form("KStarPlusMinus%s%s", (isPP? "pp" : "PbPb"), (isMC ? "MC" : "Data"));
        AliRsnMiniAnalysisTask* task = new AliRsnMiniAnalysisTask(taskName.Data(),isMC);
    //    task->SelectCollisionCandidates(AliVEvent::kMB);
	task->UseESDTriggerMask(triggerMask);
       if (isPP)
	 task->UseMultiplicity("QUALITY");
       else
	 task->UseMultiplicity("AliMultSelection_V0M");//Only for RunII

    //  task->UseMultiplicity("AliMultSelection_V0A");

    // task->UseCentrality("V0M");
    // task->UseMultiplicity("");

     // set event mixing options
     task->UseContinuousMix();
    //task->UseBinnedMix();
     task->SetNMix(nmix);
     task->SetMaxDiffVz(maxDiffVzMix);
    task->SetMaxDiffMult(maxDiffMultMix);
    if (!isPP) task->SetMaxDiffAngle(maxDiffAngleMixDeg*TMath::DegToRad()); //set angle diff in rad
    task->SetUseTimeRangeCut(timeRangeCut);
    task->UseMC(isMC);

    ::Info("AddAnalysisTaskTOFKStar", Form("Event mixing configuration: \n events to mix = %i \n max diff. vtxZ = cm %5.3f \n max diff multi = %\5.3f",  nmix, maxDiffVzMix, maxDiffMultMix));

    mgr->AddTask(task);

    //
    // -- EVENT CUTS (same for all configs) ---------------------------------------------------------
    //
    // cut on primary vertex:
    // - 2nd argument --> |Vz| range
    // - 3rd argument --> minimum required number of contributors
    // - 4th argument --> tells if TPC stand-alone vertexes must be accepted

    AliRsnCutEventUtils* cutEventUtils=new AliRsnCutEventUtils("cutEventUtils",kTRUE,rejectPileUp);
    cutEventUtils->SetCheckAcceptedMultSelection();

   //AliRsnCutPrimaryVertex *cutVertex = 0;
   //cutVertex=new AliRsnCutPrimaryVertex("cutVertex",vtxZcut,0,kFALSE);
   AliRsnCutPrimaryVertex *cutVertex=new AliRsnCutPrimaryVertex("cutVertex",vtxZcut,0,kFALSE);
   cutVertex->GetCheckGeneratedVertexZ();

   AliRsnCutSet *eventCuts = new AliRsnCutSet("eventCuts", AliRsnTarget::kEvent);
   eventCuts->AddCut(cutEventUtils);
   eventCuts->AddCut(cutVertex);
   eventCuts->SetCutScheme(Form("%s&%s",cutEventUtils->GetName(),cutVertex->GetName()));
   task->SetEventCuts(eventCuts);

   // -- EVENT-ONLY COMPUTATIONS -------------------------------------------------------------------
  //vertex
   Int_t vtxID = task->CreateValue(AliRsnMiniValue::kVz, kFALSE);
   AliRsnMiniOutput *outVtx = task->CreateOutput("eventVtx", "HIST", "EVENT");
   outVtx->AddAxis(vtxID, 400, -20.0, 20.0);

    //multiplicity
    Int_t multID=task->CreateValue(AliRsnMiniValue::kMult,kFALSE);
    AliRsnMiniOutput* outMult=task->CreateOutput("eventMult","HIST","EVENT");
    if(isPP)
    outMult->AddAxis(multID,400,0.5,400.5);
    else outMult->AddAxis(multID,100,0.,100.);

    TH2F* hvz=new TH2F("hVzVsCent","",100,0.,100., 240,-12.0,12.0);
    task->SetEventQAHist("vz",hvz);//plugs this histogram into the fHAEventVz data member

    TH2F* hmc=new TH2F("MultiVsCent","", 100,0.,100., 100,0.5,100.5);
    hmc->GetYaxis()->SetTitle("QUALITY");
    task->SetEventQAHist("multicent",hmc);//plugs this histogram into the fHAEventMultiCent data member

    //
    // -- PAIR CUTS (common to all resonances) ------------------------------------------------------
    //    Double_t    minYlab =  -0.465;
    // Double_t    maxYlab =  0.035;

    Double_t    minYlab = -0.5;
    Double_t    maxYlab = 0.5;

    AliRsnCutMiniPair* cutY=new AliRsnCutMiniPair("cutRapidity", AliRsnCutMiniPair::kRapidityRange);
    cutY->SetRangeD(-0.5,0.5);

    AliRsnCutMiniPair* cutV0=new AliRsnCutMiniPair("cutV0", AliRsnCutMiniPair::kContainsV0Daughter);

    AliRsnCutSet* PairCutsSame=new AliRsnCutSet("PairCutsSame",AliRsnTarget::kMother);
    PairCutsSame->AddCut(cutY);
    PairCutsSame->AddCut(cutV0);
    PairCutsSame->SetCutScheme(TString::Format("%s&(!%s)",cutY->GetName(),cutV0->GetName()).Data());
    //note the use of the ! operator in this cut scheme

    AliRsnCutSet* PairCutsMix=new AliRsnCutSet("PairCutsMix",AliRsnTarget::kMother);
    PairCutsMix->AddCut(cutY);
    PairCutsMix->SetCutScheme(cutY->GetName());
    //
    // -- CONFIG ANALYSIS --------------------------------------------------------------------------
    //        gROOT->LoadMacro("$ALICE_PHYSICS/PWGLF/RESONANCES/macros/mini/ConfigKStarPlusMinuspPbRun2.C");
    //gROOT->LoadMacro("$ALICE_PHYSICS/PWGLF/RESONANCES/macros/mini/ConfigKStarPlusMinusPbPb2018.C");
    gROOT->LoadMacro("$ALICE_PHYSICS/PWGLF/RESONANCES/macros/mini/ConfigKStarPlusMinusPbPb2018.C");
    //gROOT->LoadMacro("ConfigKStarPlusMinuspPbRun2.C");
    //gROOT->LoadMacro("ConfigKStarPlusMinusPbPb2018grid.C");

     if (isMC) {
       Printf("========================== MC analysis - PID cuts not used");
    } else
       Printf("========================== DATA analysis - PID cuts used");

     //    if(!ConfigKStarPlusMinuspPbRun2(task, isMC, isPP,isGT,isRotate,piPIDCut,nsigmaTOF,customQualityCutsID, cutPiCandidate, pi_k0s_PIDCut, aodFilterBit, enableMonitor, monitorOpt.Data(), massTol, massTolVeto, tol_switch, tol_sigma, pLife, radiuslow, Switch, k0sDCA, k0sCosPoinAn, k0sDaughDCA, NTPCcluster, "", PairCutsSame,PairCutsMix, DCAxy, enableSys, crossedRows, rowsbycluster, v0rapidity, Sys)) return 0x0;
     if(!ConfigKStarPlusMinusPbPb2018(task, isMC, piPIDCut,nsigmaTOF,customQualityCutsID, cutPiCandidate, pi_k0s_PIDCut, enableMonitor, monitorOpt.Data(), UseArmentousCut, ArmentousParameter, massTol, massTolVeto, tol_switch, tol_sigma, pLife, radiuslow, Switch, k0sDCA, k0sCosPoinAn, k0sDaughDCA, NTPCcluster, "", PairCutsSame,PairCutsMix, DCAxy, enableSys, crossedRows, rowsbycluster, Sys, imbin, limbin, himbin, ptbin, lptbin, hptbin, multbin, lmultbin, hmultbin)) return 0x0;

     //
     // -- CONTAINERS --------------------------------------------------------------------------------
     //
     TString outputFileName = AliAnalysisManager::GetCommonFileName();
     //  outputFileName += ":Rsn";
     Printf("AddTaskKStarPlusMinus - Set OutputFileName : \n %s\n", outputFileName.Data() );

     AliAnalysisDataContainer *output = mgr->CreateContainer(Form("RsnOut_%s_%.1f_%.1f_%.1f_%.2f_%.3f_%.f_%.f_%.f_%.1f_%.2f_%.1f_%.3f_%.1f_%.2f", outNameSuffix.Data(),piPIDCut,nsigmaTOF,customQualityCutsID,pi_k0s_PIDCut,massTol,massTolVeto,pLife,radiuslow, k0sDCA,k0sCosPoinAn,k0sDaughDCA, DCAxy, Sys), TList::Class(), AliAnalysisManager::kOutputContainer, outputFileName);

    mgr->ConnectInput(task, 0, mgr->GetCommonInputContainer());
    mgr->ConnectOutput(task, 1, output);

    return task;
}


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

package xl

import (
	"encoding/json"
	"fmt"
	"path/filepath"

	"github.com/minio/minio-xl/pkg/probe"
	"github.com/minio/minio-xl/pkg/xl/disk"
)

// healBuckets heal bucket slices
func (xl API) healBuckets() *probe.Error {
	if err := xl.listXLBuckets(); err != nil {
		return err.Trace()
	}
	bucketMetadata, err := xl.getXLBucketMetadata()
	if err != nil {
		return err.Trace()
	}
	disks := make(map[int]disk.Disk)
	for _, node := range xl.nodes {
		nDisks, err := node.ListDisks()
		if err != nil {
			return err.Trace()
		}
		for k, v := range nDisks {
			disks[k] = v
		}
	}
	for order, disk := range disks {
		if disk.IsUsable() {
			disk.MakeDir(xl.config.XLName)
			bucketMetadataWriter, err := disk.CreateFile(filepath.Join(xl.config.XLName, bucketMetadataConfig))
			if err != nil {
				return err.Trace()
			}
			defer bucketMetadataWriter.Close()
			jenc := json.NewEncoder(bucketMetadataWriter)
			if err := jenc.Encode(bucketMetadata); err != nil {
				return probe.NewError(err)
			}
			for bucket := range bucketMetadata.Buckets {
				bucketSlice := fmt.Sprintf("%s$0$%d", bucket, order) // TODO handle node slices
				err := disk.MakeDir(filepath.Join(xl.config.XLName, bucketSlice))
				if err != nil {
					return err.Trace()
				}
			}
		}
	}
	return nil
}

redpajama_set_name: RedPajamaGithub


text:
# JustAPI

Simple REST API based on plain PHP.

It works as a front controller to call an appropriate service class for the requested API call.

## Installation

### Composer
  composer require justso/justapi

### git
  git clone git://github.com/JustsoSoftware/JustAPI.git vendor/justso/justapi

## Setup

Create a `config.json` file in your root folder containing at least the following attributes:

```
  domain: FQDN of domain.
  packages: List of packages to be used by the PHP autoloader. They should be located directly under 'vendor'.
  services: List of services, having a pattern as key and a service locator as value.
  environments: List of environments your application is going to run in, e.g. 'production' or 'development'.
```

The service locator is either a PHP class name or begins with the keyword 'file:', saying that service calls matching
this pattern are handled by another list of services, located in the 'vendor' folder.
The name after 'file:' is the location of the service.

Each environment you specify, should contain at least the AppRoot which is the local path on the server where your code
is checked out, e.g. '/var/www/'. Additionally, it should specify the URLs for the application and optionally the API.

Here is a complete example for such a config.json file:

```
{
    "domain": "my-project.de",
    "packages": {
        "MyPackage": "/path/to/my/package"
    },
    "environments": {
        "production": {
            "approot": "/var/www/prod",
            "appurl":  "https://my-project.de",
            "apiurl":  "https://api.my-project.de",
            "apipprefix": "/"
        },
        "integration": {
            "approot": "/var/www/test",
            "appurl":  "https://test.my-project.de",
            "apiurl":  "https://test.my-project.de/api",
            "apipprefix": "/api/"
        },
        "autotest": {
            "approot": "/var/lib/jenkins/jobs/my-project/workspace",
            "appurl":  "http://localhost/my-project",
            "apiurl":  "http://localhost/my-project/api"
        },
        "development": {
            "approot": "/var/www/my-project",
            "appurl":  "http://local.my-project.de",
            "apiurl":  "http://local.my-project.de/api"
        }
    },
    "services": {
        "/api/myService":      "\\MyPackage\\MyService",
        "/api/otherService/*": "\\OtherPackage\\OtherService"
    }
}
```

If using Apache, you should configure it to have

```
Alias /api /path/to/my/project/vendor/justso/justapi/FrontController.php
```

In NginX, you could work with rewriting:

```
location /api/ {
    rewrite ^.*$ vendor/justso/justapi/FrontController.php;
}
```

This should invoke the front controller whenever a service is called on the sub directory '/api'.
It is possible to use JustAPI in a subdomain, e.g. 'api.example.com' as well.

## Autoloader

JustAPI contains a PSR-0 compliant autoloader. It is recommended to use it for your custom classes as well.
You only have to specify them in your config.json file in the 'packages' list with its path.

## SystemEnvironment

A key element of all classes in JustAPI is `SystemEnvironment` class and its `SystemEnvironmentInterface`. It is the
connection to all operating system functions, contains information about the installation, given parameters and the
file system.

## Dependency Injection Container

The package contains a simple Dependency Injection Container which can be configured in `/conf/dependencies.php` file.
It should contain only a `return` statement with a list of definitions with an identifier each. It is a good practice
to use the class name for the definition as the identifier, though it is possible to use other names.

If you use this convention and simply want to create new objects, then no definition is needed for that. You can
instantiate new objects then by calling `$object = $dic->get('\MyNameSpace\MyClassName');`.

It is possible to give an array of parameters to the `get()` call as a second parameter. If you don't specify any
parameters, at least the SystemEnvironment of the DependencyContainer is used as a parameter to the constructor.

If you want a class to be a singleton, place an entry in your `dependencies.php` file using the `singleton()` function:

```
return [
    '\MYNameSpace\MyClassName' => $this->singleton(MyNameSpace\MyClassName::class, [$this->env, 123])
];
```

This makes sure that every call to `get()` will return the same object. This object is instantiated the first time
`get()` is called for that object with the SystemEnvironment and a scalar value of `123` as constructor parameters.

## Specifying controller classes

To actually handle API requests, you must implement classes and derive from RestService to handle these requests and
 specify them in config.json. So, if your service class 'My\Cool\RestService' should handle requests on
 '/api/my/service', your 'services' entry should look like this:

```
"my/service": "My\\Cool\\Service"
```

If your class should handle calls like '/api/my/service/77' as well, the entry may contain a wildcard (`*`):

```
"my/service/*": "My\\Cool\\Service"
```

All requests matching the pattern are given to the service class then. It is possible to use wildcards in the middle
 of a service specification as well, e.g.

```
"my/service/*/subservice": "My\\Cool\\Service"
```

The service class can implement one or more of the following methods:

- getAction
- postAction
- putAction
- deleteAction

Output is placed in $this->environment and never be printed or echoed.

## Upgrading from version 2

If you upgrade from version 2, you should change a few things in your config.json file.

- In version 2 you only needed to specify the package name to make the auto loader find your package. But it required your package to be in `/vendor`. This is not required any more, but you need to specify both, the name of the package and it's location as a key/value pair in `packages`
- Routing API pathes is more flexible now and can handle other path prefixes than `/api` as well. But you are required to specify the full path of your service in your service rules.
- Function `DependencyContainerInterface::newInstanceOf()` was removed, so any calls should be replaced by a call to `get()` on the DependencyContainer object. This affects the DependencyContainer itself as well as the SystemEnvironment, which implements this interface.

## Support & More

If you need support, please contact us: http://justso.de


text:
<title>Pretty-Printer Commands - Debugging with GDB</title>
<meta http-equiv="Content-Type" content="text/html">
<meta name="description" content="Debugging with GDB">
<meta name="generator" content="makeinfo 4.8">
<link title="Top" rel="start" href="index.html#Top">
<link rel="up" href="Pretty-Printing.html#Pretty-Printing" title="Pretty Printing">
<link rel="prev" href="Pretty_002dPrinter-Example.html#Pretty_002dPrinter-Example" title="Pretty-Printer Example">
<link href="http://www.gnu.org/software/texinfo/" rel="generator-home" title="Texinfo Homepage">

<meta http-equiv="Content-Style-Type" content="text/css">

Previous: Pretty-Printer Example,
Up: Pretty Printing

10.9.3 Pretty-Printer Commands

info pretty-printer [<var>object-regexp</var> [<var>name-regexp</var>]]
Print the list of installed pretty-printers.
This includes disabled pretty-printers, which are marked as such.

<var>object-regexp</var> is a regular expression matching the objects
whose pretty-printers to list.
Objects can be global, the program space's file
(see Progspaces In Python),
and the object files within that program space (see Objfiles In Python).
See Selecting Pretty-Printers, for details on how gdb
looks up a printer from these three objects.

<var>name-regexp</var> is a regular expression matching the name of the printers
to list.

disable pretty-printer [<var>object-regexp</var> [<var>name-regexp</var>]]
Disable pretty-printers matching <var>object-regexp</var> and <var>name-regexp</var>.
A disabled pretty-printer is not forgotten, it may be enabled again later.

enable pretty-printer [<var>object-regexp</var> [<var>name-regexp</var>]]
Enable pretty-printers matching <var>object-regexp</var> and <var>name-regexp</var>.

Example:

Suppose we have three pretty-printers installed: one from library1.so
named foo that prints objects of type foo, and
another from library2.so named bar that prints two types of objects,
bar1 and bar2.

     (gdb) info pretty-printer
     library1.so:
       foo
     library2.so:
       bar
         bar1
         bar2
     (gdb) info pretty-printer library2
     library2.so:
       bar
         bar1
         bar2
     (gdb) disable pretty-printer library1
     1 printer disabled
     2 of 3 printers enabled
     (gdb) info pretty-printer
     library1.so:
       foo [disabled]
     library2.so:
       bar
         bar1
         bar2
     (gdb) disable pretty-printer library2 bar:bar1
     1 printer disabled
     1 of 3 printers enabled
     (gdb) info pretty-printer library2
     library1.so:
       foo [disabled]
     library2.so:
       bar
         bar1 [disabled]
         bar2
     (gdb) disable pretty-printer library2 bar
     1 printer disabled
     0 of 3 printers enabled
     (gdb) info pretty-printer library2
     library1.so:
       foo [disabled]
     library2.so:
       bar [disabled]
         bar1 [disabled]
         bar2

Note that for bar the entire printer can be disabled,
as can each individual subprinter.


text:
import queue, random, sys

# Take input
if len(sys.argv) > 1:
    N  = int(sys.argv[1])
else:
    N = int(input("N? "))

visited_states = set()   # Set of: (value, score)
solution = None

first_step = {
    "value": N,
    "from": None,
    "move": None,
    "score": 0,
}

to_process = queue.PriorityQueue()  # Pqueue of (abs_score, step)
to_process.put( (0, first_step) )

# While there are steps to process
while not to_process.empty():
    _, step = to_process.get()

    # Check if this is a solution
    if step["value"] == 1:
        if step["score"] == 0:
            solution = step
            break
        continue

    # Record this value/score state; if already visited, skip
    score_key = (step["value"], step["score"])
    if score_key in visited_states:
        continue
    visited_states.add(score_key)

    # Calculate what moves are available based on value mod 3
    move_options = {
        0: (0,),
        1: (-1, 2),
        2: (-2, 1),
    }[step["value"] % 3]

    if step["value"] == 2: # Edge case, can't reach zero
        move_options = (1,)

    # Create and record next steps
    for move in move_options:
        next_step = {
            "value": (step["value"] + move) // 3,
            "from": step,
            "move": move,
            "score": step["score"] + move
        }
        abs_score = abs(next_step["score"])
        abs_score += random.random() / 100000  # Hack to avoid comparing the second tuple element (dicts)
        to_process.put( (abs_score, next_step) )

# Impossible?
if not solution:
    print("Impossible")
    exit()

# Process into printable lines (moves are offset by 1)
output = []
current_step = solution
last_move = None
while current_step:
    if last_move is not None:
        output.append( (current_step["value"], last_move) )
    else:
        output.append( (current_step["value"],) )
    last_move = current_step["move"]
    current_step = current_step["from"]

# Print
for line in reversed(output):
    print(*line)

# Done!


text:
/* Overriden svn.js from:
  https://github.com/ddliu/node-svn-spawn/blob/master/lib/svn.js
   , in order to fix a bug in getLog method. */

import Spawn from 'easy-spawn';
import util from 'util';
import xml2js from 'xml2js';
import async from 'async';
import fs from 'fs';

var Client = function(options) {
  this.option({
    program: 'svn'
  }).option(options);
};

util.inherits(Client, Spawn);

Client.prototype.cmd = function(params, callback) {
  if (!util.isArray(params)) {
    params = [params];
  }
  if (this.getOption('username') !== undefined) {
    params.push('--username', this.getOption('username'));
  }
  if (this.getOption('password') !== undefined) {
    params.push('--password', this.getOption('password'));
  }
  if (this.getOption('noAuthCache') === true) {
    params.push('--no-auth-cache');
  }
  return Client.super_.prototype.cmd.call(this, params, callback);
};

/*
SVN commands
*/

Client.prototype.checkout = function(params, callback) {
  // try making dir
  var cwd = this.getOption('cwd');
  if (cwd !== undefined && !fs.existsSync(cwd)) {
    fs.mkdirSync(cwd);
  }

  if (typeof params === 'function') {
    callback = params;
    params = null;
  }

  // Default path
  if (typeof params === 'array' && params.length === 1) {
    params.splice(1, 0, '.');
  }
  else if (typeof params === 'string') {
    params = [params, '.'];
  }

  params = Spawn.joinParams('checkout', params);

  this.cmd(params, callback);
};

Client.prototype.update = function(params, callback) {
  if (typeof params === 'function') {
    callback = params;
    params = null;
  }
  params = Spawn.joinParams('update', params);

  this.cmd(params, callback);
};

Client.prototype.commit = function(params, callback) {
  if (typeof params === 'function') {
    callback = params;
    params = null;
  }
  params = Spawn.joinParams(['commit', '-m'], params);

  this.cmd(params, callback);
};

Client.prototype.add = function(params, callback) {
  if (typeof params === 'function') {
    callback = params;
    params = null;
  }
  params = Spawn.joinParams('add', params);

  this.cmd(params, callback);
};

Client.prototype.del = function(params, callback) {
  if (typeof params === 'function') {
    callback = params;
    params = null;
  }
  params = Spawn.joinParams('delete', params);

  this.cmd(params, callback);
};

Client.prototype.info = function(params, callback) {
  if (typeof params === 'function') {
    callback = params;
    params = null;
  }

  params = Spawn.joinParams('info', params);

  this.cmd(params, callback);
};

/**
* svn info with parsed info in callback
* @param  {Mixed}   params
* @param  {Function} callback
*/
Client.prototype.getInfo = function(params, callback) {
  if (typeof params === 'function') {
    callback = params;
    params = null;
  }
  var self = this;

  params = Spawn.joinParams(['info', '--xml'], params),

  async.waterfall([
    function(callback) {
      self.session('silent', true).cmd(params, callback);
    },
    function(data, callback) {
      xml2js.parseString(data,
        {
          explicitRoot: false,
          explicitArray: false
        },
        callback
      );
    },
  ], function(err, data) {
    if (callback) {
      if (err) {
        callback(err);
      }
      else {
        callback(err, data.entry);
      }
    }
  });
};

Client.prototype.status = function(params, callback) {
  if (typeof params === 'function') {
    callback = params;
    params = null;
  }

  params = Spawn.joinParams('status', params);

  this.cmd(params, callback);
};

/**
* svn status with parsed info in callback
*
* @see status list https://github.com/apache/subversion/blob/trunk/subversion/svn/schema/status.rnc
* @param  {Mixed}   params
* @param  {Function} callback
*/
Client.prototype.getStatus = function(params, callback) {
  if (typeof params === 'function') {
    callback = params;
    params = null;
  }
  var self = this;

  params = Spawn.joinParams(['status', '--xml'], params);

  async.waterfall([
    function(callback) {
      self.session('silent', true).cmd(params, callback);
    },
    function(data, callback) {
      xml2js.parseString(data,
        {
          explicitRoot: false,
          explicitArray: false
        },
        callback
      );
    }
  ], function(err, data) {
    if (callback) {
      if (err) {
        callback(err);
      }
      else {
        var list = [];
        if ('target' in data) {
          data = data.target;
          if ('entry' in data) {
            if (util.isArray(data.entry)) {
              for (var i = 0; i < data.entry.length; i++) {
                list.push(data.entry[i]);
              }
            } else {
              list.push(data.entry);
            }
          }
        }
        callback(null, list);
      }
    }
  });
};

Client.prototype.log = function(params, callback) {
  if (typeof params === 'function') {
    callback = params;
    params = null;
  }

  params = Spawn.joinParams('log', params);
  this.cmd(params, callback);
};

/**
* svn log with parsed info in callback
* sample result:
* <code>
* [
* { '$': { revision: '1' },
*   author: 'dong',
*   date: '2013-05-21T10:23:35.427701Z',
*   msg: 'tt'
* } ...
* ]
* </code>
* @param  {Mixed}   params
* @param  {Function} callback
*/
Client.prototype.getLog = function(params, callback) {
  if (typeof params === 'function') {
    callback = params;
    params = null;
  }

  var self = this;

  params = Spawn.joinParams(['log', '--xml'], params);

  async.waterfall([
    function(callback) {
      self.session('silent', true).cmd(params, callback);
    },
    function(data, callback) {
      xml2js.parseString(data,
        {
          explicitRoot: false,
          explicitArray: false
        },
        callback
      );
    }
  ], function(err, data) {
    if (callback) {
      if (err) {
        callback(err);
      }
      else {
        var list = [];
        if (util.isArray(data)) {
          for (var i = 0; i < data.length; i++) {
            list.push(data[i].logentry);
          }
        }
        else if(data.logentry) {
          list.push(data.logentry);
        }
        callback(null, list);
      }
    }
  });
};

/**
* Add all local changes to for commit
*
* @param  {Object}   options
*         - status
* @param  {Function} callback
*/
Client.prototype.addLocal = function(options, callback) {
  if (typeof options === 'function') {
    callback = options;
    options = {
      status: null
    }
  }

  if (!'status' in options) {
    options.status = null;
  }

  var self = this;

  async.waterfall([
    function(callback) {
      self.getStatus(callback);
    },
    function(data, callback) {
      // do not run in parallel, or svn might be locked
      async.eachSeries(data, function(info, callback) {
        var path = info.$.path,
        status = info['wc-status'].$.item;

        if (options.status === null || options.status.indexOf(status) !== -1) {
          // add
          if (['none', 'unversioned'].indexOf(status) !== -1) {
            self.add(path, function(err) {
              callback(err);
            });
          }
          // delete
          else if(['missing'].indexOf(status) !== -1) {
            self.del(path, function(err) {
              callback(err);
            });
          }
          else {
            callback(null);
          }
        }
        else {
          callback(null);
        }
      }, function(err) {
        callback(err);
      });
    }
  ], function(err) {
    callback && callback(err);
  });
};

Client.prototype.addLocalUnversioned = function(options, callback) {
  if (typeof options === 'function') {
    callback = options;
    options = {
    };
  }
  else if(options === undefined || options === null){
    options = {

    }
  }
  options.status = 'unversioned';
  this.addLocal(options, callback);
};

module.exports = Client;


text:
package org.fastcatsearch.job.management;

import org.fastcatsearch.common.io.Streamable;
import org.fastcatsearch.exception.FastcatSearchException;
import org.fastcatsearch.ir.IRService;
import org.fastcatsearch.ir.config.DataInfo.SegmentInfo;
import org.fastcatsearch.ir.document.Document;
import org.fastcatsearch.ir.document.DocumentReader;
import org.fastcatsearch.ir.field.Field;
import org.fastcatsearch.ir.io.BytesDataOutput;
import org.fastcatsearch.ir.io.DataInput;
import org.fastcatsearch.ir.io.DataOutput;
import org.fastcatsearch.ir.search.CollectionHandler;
import org.fastcatsearch.ir.search.SegmentReader;
import org.fastcatsearch.ir.search.SegmentSearcher;
import org.fastcatsearch.ir.settings.FieldSetting;
import org.fastcatsearch.ir.settings.PrimaryKeySetting;
import org.fastcatsearch.ir.settings.RefSetting;
import org.fastcatsearch.ir.settings.SchemaSetting;
import org.fastcatsearch.job.Job;
import org.fastcatsearch.service.ServiceManager;
import org.fastcatsearch.vo.CollectionIndexData;
import org.fastcatsearch.vo.CollectionIndexData.RowData;

import java.io.IOException;
import java.util.*;

public class GetCollectionIndexDataJob extends Job implements Streamable {

	private static final long serialVersionUID = 1123665008671820737L;
	private String collectionId;
	private int start;
	private int end;
	private String pkValue;

	public GetCollectionIndexDataJob() {}

	public GetCollectionIndexDataJob(String collectionId, int start, int end, String pkValue) {
		this.collectionId = collectionId;
		this.start = start;
		this.end = end;
		this.pkValue = pkValue;
	}

	@Override
	public JobResult doRun() throws FastcatSearchException {

		IRService irService = ServiceManager.getInstance().getService(IRService.class);

		CollectionHandler collectionHandler = irService.collectionHandler(collectionId);
		if(collectionHandler == null || !collectionHandler.isLoaded()){
			CollectionIndexData data = new CollectionIndexData(collectionId, 0, 0, new ArrayList<String>(), new ArrayList<RowData>(), new ArrayList<Boolean>());
			return new JobResult(data);
		}

		int segmentSize = collectionHandler.segmentSize();
		List<String> fieldList = new ArrayList<String>();
		List<RowData> indexDataList = new ArrayList<RowData>();
		List<Boolean> isDeletedList = new ArrayList<Boolean>();

		int documentSize = 0;
        int deleteSize = 0;
		try {
			SchemaSetting schemaSetting = collectionHandler.schema().schemaSetting();
			List<FieldSetting> fieldSettingList = schemaSetting.getFieldSettingList();
			PrimaryKeySetting primaryKeySetting = schemaSetting.getPrimaryKeySetting();
			List<RefSetting> primaryKeyIdList = primaryKeySetting.getFieldList();
			for (int i = 0; i < fieldSettingList.size(); i++) {
				FieldSetting fieldSetting = fieldSettingList.get(i);
				String fieldId = fieldSetting.getId();
				fieldList.add(fieldId);
			}
			if(pkValue != null && pkValue.length() > 0) {
				if(primaryKeyIdList != null && primaryKeyIdList.size() > 0) {
					String[] pkList = pkValue.split("\\s");
					BytesDataOutput tempOutput = new BytesDataOutput();
					int count = 0;
					Set<String> dupSet = new HashSet<String>();
					for(String pk : pkList) {
						pk = pk.trim();
						if(pk.length() == 0) {
							continue;
						}
						if(dupSet.contains(pk)){
							continue;
						}else{
							dupSet.add(pk);
						}
						for(SegmentReader segmentReader : collectionHandler.segmentReaders()) {
							int docNo = segmentReader.newSearchIndexesReader().getPrimaryKeyIndexesReader().getDocNo(pk, tempOutput);
							if (docNo != -1) {
	//							logger.debug(">>> {} , doc={}~ {}", count, start, end);
								if(count >= start && count <= end) {
									Document document = segmentReader.segmentSearcher().getDocument(docNo);
									if(document != null) {
										isDeletedList.add(segmentReader.deleteSet().isSet(docNo));
										add(document, segmentReader.segmentInfo().getId(), indexDataList);
									}
								}
								documentSize++;
								count++;
							}
						}
					}
				}
			}else{

				//이 배열의 index번호는 세그먼트번호.
				SegmentReader[] segmentReaderList = new SegmentReader[segmentSize];
				int[] segmentEndNumbers = new int[segmentSize];

                int segmentNumber = 0;
				List<SegmentInfo> segmentInfoList = new ArrayList<SegmentInfo>(collectionHandler.collectionContext().dataInfo().getSegmentInfoList());
				Collections.reverse(segmentInfoList);
				for(SegmentInfo segmentInfo : segmentInfoList) {
                    SegmentReader reader = collectionHandler.segmentReader(segmentInfo.getId());
					DocumentReader documentReader = reader.newDocumentReader();
					int count = documentReader.getDocumentCount();
					documentSize += count;
                    deleteSize += reader.deleteSet().getOnCount();
					segmentReaderList[segmentNumber] = reader;
//					segmentEndNumbers[segmentNumber] = documentSize - 1;
					segmentEndNumbers[segmentNumber] = count;
					logger.debug("segment[{}] EndNumbers[{}]={}", segmentInfo.getId(), segmentNumber, segmentEndNumbers[segmentNumber]);
					segmentNumber++;
				}

				//여러세그먼트에 걸쳐있을 경우를 고려한다.
				//segmentId, start, end가 저장된다.
				List<Integer[]> matchSegmentList = matchSegment(segmentEndNumbers, start, end - start + 1);
				//write data
				for(Integer[] matchSegment : matchSegmentList) {
					int segmentSequence = matchSegment[0];
					int startNo = matchSegment[1];
					int endNo = matchSegment[2];

					SegmentReader segmentReader = segmentReaderList[segmentSequence];

					if (segmentReader != null) {
						SegmentInfo segmentInfo = segmentReader.segmentInfo();
//						String segmentId = segmentInfo.getId();
						SegmentSearcher segmentSearcher = segmentReader.segmentSearcher();

                        for (int docNo = endNo; docNo >= startNo; docNo--) {
							Document document = segmentSearcher.getDocument(docNo);
							if(document == null){
								//문서의 끝에 다다름.
								continue;
							}
							isDeletedList.add(segmentReader.deleteSet().isSet(docNo));
							add(document, segmentReader.segmentInfo().getId(), indexDataList);
						}

					} else {
						logger.debug("segmentReader is NULL");
					}
				}

			}

			CollectionIndexData data = new CollectionIndexData(collectionId, documentSize, deleteSize, fieldList, indexDataList, isDeletedList);
			return new JobResult(data);

		} catch (Throwable t) {
			logger.error("", t);
			CollectionIndexData data = new CollectionIndexData(collectionId, 0, 0, null, null, null);
			return new JobResult(data);
		}

	}

	private void add(Document document, String segmentId, List<RowData> indexDataList) {
		int fieldSize = document.size();
		String[][] fieldData = new String[fieldSize][];
		for (int index = 0; index < fieldSize; index++) {
			Field field = document.get(index);
			fieldData[index] = new String[] { field.getId(), field.toString() };
		}
		RowData rowData = new RowData(segmentId, fieldData);
		indexDataList.add(rowData);
	}

	private List<Integer[]> matchSegment(int[] segDocSize, int start, int rows) {
		// [][세그먼트번호,시작번호,끝번호]
		ArrayList<Integer[]> list = new ArrayList<Integer[]>();
		for (int i = 0; i < segDocSize.length; i++) {
			if (start > segDocSize[i]) {
				start = start - segDocSize[i] - 1;
			} else {
				Integer[] res = new Integer[3];
				int emptyCount = segDocSize[i] - start + 1;
				res[0] = i;// 세그먼트번호
				if (emptyCount < rows) {
					res[1] = start;// 시작번호
					res[2] = segDocSize[i];
					start = 0;
					rows = rows - emptyCount;
					list.add(res);
				} else {
					res[1] = start;// 시작번호
					res[2] = start + rows - 1;// 끝번호
					list.add(res);
					break;
				}
			}
		}

		return list;
	}

	@Override
	public void readFrom(DataInput input) throws IOException {
		collectionId = input.readString();
		start = input.readInt();
		end = input.readInt();
		pkValue = input.readString();
	}

	@Override
	public void writeTo(DataOutput output) throws IOException {
		output.writeString(collectionId);
		output.writeInt(start);
		output.writeInt(end);
		output.writeString(pkValue);
	}

}


text:
title: Date / Time Datatypes
short_title: Date / Time
---

# Datetime Datatype

JSON doesn't have a date, datetime, or time datatype, so dates in Xapiand can
either be:

* Strings containing formatted dates, e.g. `"2001-05-24T10:41:25.123Z"`,
  `"2001-05-24"`, `"2001/05/24 10:41:25.123"` or ISO-8601.
* A floating point number representing seconds-since-the-epoch.
* An object containing a `_datetime` or `_date` type.

Internally, dates are converted to UTC (if the time-zone is specified) and
stored as a floating point number representing seconds-since-the-epoch.

Queries on dates are internally converted to range queries on this
representation, and the result of aggregations and stored fields is converted
back to a string depending on the date format that is associated with the field.

{% capture req %}

```json
UPDATE /bank/1

{
  "birthday": "2001-05-24T10:41:25.123Z"
}
```
{% endcapture %}
{% include curl.html req=req %}

{% capture req %}

```json
UPDATE /bank/1

{
  "birthday": {
    "_datetime": {
      "_year": 2001,
      "_month": 5,
      "_day": 24,
      "_hour": 10,
      "_min": 41,
      "_sec": 25,
      "_fsec": 0.123
    }
  }
}
```
{% endcapture %}
{% include curl.html req=req %}

## Optimized Range Searches

Data types like date and numeric are often used for range search. Due to the way
range searches are implemented, searchig for values is not as performant as
seaching by terms. To improve the performance of the search, Xapiand uses the
`_accuracy` keyword, which indexes terms for value thresholds which later are
used during the querying to improve the filtering and searching.

In the above example terms for the day, month and year are generated.

Default accuracy in datetime fields is:

```json
[ "hour", "day", "month", "year", "decade", "century" ]
```

## Date Math Expressions

The _Date Datatype_ supports using date math expressions when using it in a
query/filter or during indexation. Whenever durations need to be specified,
e.g. for a timeout parameter, the duration can be specified.

The expression starts with an "_anchor_" date, which can be either `now` or a
date string (in the applicable format) ending with `||`. This anchor date can
optionally be followed by one or more maths expressions:

* `+1h` - add one hour
* `-1d` - subtract one day
* `/d` - round down to the nearest day

The supported units are:

|-----|---------|
| `y` | Years   |
| `M` | Months  |
| `w` | Weeks   |
| `d` | Days    |
| `h` | Hours   |
| `m` | Minutes |
| `s` | Seconds |

### Example

{% capture req %}

```json
UPDATE /bank/2

{
    "birthday": {
      "_value": "2019-01-01||-18y+4M+23d",
      "_type": "datetime"
    }
}
```
{% endcapture %}
{% include curl.html req=req %}

The above example is indexed as "`2001-05-24`".

## Parameters

The following parameters are accepted by _Date_ fields:

|---------------------------------------|-----------------------------------------------------------------------------------------|
| `_accuracy`                           | Array with the accuracies to be indexed: `"second"`, `"minute"`, `"day"`, `"hour"`, `"month"`, `"year"`, `"decade"`, `"century"`, `"millennium"` |
| `_value`                              | The value for the field. (Only used at index time).                                     |
| `_index`                              | The mode the field will be indexed as: `"none"`, `"field_terms"`, `"field_values"`, `"field_all"`, `"field"`, `"global_terms"`, `"global_values"`, `"global_all"`, `"global"`, `"terms"`, `"values"`, `"all"`. (The default is `"field_all"`). |
| `_slot`                               | The slot number. (It's calculated by default).                                          |
| `_prefix`                             | The prefix the term is going to be indexed with. (It's calculated by default)           |
| `_weight`                             | The weight the term is going to be indexed with.                                        |

# Time Datatype

The `time` can also be a type without the entire date:

For example:
{% capture req %}

```json
UPDATE /bank/1

{
  "wakeupTime": {
    "_value": "10:12:12.123",
    "_type": "time"
  }
}
```
{% endcapture %}
{% include curl.html req=req %}

# Time Delta Datatype

For example:
{% capture req %}

```json
UPDATE /bank/1

{
  "delay": {
    "_type": "timedelta",
    "_value": "+10:12:12.123"
  }
}
```
{% endcapture %}
{% include curl.html req=req %}


text:
package br.com.uol.pagseguro.domain;

import br.com.uol.pagseguro.enums.DocumentType;
import br.com.uol.pagseguro.helper.PagSeguroUtil;

/**
 * Class that represents a Sender Document
 *
 */
public class SenderDocument {

    /** Sender document type */
    private DocumentType type;

    /** Sender document value */
    private String value;

    /**
     * The constructor
     */
    public SenderDocument() {

    }

    /**
     * The constructor
     *
     * @param documentType
     * @param value
     */
    public SenderDocument(DocumentType type, String value) {
        this.type = type;
        this.value = PagSeguroUtil.getOnlyNumbers(value);
    }

    /**
     * Gets document type
     *
     * @return String
     */
    public DocumentType getType() {
        return this.type;
    }

    /**
     * Sets document type
     *
     * @param String
     *            type
     */
    public void setType(DocumentType type) {
        this.type = type;
    }

    /**
     * Gets document value
     *
     * @return Long
     */
    public String getValue() {
        return this.value;
    }

    /**
     * Sets document value
     *
     * @param String
     *            value
     */
    public void setValue(String value) {
        this.value = PagSeguroUtil.getOnlyNumbers(value);
    }

    /**
     * Gets toString class return string
     */
    @Override
    public String toString() {
        return "PagSeguroSenderDocument [type=" + type + ", value=" + value + "]";
    }
}


text:
package fr.adrienbrault.idea.symfony2plugin.action.ui;

import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiFile;
import com.jetbrains.php.lang.psi.elements.Method;
import com.jetbrains.php.lang.psi.elements.PhpClass;
import fr.adrienbrault.idea.symfony2plugin.util.PhpElementsUtil;
import fr.adrienbrault.idea.symfony2plugin.util.dict.ServiceTag;
import fr.adrienbrault.idea.symfony2plugin.util.dict.ServiceUtil;
import fr.adrienbrault.idea.symfony2plugin.util.yaml.YamlHelper;
import org.apache.commons.lang.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.yaml.psi.YAMLFile;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.StringWriter;
import java.util.*;

/**
 * @author Daniel Espendiller <daniel@espendiller.net>
 */
public class ServiceBuilder {

    public enum OutputType {
        Yaml, XML,
    }

    private List<MethodParameter.MethodModelParameter>  methodModelParameter;
    private Project project;

    /**
     * Symfony 3.3 class name can be id attribute for services
     */
    private final boolean isClassAsIdAttribute;

    @Nullable
    private PsiFile psiFile;

    public ServiceBuilder(@NotNull List<MethodParameter.MethodModelParameter> methodModelParameter, @NotNull Project project, boolean isClassAsIdAttribute) {
        this.methodModelParameter = methodModelParameter;
        this.project = project;
        this.isClassAsIdAttribute = isClassAsIdAttribute;
    }

    public ServiceBuilder(@NotNull List<MethodParameter.MethodModelParameter> methodModelParameter, @NotNull PsiFile psiFile, boolean isClassAsIdAttribute) {
        this.methodModelParameter = methodModelParameter;
        this.project = psiFile.getProject();
        this.psiFile = psiFile;
        this.isClassAsIdAttribute = isClassAsIdAttribute;
    }

    @Nullable
    public String build(OutputType outputType, String className, String serviceName) {
        HashMap<String, List<MethodParameter.MethodModelParameter>> methods = new HashMap<>();

        for(MethodParameter.MethodModelParameter methodModelParameter: this.methodModelParameter) {

            String methodName = methodModelParameter.getName();
            if(methodModelParameter.getMethod().getMethodType(false) == Method.MethodType.CONSTRUCTOR) {
                methodName = "__construct";
            }

            if(methods.containsKey(methodModelParameter.getName())) {
                methods.get(methodName).add(methodModelParameter);
            } else {
                methods.put(methodName, new ArrayList<>(Collections.singletonList(methodModelParameter)));
            }
        }

        if(outputType == OutputType.Yaml) {
            return buildYaml(methods, className, serviceName);
        }

        if(outputType == OutputType.XML) {
            return buildXml(methods, className, serviceName);
        }

        return null;
    }

    @Nullable
    private List<String> getParameters(List<MethodParameter.MethodModelParameter> methodModelParameters) {
        boolean hasCall = false;
        List<String> methodCalls = new ArrayList<>();

        // sort by indexes parameter
        methodModelParameters.sort((o1, o2) -> ((Integer) o1.getIndex()).compareTo(o2.getIndex()));

        for(MethodParameter.MethodModelParameter methodModelParameter: methodModelParameters) {

            // only add items which have at least one service parameter
            if(!hasCall && methodModelParameter.isPossibleService()) {
                hasCall = true;
            }

            // missing required parameter; add to service template, so use can correct it after
            String currentService = methodModelParameter.getCurrentService();
            if(currentService == null || !methodModelParameter.isPossibleService()) {
                currentService = "?";
            }

            methodCalls.add(currentService);

        }

        if(!hasCall || methodCalls.size() == 0) {
            return null;
        }

        return methodCalls;
    }

    @Nullable
    private String buildXml(Map<String, List<MethodParameter.MethodModelParameter>> methods, String className, String serviceName) {
        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder;
        try {
            docBuilder = docFactory.newDocumentBuilder();
        } catch (ParserConfigurationException e) {
            return null;
        }

        // root elements
        final Document doc = docBuilder.newDocument();
        final Element rootElement = doc.createElement("service");
        rootElement.setAttribute("id", !this.isClassAsIdAttribute ? serviceName : className);

        if(!this.isClassAsIdAttribute) {
            rootElement.setAttribute("class", className);
        }

        doc.appendChild(rootElement);

        if(methods.containsKey("__construct")) {

            List<String> parameters = getParameters(methods.get("__construct"));
            if(parameters != null) {
                appendArgumentXmlTags(doc, rootElement, parameters);
            }

            methods.remove("__construct");
        }

        for(Map.Entry<String, List<MethodParameter.MethodModelParameter>> entry: methods.entrySet()) {

            List<String> parameters = getParameters(entry.getValue());
            if(parameters != null) {
                Element calls = doc.createElement("call");
                calls.setAttribute("method", entry.getKey());
                appendArgumentXmlTags(doc, calls, parameters);
                rootElement.appendChild(calls);
            }
        }

        serviceTagCallback(className, serviceTags -> {

            for (ServiceTag serviceTag : serviceTags) {
                try {
                    // convert string to node
                    Element node = DocumentBuilderFactory
                        .newInstance()
                        .newDocumentBuilder()
                        .parse(new ByteArrayInputStream(serviceTag.toXmlString().getBytes()))
                        .getDocumentElement();

                    rootElement.appendChild(doc.importNode(node, true));

                } catch (SAXException | IOException | ParserConfigurationException ignored) {
                }
            }
        });

        try {
            return getStringFromDocument(doc);
        } catch (TransformerException e) {
            return null;
        }
    }

    /**
     * Build arguments tags
     *
     * <argument type="service" id="foobar"/>
     */
    private void appendArgumentXmlTags(@NotNull Document doc, @NotNull Element rootElement, @NotNull List<String> parameters) {
        for(String parameter: parameters) {
            Element argument = doc.createElement("argument");
            argument.setAttribute("type", "service");
            argument.setAttribute("id", parameter);
            rootElement.appendChild(argument);
        }
    }

    private static String getStringFromDocument(Document doc) throws TransformerException {

        StringWriter writer = new StringWriter();
        StreamResult result = new StreamResult(writer);

        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");

        transformer.transform(new DOMSource(doc), result);

        return writer.toString();
    }

    private String buildYaml(Map<String, List<MethodParameter.MethodModelParameter>> methods, String className, String serviceName) {
        int indentSpaces = 4;

        // find indent on file content
        if(psiFile instanceof YAMLFile) {
            indentSpaces = YamlHelper.getIndentSpaceForFile((YAMLFile) psiFile);
        }

        // yaml files are spaces only; fill indent
        String indent = StringUtils.repeat(" ", indentSpaces);

        List<String> lines = new ArrayList<>();

        lines.add((this.isClassAsIdAttribute ? className : serviceName) + ":");
        if(!this.isClassAsIdAttribute) {
            lines.add(indent + "class: " + className);
        }

        if(methods.containsKey("__construct")) {
            List<String> parameters = getParameters(methods.get("__construct"));
            if(parameters != null) {
                lines.add(String.format("%sarguments: [%s]", indent, StringUtils.join(formatYamlService(parameters), ", ")));
            }

            methods.remove("__construct");
        }

        List<String> calls = new ArrayList<>();
        for(Map.Entry<String, List<MethodParameter.MethodModelParameter>> entry: methods.entrySet()) {
            List<String> parameters = getParameters(entry.getValue());
            if(parameters != null) {
                calls.add(String.format("%s%s- [%s, [%s]]", indent, indent, entry.getKey(), StringUtils.join(formatYamlService(parameters), ", ")));
            }
        }

        if(calls.size() > 0) {
            lines.add(indent + "calls:");
            lines.addAll(calls);
        }

        serviceTagCallback(className, serviceTags -> {
            lines.add(indent + "tags:");
            for (ServiceTag serviceTag : serviceTags) {
                lines.add(indent + indent + serviceTag.toYamlString());
            }
        });

        if(lines.size() == 1) {
            lines.set(0, lines.get(0) + " ~");
        }

        return StringUtils.join(lines, "\n");
    }

    private void serviceTagCallback(String className, TagCallbackInterface callback) {

        PhpClass phpClass = PhpElementsUtil.getClass(project, className);
        if(phpClass == null) {
            return;
        }

        List<ServiceTag> serviceTags = new ArrayList<>();
        for (String tag : ServiceUtil.getPhpClassServiceTags(phpClass)) {
            ServiceTag serviceTag = new ServiceTag(phpClass, tag);
            ServiceUtil.decorateServiceTag(serviceTag);
            serviceTags.add(serviceTag);
        }

        if(serviceTags.size() == 0) {
            return;
        }

        callback.onTags(serviceTags);
    }

    private List<String> formatYamlService(List<String> parameters) {

        // append yaml syntax, more will follow...
        List<String> yamlSyntaxParameters = new ArrayList<>();
        for(String parameter: parameters) {
            yamlSyntaxParameters.add(String.format("'@%s'", parameter));
        }

        return yamlSyntaxParameters;
    }

    public interface TagCallbackInterface {
        void onTags(@NotNull List<ServiceTag> tags);
    }
}


text:
import { app, Menu } from 'electron';
import { devMenuTemplate } from './menu/dev_menu_template';
import { editMenuTemplate } from './menu/edit_menu_template';
import createWindow from './helpers/window';

// Special module holding environment variables which you declared
// in config/env_xxx.json file.
import env from './env';

var mainWindow;

var setApplicationMenu = function () {
    var menus = [editMenuTemplate];
    if (env.name !== 'production') {
        menus.push(devMenuTemplate);
    }
    Menu.setApplicationMenu(Menu.buildFromTemplate(menus));
};

// Save userData in separate folders for each environment.
// Thanks to this you can use production and development versions of the app
// on same machine like those are two separate apps.
if (env.name !== 'production') {
    var userDataPath = app.getPath('userData');
    app.setPath('userData', userDataPath + ' (' + env.name + ')');
}

app.on('ready', function () {
    setApplicationMenu();

    var mainWindow = createWindow('main', {
        width: 1000,
        height: 600
    });

    mainWindow.loadURL('file://' + __dirname + '/app.html');

    if (env.name === 'development') {
        mainWindow.openDevTools();
    }
});

app.on('window-all-closed', function () {
    app.quit();
});


text:
A number of Angular CLI commands run a complex process on your code, such as linting, building, or testing.
The commands use an internal tool called Architect to run *CLI builders*, which apply another tool to accomplish the desired task.

With Angular version 8, the CLI Builder API is stable and available to developers who want to customize the Angular CLI by adding or modifying commands. For example, you could supply a builder to perform an entirely new task, or to change which third-party tool is used by an existing command.

This document explains how CLI builders integrate with the workspace configuration file, and shows how you can create your own builder.

   You can find the code from the examples used here in [this GitHub repository](https://github.com/mgechev/cli-builders-demo).

## CLI builders

The internal Architect tool delegates work to handler functions called [*builders*](guide/glossary#builder).
A builder handler function receives two arguments; a set of input `options` (a JSON object), and a `context` (a `BuilderContext` object).

The separation of concerns here is the same as with [schematics](guide/glossary#schematic), which are used for other CLI commands that touch your code (such as `ng generate`).

* The `options` object is provided by the CLI user, while the `context` object is provided by the CLI Builder API.

* In addition to the contextual information, the `context` object, which is an instance of the `BuilderContext`, also provides access to a scheduling method, `BuilderContext.scheduleTarget()`. The scheduler executes the builder handler function with a given [target configuration](guide/glossary#target).

The builder handler function can be synchronous (return a value) or asynchronous (return a Promise), or it can watch and return multiple values (return an Observable).
The return value or values must always be of type `BuilderOutput`.
This object contains a Boolean `success` field and an optional `error` field that can contain an error message.

Angular provides some builders that are used by the CLI for commands such as `ng build`, `ng test`, and `ng lint`.
Default target configurations for these and other built-in CLI builders can be found (and customized) in the "architect" section of the [workspace configuration file](guide/workspace-config), `angular.json`.
You can also extend and customize Angular by creating your own builders, which you can run using the [`ng run` CLI command](cli/run).

### Builder project structure

A builder resides in a "project" folder that is similar in structure to an Angular workspace, with global configuration files at the top level, and more specific configuration in a source folder with the code files that define the behavior.
For example, your `myBuilder` folder could contain the following files.

| FILES    | PURPOSE |
| :----------------------- | :------------------------------------------|
| `src/my-builder.ts`      | Main source file for the builder definition. |
| `src/my-builder.spec.ts` | Source file for tests. |
| `src/schema.json`        | Definition of builder input options. |
| `builders.json`          | Builders definition. |
| `package.json`           | Dependencies. See https://docs.npmjs.com/files/package.json. |
| `tsconfig.json`          | [TypeScript configuration](https://www.typescriptlang.org/docs/handbook/tsconfig-json.html). |

You can publish the builder to `npm` (see [Publishing your Library](guide/creating-libraries#publishing-your-library)). If you publish it as `@example/my-builder`, you can install it using the following command.

npm install @example/my-builder

## Creating a builder

As an example, let's create a builder that executes a shell command.
To create a builder, use the `createBuilder()` CLI Builder function, and return a `Promise<BuilderOutput>` object.

Now let's add some logic to it.
The following code retrieves the command and arguments from the user options, spawns the new process, and waits for the process to finish.
If the process is successful (returns a code of 0), it resolves the return value.

### Handling output

By default, the `spawn()` method outputs everything to the process standard output and error.
To make it easier to test and debug, we can forward the output to the CLI Builder logger instead.
This also allows the builder itself to be executed in a separate process, even if the standard output and error are deactivated (as in an [Electron app](https://electronjs.org/)).

We can retrieve a Logger instance from the context.

### Progress and status reporting

The CLI Builder API includes progress and status reporting tools, which can provide hints for certain functions and interfaces.

To report progress, use the `BuilderContext.reportProgress()` method, which takes a current value, (optional) total, and status string as arguments.
The total can be any number; for example, if you know how many files you have to process, the total could be the number of files, and current should be the number processed so far.
The status string is unmodified unless you pass in a new string value.

You can see an [example](https://github.com/angular/angular-cli/blob/ba21c855c0c8b778005df01d4851b5a2176edc6f/packages/angular_devkit/build_angular/src/tslint/index.ts#L107) of how the `tslint` builder reports progress.

In our example, the shell command either finishes or is still executing, so there's no need for a progress report, but we can report status so that a parent builder that called our builder would know what's going on.
Use the `BuilderContext.reportStatus()` method to generate a status string of any length.
(Note that there's no guarantee that a long string will be shown entirely; it could be cut to fit the UI that displays it.)
Pass an empty string to remove the status.

## Builder input

You can invoke a builder indirectly through a CLI command, or directly with the Angular CLI `ng run` command.
In either case, you must provide required inputs, but can allow other inputs to default to values that are pre-configured for a specific [*target*](guide/glossary#target), provide a pre-defined, named override configuration, and provide further override option values on the command line.

### Input validation

You define builder inputs in a JSON schema associated with that builder.
The Architect tool collects the resolved input values into an `options` object, and validates their types against the schema before passing them to the builder function.
(The Schematics library does the same kind of validation of user input).

For our example builder, we expect the `options` value to be a `JsonObject` with two keys: a `command` that is a string, and an `args` array of string values.

We can provide the following schema for type validation of these values.

{
  "$schema": "http://json-schema.org/schema",
  "type": "object",
  "properties": {
    "command": {
      "type": "string"
    },
    "args": {
      "type": "array",
      "items": {
        "type": "string"
      }
    }
  }
}

This is a very simple example, but the use of a schema for validation can be very powerful.
For more information, see the [JSON schemas website](http://json-schema.org/).

To link our builder implementation with its schema and name, we need to create a *builder definition* file, which we can point to in `package.json`.

Create a file named `builders.json` file that looks like this.

{
  "builders": {
    "command": {
      "implementation": "./command",
      "schema": "./command/schema.json",
      "description": "Runs any command line in the operating system."
    }
  }
}

In the `package.json` file, add a `builders` key that tells the Architect tool where to find our builder definition file.

{
  "name": "@example/command-runner",
  "version": "1.0.0",
  "description": "Builder for Command Runner",
  "builders": "builders.json",
  "devDependencies": {
    "@angular-devkit/architect": "^1.0.0"
  }
}

The official name of our builder is now ` @example/command-runner:command`.
The first part of this is the package name (resolved using node resolution), and the second part is the builder name (resolved using the `builders.json` file).

Using one of our `options` is very straightforward, we did this in the previous section when we accessed `options.command`.

### Target configuration

A builder must have a defined target that associates it with a specific input configuration and [project](guide/glossary#project).

Targets are defined in the `angular.json` [CLI configuration file](guide/workspace-config).
A target specifies the builder to use, its default options configuration, and named alternative configurations.
The Architect tool uses the target definition to resolve input options for a given run.

The  `angular.json` file has a section for each project, and the "architect" section of each project configures targets for builders used by CLI commands such as 'build', 'test', and 'lint'.
By default, for example, the `build` command runs the builder  `@angular-devkit/build-angular:browser` to perform the build task, and passes in default option values as specified for the `build` target in   `angular.json`.

{
  "myApp": {
    ...
    "architect": {
      "build": {
        "builder": "@angular-devkit/build-angular:browser",
        "options": {
          "outputPath": "dist/myApp",
          "index": "src/index.html",
          ...
        },
        "configurations": {
          "production": {
            "fileReplacements": [
              {
                "replace": "src/environments/environment.ts",
                "with": "src/environments/environment.prod.ts"
              }
            ],
            "optimization": true,
            "outputHashing": "all",
            ...
          }
        }
      },
      ...

The command passes the builder the set of default options specified in the "options" section.
If you pass the `--configuration=production` flag, it uses the override values specified in the `production` alternative configuration.
You can specify further option overrides individually on the command line.
You might also add more alternative configurations to the `build` target, to define other environments such as `stage` or `qa`.

#### Target strings

The generic `ng run` CLI command takes as its first argument a target string of the form *project:target[:configuration]*.

* *project*: The name of the Angular CLI project that the target is associated with.

* *target*: A named builder configuration from the `architect` section of the `angular.json` file.

* *configuration*: (optional) The name of a specific configuration override for the given target, as defined in the `angular.json` file.

If your builder calls another builder, it may need to read a passed target string.
You can parse this string into an object by using the `targetFromTargetString()` utility function from `@angular-devkit/architect`.

## Schedule and run

Architect runs builders asynchronously.
To invoke a builder, you schedule a task to be run when all configuration resolution is complete.

The builder function is not executed until the scheduler returns a `BuilderRun` control object.
The CLI typically schedules tasks by calling the `BuilderContext.scheduleTarget()` function, and then resolves input options using the target definition in the `angular.json` file.

Architect resolves input options for a given target by taking the default options object, then overwriting values from the configuration used (if any), then further overwriting values from the overrides object passed to `BuilderContext.scheduleTarget()`.
For the Angular CLI, the overrides object is built from command line arguments.

Architect validates the resulting options values against the schema of the builder.
If inputs are valid, Architect creates the context and executes the builder.

For more information see [Workspace Configuration](guide/workspace-config).

   You can also invoke a builder directly from another builder or test by calling `BuilderContext.scheduleBuilder()`.
   You pass an `options` object directly to the method, and those option values are validated against the schema of the builder without further adjustment.

   Only the  `BuilderContext.scheduleTarget()` method resolves the configuration and overrides through the `angular.json` file.

### Default architect configuration

Let's create a simple `angular.json` file that puts target configurations into context.

We can publish the builder to npm (see [Publishing your Library](guide/creating-libraries#publishing-your-library)), and install it using the following command:

npm install @example/command-runner

If we create a new project with `ng new builder-test`, the generated `angular.json` file looks something like this, with only default builder configurations.

{
  // ...
  "projects": {
    // ...
    "builder-test": {
      // ...
      "architect": {
        // ...
        "build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
            // ... more options...
            "outputPath": "dist/builder-test",
            "index": "src/index.html",
            "main": "src/main.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "src/tsconfig.app.json"
          },
          "configurations": {
            "production": {
              // ... more options...
              "optimization": true,
              "aot": true,
              "buildOptimizer": true
            }
          }
        }
      }
    }
  }
  // ...
}

### Adding a target

Let's add a new target that will run our builder to execute a particular command.
This target will tell the builder to run `touch` on a file, in order to update its modified date.

We need to update the `angular.json` file to add a target for this builder to the "architect" section of our new project.

* We'll add a new target section to the "architect" object for our project.

* The target named "touch" uses our builder, which we published to `@example/command-runner`. (See [Publishing your Library](guide/creating-libraries#publishing-your-library))

* The options object provides default values for the two inputs that we defined; `command`, which is the Unix command to execute, and `args`, an array that contains the file to operate on.

* The configurations key is optional, we'll leave it out for now.

{
  "projects": {
    "builder-test": {
      "architect": {
        "touch": {
          "builder": "@example/command-runner:command",
          "options": {
            "command": "touch",
            "args": [
              "src/main.ts"
            ]
          }
        },
        "build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
            "outputPath": "dist/builder-test",
            "index": "src/index.html",
            "main": "src/main.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "src/tsconfig.app.json"
          },
          "configurations": {
            "production": {
              "fileReplacements": [
                {
                  "replace": "src/environments/environment.ts",
                  "with": "src/environments/environment.prod.ts"
                }
              ],
              "optimization": true,
              "aot": true,
              "buildOptimizer": true
            }
          }
        }
      }
    }
  }
}

### Running the builder

To run our builder with the new target's default configuration, use the following CLI command in a Linux shell.

   ng run builder-test:touch

This will run the `touch` command on the `src/main.ts` file.

You can use command-line arguments to override the configured defaults.
For example, to run with a different `command` value, use the following CLI command.

ng run builder-test:touch --command=ls

This will call the `ls` command instead of the `touch` command.
Because we did not override the *args* option, it will list information about the `src/main.ts` file (the default value provided for the target).

## Testing a builder

Use integration testing for your builder, so that you can use the Architect scheduler to create a context, as in this [example](https://github.com/mgechev/cli-builders-demo).

* In the builder source directory, we have created a new test file `my-builder.spec.ts`. The code creates new instances of `JsonSchemaRegistry` (for schema validation), `TestingArchitectHost` (an in-memory implementation of `ArchitectHost`), and `Architect`.

* We've added a `builders.json` file next to the builder's [`package.json` file](https://github.com/mgechev/cli-builders-demo/blob/master/command-builder/builders.json), and modified the package file to point to it.

Here's an example of a test that runs the command builder.
The test uses the builder to run the `node --print 'foo'` command, then validates that the `logger` contains an entry for `foo`.

   When running this test in your repo, you need the [`ts-node`](https://github.com/TypeStrong/ts-node) package. You can avoid this by renaming `my-builder.spec.ts` to `my-builder.spec.js`.

### Watch mode

Architect expects builders to run once (by default) and return.
This behavior is not entirely compatible with a builder that watches for changes (like Webpack, for example).
Architect can support watch mode, but there are some things to look out for.

* To be used with watch mode, a builder handler function should return an Observable. Architect subscribes to the Observable until it completes and might reuse it if the builder is scheduled again with the same arguments.

* The builder should always emit a `BuilderOutput` object after each execution. Once it's been executed, it can enter a watch mode, to be triggered by an external event. If an event triggers it to restart, the builder should execute the `BuilderContext.reportRunning()` function to tell Architect that it is running again. This prevents Architect from stopping the builder if another run is scheduled.

When your builder calls `BuilderRun.stop()` to exit watch mode, Architect unsubscribes from the builder's Observable and calls the builder's teardown logic to clean up.
(This behavior also allows for long running builds to be stopped and cleaned up.)

In general, if your builder is watching an external event, you should separate your run into three phases.

1. **Running**
   For example, webpack compiles. This ends when webpack finishes and your builder emits a `BuilderOutput` object.

1. **Watching**
   Between two runs, watch an external event stream. For example, webpack watches the file system for any changes. This ends when webpack restarts building, and `BuilderContext.reportRunning()` is called. This goes back to step 1.

1. **Completion**
   Either the task is fully completed (for example, webpack was supposed to run a number of times), or the builder run was stopped (using `BuilderRun.stop()`). Your teardown logic is executed, and Architect unsubscribes from your builder's Observable.

## Summary

The CLI Builder API provides a new way of changing the behavior of the Angular CLI by using builders to execute custom logic.

* Builders can be synchronous or asynchronous, execute once or watch for external events, and can schedule other builders or targets.

* Builders have option defaults specified in the `angular.json` configuration file, which can be overwritten by an alternate configuration for the target, and further overwritten by command line flags.

* We recommend that you use integration tests to test Architect builders. You can use unit tests to validate the logic that the builder executes.

* If your builder returns an Observable, it should clean up in the teardown logic of that Observable.


text:
package design

import (
	"os"

	. "app/design/constant"
	_ "app/design/resource"

	"app/design/media"

	. "github.com/goadesign/goa/design"
	. "github.com/goadesign/goa/design/apidsl"
)

var _ = API(REPO, func() {
	Host(func() string {
		switch os.Getenv("Op") {
		case "develop":
			return "localhost:8080"
		case "production":
			return "misoten-lovechan.appspot.com"
		}
		return "localhost:8080"
	}())
	Scheme(func() string {
		switch os.Getenv("Op") {
		case "develop":
			return "http"
		case "production":
			return "https"
		}
		return "http"
	}())
	BasePath("/")
	Trait(GeneralUserTrait, func() {
		Response(Accepted, media.RoutingType)
		Response(NoContent)
		Response(Unauthorized, ErrorMedia)
		Response(NotFound)
		Response(BadRequest, ErrorMedia)
		Response(InternalServerError, ErrorMedia)
	})
})


text:
package de.cau.cs.kieler.klay.layered.properties;

/**
 * Describes what interactive layout phases should take as reference point for comparison
 * of node positions.
 *
 * @author cds
 * @kieler.design proposed by msp
 * @kieler.rating proposed yellow by msp
 */
public enum InteractiveReferencePoint {

    /** the node's center point. */
    CENTER,
    /** the node's top left corner. */
    TOP_LEFT;

}


text:
class AddLevelsToUsers < ActiveRecord::Migration
  def change
  	add_column :users, :level, :integer
  end
end


text:
function mean(myArray)
{
	var runningSum = 0;

	for(var i = 0; i < myArray.length; i++)
	{
		runningSum = runningSum + myArray[i];
		/* Alternate */
		//runningSum += myArray[i];
	}

	return runningSum / myArray.length;
}

var numArray = [5,10,15,20];

console.log(mean(numArray));


text:
module RSpec
  module Mocks
    # @private
    class MethodDouble < Hash
      # @private
      attr_reader :method_name

      # @private
      def initialize(object, method_name, proxy)
        @method_name = method_name
        @object = object
        @proxy = proxy
        @stashed = false
        store(:expectations, [])
        store(:stubs, [])
      end

      # @private
      def expectations
        self[:expectations]
      end

      # @private
      def stubs
        self[:stubs]
      end

      # @private
      def visibility
        if Mock === @object
          'public'
        elsif object_singleton_class.private_method_defined?(@method_name)
          'private'
        elsif object_singleton_class.protected_method_defined?(@method_name)
          'protected'
        else
          'public'
        end
      end

      # @private
      def object_singleton_class
        class << @object; self; end
      end

      # @private
      def obfuscate(method_name)
        "obfuscated_by_rspec_mocks__#{method_name}"
      end

      # @private
      def stashed_method_name
        obfuscate(method_name)
      end

      # @private
      def object_responds_to?(method_name)
        if @proxy.already_proxied_respond_to?
          @object.__send__(obfuscate(:respond_to?), method_name)
        elsif method_name == :respond_to?
          @proxy.already_proxied_respond_to
        else
          @object.respond_to?(method_name, true)
        end
      end

      # @private
      def configure_method
        RSpec::Mocks::space.add(@object) if RSpec::Mocks::space
        warn_if_nil_class
        unless @stashed
          stash_original_method
          define_proxy_method
        end
      end

      # @private
      def stash_original_method
        stashed = stashed_method_name
        orig = @method_name
        object_singleton_class.class_eval do
          alias_method(stashed, orig) if method_defined?(orig) || private_method_defined?(orig)
        end
        @stashed = true
      end

      # @private
      def define_proxy_method
        method_name = @method_name
        visibility_for_method = "#{visibility} :#{method_name}"
        object_singleton_class.class_eval(<<-EOF, __FILE__, __LINE__)
          def #{method_name}(*args, &block)
            __mock_proxy.message_received :#{method_name}, *args, &block
          end
        #{visibility_for_method}
        EOF
      end

      # @private
      def restore_original_method
        if @stashed
          method_name = @method_name
          stashed_method_name = self.stashed_method_name
          object_singleton_class.instance_eval do
            remove_method method_name
            if method_defined?(stashed_method_name) || private_method_defined?(stashed_method_name)
              alias_method method_name, stashed_method_name
              remove_method stashed_method_name
            end
          end
          @stashed = false
        end
      end

      # @private
      def verify
        expectations.each {|e| e.verify_messages_received}
      end

      # @private
      def reset
        reset_nil_expectations_warning
        restore_original_method
        clear
      end

      # @private
      def clear
        expectations.clear
        stubs.clear
      end

      # @private
      def add_expectation(error_generator, expectation_ordering, expected_from, opts, &block)
        configure_method
        expectation = if existing_stub = stubs.first
                        existing_stub.build_child(expected_from, block, 1, opts)
                      else
                        MessageExpectation.new(error_generator, expectation_ordering, expected_from, @method_name, block, 1, opts)
                      end
        expectations << expectation
        expectation
      end

      # @private
      def add_negative_expectation(error_generator, expectation_ordering, expected_from, &implementation)
        configure_method
        expectation = NegativeMessageExpectation.new(error_generator, expectation_ordering, expected_from, @method_name, implementation)
        expectations.unshift expectation
        expectation
      end

      # @private
      def add_stub(error_generator, expectation_ordering, expected_from, opts={}, &implementation)
        configure_method
        stub = MessageExpectation.new(error_generator, expectation_ordering, expected_from, @method_name, nil, :any, opts, &implementation)
        stubs.unshift stub
        stub
      end

      # @private
      def remove_stub
        raise_method_not_stubbed_error if stubs.empty?
        expectations.empty? ? reset : stubs.clear
      end

      # @private
      def proxy_for_nil_class?
        @object.nil?
      end

      # @private
      def warn_if_nil_class
        if proxy_for_nil_class? & RSpec::Mocks::Proxy.warn_about_expectations_on_nil
          Kernel.warn("An expectation of :#{@method_name} was set on nil. Called from #{caller[4]}. Use allow_message_expectations_on_nil to disable warnings.")
        end
      end

      # @private
      def raise_method_not_stubbed_error
        raise MockExpectationError, "The method `#{method_name}` was not stubbed or was already unstubbed"
      end

      # @private
      def reset_nil_expectations_warning
        RSpec::Mocks::Proxy.warn_about_expectations_on_nil = true if proxy_for_nil_class?
      end
    end
  end
end


text:
package jp.co.thcomp.util;

import android.content.Intent;
import android.net.Uri;

import java.io.File;

public class IntentUtil {
    public static Intent getLaunchMailerIntent(String toAddress, String title, String message){
        Intent intent = new Intent();

        if(!toAddress.startsWith("mailto:")){
            toAddress = "mailto:" + toAddress;
        }

        intent.putExtra(Intent.EXTRA_EMAIL, "mailto:");
        intent.setData(Uri.parse(toAddress));
        intent.setAction(Intent.ACTION_SENDTO);
        intent.putExtra(Intent.EXTRA_SUBJECT, title);
        intent.putExtra(Intent.EXTRA_TEXT, message);

        return intent;
    }

    public static Intent getLaunchMailerIntent(String toAddress, String title, String message, String attachmentFilePath){
        return getLaunchMailerIntent(toAddress, title, message, new File(attachmentFilePath));
    }

    public static Intent getLaunchMailerIntent(String toAddress, String title, String message, File attachmentFile){
        return getLaunchMailerIntent(toAddress, title, message, Uri.fromFile(attachmentFile));
    }

    public static Intent getLaunchMailerIntent(String toAddress, String title, String message, Uri attachmentFileUri){
        Intent intent = getLaunchMailerIntent(toAddress, title, message);
        intent.putExtra(Intent.EXTRA_STREAM, attachmentFileUri);
        return intent;
    }
}


text:
package uk.co.yottr.validator;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import uk.co.yottr.model.User;
import uk.co.yottr.repository.UserRepository;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

@Component
public class UsernameAvailableValidator implements ConstraintValidator<UsernameAvailable, String> {

    @Autowired
    private UserRepository userRepository;

    @Override
    public void initialize(UsernameAvailable param) {
    }

    @Override
    public boolean isValid(String username, ConstraintValidatorContext ctx) {

        if (userRepository == null) {
            return true;
        }

        final User user = userRepository.findByUsername(username);
        return user == null;
    }
}