text:
/**
 * This example demonstrates use of Ext.form.field.File, a file upload field with custom
 * rendering, and error handling.
 */
Ext.define('KitchenSink.view.form.FileUploads', {
    extend: 'Ext.container.Container',
    xtype: 'form-fileuploads',
    controller: 'form-fileuploads',

    //<example>
    requires: [
        'KitchenSink.view.form.FileUploadsController'
    ],

    exampleTitle: 'File Upload fields',
    otherContent: [{
        type: 'ViewController',
        path: 'app/view/form/FileUploadsController.js'
    }],
    //</example>

    width: 600,
    layout: {
        type: 'vbox',
        align: 'stretch'
    },

    defaults: {
        xtype: 'form',
        layout: 'anchor',

        bodyPadding: 10,
        style: {
            'margin-bottom': '20px'
        },

        defaults: {
            anchor: '100%'
        }
    },

    items: [{
        items: [{
            xtype: 'component',
            html: [
                '
Basic File Field
',
                '
A typical file upload field with Ext style. Direct editing ',
                'of the text field cannot be done in a consistent, cross-browser way, ',
                'so it is always read-only. The file path reported by the ',
                'getValue method will depend on the browser and cannot ',
                'be controlled by Ext JS.'
            ]
        }, {
            xtype: 'filefield',
            hideLabel: true,
            reference: 'basicFile'
        }, {
            xtype: 'button',
            text: 'Get File Path',
            handler: 'getFilePath'
        }]
    }, {
        items: [{
            xtype: 'component',
            html: [
                '
Button Only
',
                '
You can also render the file input as a button without ',
                'the text field, with access to the field\'s value via the ',
                'standard <tt>Ext.form.field.Field</tt> interface or by handling ',
                'the <tt>change</tt> event (as in this example).',
                '
'
            ]
        }, {
            xtype: 'fileuploadfield', // Same as filefield above
            buttonOnly: true,
            hideLabel: true,
            listeners: {
                change: 'buttonOnlyChange'
            }
        }]
    }, {
        title: 'File Upload Form',
        frame: true,
        bodyPadding: '10 10 0',
        reference: 'firstForm',

        defaults: {
            anchor: '100%',
            allowBlank: false,
            msgTarget: 'side',
            labelWidth: 50
        },

        items: [{
            xtype: 'textfield',
            fieldLabel: 'Name'
        }, {
            xtype: 'filefield',
            emptyText: 'Select an image',
            fieldLabel: 'Photo',
            name: 'photo-path',
            buttonText: '',
            buttonConfig: {
                iconCls: 'upload-icon'
            }
        }],

        buttons: [{
            text: 'Save',
            handler: 'firstFormSave'
        }, {
            text: 'Reset',
            handler: 'firstFormReset'
        }]
    }, {
        title: 'Upload error test',
        frame: true,
        bodyPadding: '10 10 0',
        reference: 'secondForm',

        defaults: {
            anchor: '100%',
            allowBlank: false,
            msgTarget: 'side',
            labelWidth: 70
        },

        items: [{
            xtype: 'textfield',
            fieldLabel: 'Name'
        }, {
            xtype: 'filefield',
            emptyText: 'Select an image',
            fieldLabel: 'Photo',
            name: 'photo-path',
            buttonConfig: {
                text : '',
                iconCls: 'upload-icon'
            }
        }, {
            xtype: 'numberfield',
            fieldLabel: 'HTTP status',
            value: 200,
            minValue: 200,
            maxValue: 599,
            name: 'returnResponse'
        }],

        buttons: [{
            text: 'Save',
            handler: 'secondFormSubmit'
        }, {
            text: 'Reset',
            handler: 'secondFormReset'
        }]
    }]
});


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE114_Process_Control__w32_char_console_84.h
Label Definition File: CWE114_Process_Control__w32.label.xml
Template File: sources-sink-84.tmpl.h
*/
/*
 * @description
 * CWE: 114 Process Control
 * BadSource: console Read input from the console
 * GoodSource: Hard code the full pathname to the library
 * Sinks:
 *    BadSink : Load a dynamic link library
 * Flow Variant: 84 Data flow: data passed to class constructor and destructor by declaring the class object on the heap and deleting it after use
 *
 * */

#include "std_testcase.h"

#include <wchar.h>

namespace CWE114_Process_Control__w32_char_console_84
{

#ifndef OMITBAD

class CWE114_Process_Control__w32_char_console_84_bad
{
public:
    CWE114_Process_Control__w32_char_console_84_bad(char * dataCopy);
    ~CWE114_Process_Control__w32_char_console_84_bad();

private:
    char * data;
};

#endif /* OMITBAD */

#ifndef OMITGOOD

class CWE114_Process_Control__w32_char_console_84_goodG2B
{
public:
    CWE114_Process_Control__w32_char_console_84_goodG2B(char * dataCopy);
    ~CWE114_Process_Control__w32_char_console_84_goodG2B();

private:
    char * data;
};

#endif /* OMITGOOD */

}

redpajama_set_name: RedPajamaGithub


text:
import { TestBed } from '@angular/core/testing';
import { Component, ViewChild } from '@angular/core';
import * as Infragistics from '../../../dist/npm/igniteui.angular2';

export function main() {
    describe('Infragistics Angular2 Popover', () => {

        beforeEach(() => {
            TestBed.configureTestingModule({
                declarations: [ Infragistics.IgPopoverComponent, TestComponent]
            });
        });

        it('should initialize correctly', (done) => {
            var template = '
<ig-popover [widgetId]="\'popover\'" [(options)]="opts"></ig-popover>
';
            TestBed.overrideComponent(TestComponent, {
                set: {
                    template: template
                }
            });
            TestBed.compileComponents().then(() => {
                let fixture = TestBed.createComponent(TestComponent);
                fixture.detectChanges();
                expect(fixture.debugElement.componentInstance.viewChild instanceof Infragistics.IgPopoverComponent)
                    .toBe(true);
                done();
            });
        });

        it('should initialize correctly when having a target element', (done) => {
            var template = '
<ig-popover [widgetId]="\'popover\'" [(options)]="opts"></ig-popover><input id="popover"/>
';
            TestBed.overrideComponent(TestComponent, {
                set: {
                    template: template
                }
            });
            TestBed.compileComponents().then(() => {
                let fixture = TestBed.createComponent(TestComponent);
                fixture.detectChanges();
                expect(fixture.debugElement.componentInstance.viewChild instanceof Infragistics.IgPopoverComponent)
                    .toBe(true);
                done();
            });
        });

    });
}

@Component({
    selector: 'test-cmp',
    template: '

' //"Component 'TestComponent' must have either 'template' or 'templateUrl' set."
})
class TestComponent {
    private opts: any;

    @ViewChild(Infragistics.IgPopoverComponent) public viewChild: Infragistics.IgPopoverComponent;

    constructor() {
        this.opts = {
            contentTemplate: "
Test Content
"
        };
    }
}


text:
"""FitLab

Usage:
	fitlab.py (login | logout) <username>
	fitlab.py (-h | --help)
	fitlab.py --version
	fitlab.py csv (sleep | activity | calories) [-hvo FILE]

Options:
	-h --help 			show this help file
	--version 			show version
	-v --verbose		show more text during execution
	-o --output FILE 	specify output file [default: ./fitbit.csv]

"""

from docopt import docopt

if __name__ == '__main__':
    arguments = docopt(__doc__, version='FitLab 0.1')
    print(arguments)


text:
References:

*   [Code](https://github.com/huggingface/datasets/blob/master/datasets/ro_sts)
*   [Huggingface](https://huggingface.co/datasets/ro_sts)

## ro_sts

Use the following command to load this dataset in TFDS:

```python
ds = tfds.load('huggingface:ro_sts/ro_sts')
```

*   **Description**:

```
The RO-STS (Romanian Semantic Textual Similarity) dataset contains 8628 pairs of sentences with their similarity score. It is a high-quality translation of the STS benchmark dataset.
```

*   **License**: CC BY-SA 4.0 License
*   **Version**: 1.0.0
*   **Splits**:

Split  | Examples
:----- | -------:
`'test'` | 1379
`'train'` | 5749
`'validation'` | 1500

*   **Features**:

```json
{
    "score": {
        "dtype": "float32",
        "id": null,
        "_type": "Value"
    },
    "sentence1": {
        "dtype": "string",
        "id": null,
        "_type": "Value"
    },
    "sentence2": {
        "dtype": "string",
        "id": null,
        "_type": "Value"
    }
}
```


text:
\documentclass[nofootinbib,amssymb,amsmath]{revtex4}
\usepackage{mathtools}
\usepackage{amsthm}
\usepackage{algorithm}
\usepackage{algpseudocode}
\usepackage{lmodern}
\usepackage{graphicx}
\usepackage{color}
\usepackage{bm}

%Put an averaged random variable between brackets
\newcommand{\ave}[1]{\left\langle #1 \right\rangle}

\newcommand{\vzero}{{\bf 0}}
\newcommand{\vI}{{\bf I}}
\newcommand{\vb}{{\bf b}}
\newcommand{\vd}{{\bf d}}
\newcommand{\vf}{{\bf f}}
\newcommand{\vc}{{\bf c}}
\newcommand{\vv}{{\bf v}}
\newcommand{\vz}{{\bf z}}
\newcommand{\vn}{{\bf n}}
\newcommand{\vm}{{\bf m}}
\newcommand{\vG}{{\bf G}}
\newcommand{\vQ}{{\bf Q}}
\newcommand{\vM}{{\bf M}}
\newcommand{\vW}{{\bf W}}
\newcommand{\vX}{{\bf X}}
\newcommand{\vPsi}{{\bf \Psi}}
\newcommand{\vSigma}{{\bf \Sigma}}
\newcommand{\vlambda}{{\bf \lambda}}
\newcommand{\vpi}{{\bf \pi}}
\newcommand{\valpha}{{\bm{\alpha}}}
\newcommand{\vbeta}{{\bm{\beta}}}
\newcommand{\vomega}{{\bm{\omega}}}
\newcommand{\vLambda}{{\bf \Lambda}}
\newcommand{\vA}{{\bf A}}

\newcommand{\code}[1]{\texttt{#1}}

\newtheorem{lemma}{Lemma}
\newtheorem{corollary}{Corollary}

\def\SL#1{{\color [rgb]{0,0,0.8} [SL: #1]}}
\def\DB#1{{\color [rgb]{0,0.8,0} [DB: #1]}}

\newcommand{\HOM}{$\mathsf{Hom}$}
\newcommand{\HET}{$\mathsf{Het}$}
\newcommand{\REF}{$\mathsf{Ref}$}
\newcommand{\epss}{\varepsilon}

\begin{document}

\title{Mathematical Notes on Mutect}
\author{David Benjamin}
\email{davidben@broadinstitute.org}
\affiliation{Broad Institute, 75 Ames Street, Cambridge, MA 02142}

\date{\today}

\maketitle

\section{Introduction}\label{introduction}

We have a set of potential somatic alleles and read-allele likelihoods $\ell_{ra} \equiv P({\rm read~}r|{\rm allele~}a)$.  We don't know which alleles are real somatic alleles and so we must compute, for each subset $\mathbb{A}$ of alleles, the likelihood that the reads come from $\mathbb{A}$.  A simple model for this likelihood is as follows: each read $r$ is associated with a latent indicator vector $\vz_r$ with one-hot encoding $z_{ra} = 1$ iff read $r$ came from allele $a \in \mathbb{A}$.  The conditional probability of the reads $\mathbb{R}$ given their allele assignments is
\begin{equation}
P( \mathbb{R} | \vz, \mathbb{A}) = \prod_{r \in \mathbb{R}} \prod_a \ell_{ra}^{z_{ra}}.
\end{equation}
The alleles are not equally likely because there is a latent vector $\vf$ of allele fractions -- $f_a$ is the allele fraction of allele $a$.  Since the components of $\vf$ sum to one it is a categorical distribution and can be given a Dirichlet prior,
\begin{equation}
P(\vf) = {\rm Dir}(\vf | \valpha).
\end{equation}
Then $f_a$ is the prior probability that a read comes from allele $a$ and thus the conditional probability of the indicators $\vz$ given the allele fractions $\vf$ is
\begin{equation}
P(\vz | \vf) = \prod_r \prod_a f_a^{z_{ra}}.
\end{equation}
The full-model likelihood is therefore
\begin{equation}
\mathbb{L}(\mathbb{A}) = P(\mathbb{R}, \vz, \vf | \mathbb{A}) = {\rm Dir}(\vf | \valpha) \prod_a  \prod_r \left( f_a \ell_{ra}\right)^{z_{ra}}.
\label{full_likelihood}
\end{equation}
And the marginalized likelihood of $\mathbb{A}$, that is, the model evidence for allele subset $\mathbb{A}$, is
\begin{equation}
P(\mathbb{R} | \mathbb{A}) = \sum_\vz \int d \vf \, {\rm Dir}(\vf | \valpha) \prod_a  \prod_r \left( f_a \ell_{ra}\right)^{z_{ra}},
\label{evidence}
\end{equation}
where the integral is over the probability simplex $\sum_a f_a = 1$.

The integral over $\vf$ is the normalization constant of a Dirichlet distribution and as such we can simply look up its formula.  However, the sum over all values of $\vz$ for all reads has exponentially many terms.  We will get around this difficulty by handling $\vz$ with a mean-field approximation in which we factorize the likelihood as $\mathbb{L} \approx q(\vz) q(\vf)$.  This approximation is exact in two limits: first, if there are many reads, each allele is associated with many reads and therefore the Law of Large Numbers causes $\vf$ and $\vz$ to become uncorrelated.  Second, if the allele assignments of reads are obvious $\vz_r$ is effectively not a random variable at all (there is no uncertainty as to which of component is non-zero) and also becomes uncorrelated with $\vf$.

In the variational Bayesian mean-field formalism the value of $\vf$ that $\vz$ ``sees'' is the expectation of $\log \mathbb{L}$ with respect to $q(\vf)$ and vice versa.  That is,
\begin{equation}
q(\vf) \propto {\rm Dir}(\vf | \valpha) \prod_a  \prod_r f_a^{\bar{z}_{ra}} \propto {\rm Dir}(\vf | \valpha + \sum_r \bar{\vz}_r),
\label{qf}
\end{equation}
where $\bar{z}_{ra} \equiv E_q \left[ z_{ra} \right]$, and
\begin{equation}
q(\vz_r) = \prod_a \left( \tilde{f}_a \ell_{ra}\right)^{z_{ra}}, \tilde{f}_a = \exp E[\ln f_a]
\end{equation}
Because $q(\vz)$ is categorical and $q(\vf)$ is Dirichlet\footnote{Note that we didn't \textit{impose} this in any way.  It simply falls out of the mean field equations.} the necessary mean fields are easily obtained and we have
\begin{equation}
\bar{z}_{ra} = \frac{\tilde{f}_a \ell_{ra}}{\sum_{a^\prime} \tilde{f}_{a^\prime} \ell_{ra^\prime}}
\label{z_mean_field}
\end{equation}
and
\begin{equation}
\ln \tilde{f}_a = \psi(\alpha_a + \sum_r \bar{z}_{ra}) - \psi(\sum_{a^\prime} \alpha_{a^\prime} + N)
\label{f_mean_field}
\end{equation}
where $\psi$ is the digamma function and $N$ is the number of reads.  To obtain $q(\vz)$ and $q(\vf)$ we iterate Equations \ref{z_mean_field} and \ref{f_mean_field} until convergence.  A very reasonable initialization is to set $\bar{z}_{ra} = 1$ if $a$ is the most likely allele for read $r$, 0 otherwise.  Having obtained the mean field of $\vz$, we would like to plug it into Eq \ref{evidence}.  We can't do this directly, of course, because Eq \ref{evidence} says nothing about our mean field factorization.  Rather, we need the variational approximation (Bishop's Eq 10.3) to the model evidence, which is
\begin{align}
\ln P(\mathbb{R} | \mathbb{A}) \approx& \sum_{\vz} \int d \vf q(\vz) q(\vf) \left[ \ln P(\mathbb{R}, \vz, \vf | \mathbb{A}) - \ln q(\vz) - \ln q(\vf) \right] \\
=& E_q \left[ \ln P(\mathbb{R}, \vz, \vf | \mathbb{A}) \right] - E_q \left[ \ln q(\vz) \right] - E_q \left[ \ln q(\vf) \right]. \label{lagrangian}
\end{align}
Before we proceed, let's introduce some notation.  First, from Eq \ref{qf} the posterior $q(\vf)$ is
\begin{equation}
q(\vf) = {\rm Dir}(\vf | \vbeta), \quad \vbeta = \valpha + \sum_r \bar{\vz}_r.
\end{equation}
Second, let's define the log normalization constant of a Dirichlet distribution as $g$ so that
\begin{equation}
\ln {\rm Dir}(\vf | \vomega) = g(\vomega) + \sum_a (\omega_a - 1) \ln f_a, \quad g(\vomega) = \ln \Gamma(\sum_a \omega_a) - \sum_a \ln \Gamma(\omega_a).
\end{equation}
Finally, define the Dirichlet mean log (aka ``that digamma stuff") as $h$:
\begin{equation}
E_{\rm Dir(\vf | \vomega)} \left[ \ln f_a \right] = \psi(\omega_a) - \psi(\sum_{a^\prime} \omega_{a^\prime}) \equiv h_a(\vomega).
\end{equation}

The log of Eq \ref{full_likelihood} is
\begin{equation}
\ln P(\mathbb{R}, \vz, \vf | \mathbb{A}) = g(\valpha) + \sum_a (\alpha_a - 1) \ln f_a + \sum_{ra} z_{ra} (\ln f_a + \ln \ell_{ra}).
\end{equation}
and thus the first term in Eq \ref{lagrangian} is
\begin{align}
E_q \left[ \ln P(\mathbb{R}, \vz, \vf | \mathbb{A}) \right] =& g(\valpha) + \sum_a (\alpha_a - 1) h_a(\vbeta) + \sum_{ra}\bar{z}_{ra} \left( h_a(\vbeta) + \ln \ell_{ra} \right) \\
=& g(\valpha) + \sum_a (\beta_a - 1) h_a(\vbeta) + \sum_{ra}\bar{z}_{ra} \ln \ell_{ra}, \label{first_term}
\end{align}
where we used the relationship $\vbeta = \valpha + \sum_r \bar{\vz}_r$.

The second term in Eq \ref{lagrangian} is
\begin{align}
- E_q \left[ \ln q(\vz) \right] = - \sum_{ra} \bar{z}_{ra} \ln \bar{z}_{ra} \label{second_term}.
\end{align}

The third term in Eq \ref{lagrangian} is
\begin{align}
- E_q \left[ \ln q(\vf) \right] = -g(\vbeta) - \sum_a (\beta_a - 1) E_q [\ln f_a] = -g(\vbeta) - \sum_a (\beta_a - 1) h_a(\vbeta) \label{third_term}.
\end{align}

Adding Eqs \ref{first_term}, \ref{second_term}, and \ref{third_term} and noting the cancellation between parts of Eqs \ref{first_term} and \ref{third_term} we obtain
\begin{equation}
\ln P(\mathbb{R} | \mathbb{A}) \approx g(\valpha) - g(\vbeta) +  \sum_{ra} \bar{z}_{ra} \left( \ln \ell_{ra} - \ln \bar{z}_{ra} \right).
\end{equation}

We now have the model evidence for allele subset $\mathbb{A}$.  This lets us choose which alleles are true somatic variants.  It also lets us make calls on somatic loss of heterozygosity events.  Furthermore, instead of reporting max-likelihood allele fractions as before, we may emit the parameters of the Dirichlet posterior $q(\vf)$, which encode both the maximum likelihood allele fractions and their uncertainty.

\end{document}


text:
module PlanningDeGarde
  class City
    include Virtus.model

    attribute :name, String

  end
end


text:
package com.adobe.air;

import android.content.Intent;
import android.content.res.Configuration;
import android.util.Log;

import com.adobe.air.AndroidActivityWrapper.ActivityState;
import com.u8.sdk.U8SDK;

/***
 * 由于AndroidActivityWrapper类的可见度限制,需要将这个类,放在com.adobe.air包名下,不要改包名
 *
 * @author xiaohei
 *
 */
public class U8CallbackWrapper implements AndroidActivityWrapper.ActivityResultCallback, AndroidActivityWrapper.StateChangeCallback{

	private AndroidActivityWrapper aaw;

	public U8CallbackWrapper(){

	}

	public void init(){
	    aaw = AndroidActivityWrapper.GetAndroidActivityWrapper();
        aaw.addActivityResultListener( this );
        aaw.addActivityStateChangeListner( this );
	}

	public void destroy(){
        if (aaw!=null) {
            aaw.removeActivityResultListener( this );
            aaw.removeActivityStateChangeListner( this );
            aaw = null;
        }
	}

	@Override
	public void onActivityStateChanged(ActivityState state) {
		Log.d("U8SDK_ANE", "onActivityStateChanged called. state:"+state);
		switch(state){
		case STARTED:
			U8SDK.getInstance().onStart();
			break;
		case RESTARTED:
			U8SDK.getInstance().onRestart();
			break;
		case RESUMED:
			U8SDK.getInstance().onResume();
			break;
		case PAUSED:
			U8SDK.getInstance().onResume();
			break;
		case STOPPED:
			U8SDK.getInstance().onStop();
			break;
		case DESTROYED:
			U8SDK.getInstance().onDestroy();
			break;
		}
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		Log.d("U8SDK_ANE", "onConfigurationChanged called. ");
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		Log.d("U8SDK_ANE", "onActivityResult called. ");
		U8SDK.getInstance().onActivityResult(requestCode, resultCode, data);
	}

}


text:
import _ from 'lodash'
import { Graph } from 'graphlibrary'

import util from '../util'

/*
 * This module provides coordinate assignment based on Brandes and Köpf, "Fast
 * and Simple Horizontal Coordinate Assignment."
 */

/*
 * Marks all edges in the graph with a type-1 conflict with the "type1Conflict"
 * property. A type-1 conflict is one where a non-inner segment crosses an
 * inner segment. An inner segment is an edge with both incident nodes marked
 * with the "dummy" property.
 *
 * This algorithm scans layer by layer, starting with the second, for type-1
 * conflicts between the current layer and the previous layer. For each layer
 * it scans the nodes from left to right until it reaches one that is incident
 * on an inner segment. It then scans predecessors to determine if they have
 * edges that cross that inner segment. At the end a final scan is done for all
 * nodes on the current rank to see if they cross the last visited inner
 * segment.
 *
 * This algorithm (safely) assumes that a dummy node will only be incident on a
 * single node in the layers being scanned.
 */
function findType1Conflicts (g, layering) {
  const conflicts = {}

  function visitLayer (prevLayer, layer) {
    // last visited node in the previous layer that is incident on an inner
    // segment.
    let k0 = 0
    // Tracks the last node in this layer scanned for crossings with a type-1
    // segment.
    let scanPos = 0
    const prevLayerLength = prevLayer.length
    const lastNode = _.last(layer)

    _.forEach(layer, function (v, i) {
      const w = findOtherInnerSegmentNode(g, v)
      const k1 = w ? g.node(w).order : prevLayerLength

      if (w || v === lastNode) {
        _.forEach(layer.slice(scanPos, i + 1), function (scanNode) {
          _.forEach(g.predecessors(scanNode), function (u) {
            const uLabel = g.node(u)
            const uPos = uLabel.order
            if ((uPos < k0 || k1 < uPos) &&
              !(uLabel.dummy && g.node(scanNode).dummy)) {
              addConflict(conflicts, u, scanNode)
            }
          })
        })
        scanPos = i + 1
        k0 = k1
      }
    })

    return layer
  }

  _.reduce(layering, visitLayer)
  return conflicts
}

function findType2Conflicts (g, layering) {
  const conflicts = {}

  function scan (south, southPos, southEnd, prevNorthBorder, nextNorthBorder) {
    let v
    _.forEach(_.range(southPos, southEnd), function (i) {
      v = south[i]
      if (g.node(v).dummy) {
        _.forEach(g.predecessors(v), function (u) {
          const uNode = g.node(u)
          if (uNode.dummy &&
            (uNode.order < prevNorthBorder || uNode.order > nextNorthBorder)) {
            addConflict(conflicts, u, v)
          }
        })
      }
    })
  }

  function visitLayer (north, south) {
    let prevNorthPos = -1
    let nextNorthPos
    let southPos = 0

    _.forEach(south, function (v, southLookahead) {
      if (g.node(v).dummy === 'border') {
        const predecessors = g.predecessors(v)
        if (predecessors.length) {
          nextNorthPos = g.node(predecessors[0]).order
          scan(south, southPos, southLookahead, prevNorthPos, nextNorthPos)
          southPos = southLookahead
          prevNorthPos = nextNorthPos
        }
      }
      scan(south, southPos, south.length, nextNorthPos, north.length)
    })

    return south
  }

  _.reduce(layering, visitLayer)
  return conflicts
}

function findOtherInnerSegmentNode (g, v) {
  if (g.node(v).dummy) {
    return _.find(g.predecessors(v), function (u) {
      return g.node(u).dummy
    })
  }
}

function addConflict (conflicts, v, w) {
  if (v > w) {
    const tmp = v
    v = w
    w = tmp
  }

  let conflictsV = conflicts[v]
  if (!conflictsV) {
    conflicts[v] = conflictsV = {}
  }
  conflictsV[w] = true
}

function hasConflict (conflicts, v, w) {
  if (v > w) {
    const tmp = v
    v = w
    w = tmp
  }
  return _.has(conflicts[v], w)
}

/*
 * Try to align nodes into vertical "blocks" where possible. This algorithm
 * attempts to align a node with one of its median neighbors. If the edge
 * connecting a neighbor is a type-1 conflict then we ignore that possibility.
 * If a previous node has already formed a block with a node after the node
 * we're trying to form a block with, we also ignore that possibility - our
 * blocks would be split in that scenario.
 */
function verticalAlignment (g, layering, conflicts, neighborFn) {
  const root = {}
  const align = {}
  const pos = {}

  // We cache the position here based on the layering because the graph and
  // layering may be out of sync. The layering matrix is manipulated to
  // generate different extreme alignments.
  _.forEach(layering, function (layer) {
    _.forEach(layer, function (v, order) {
      root[v] = v
      align[v] = v
      pos[v] = order
    })
  })

  _.forEach(layering, function (layer) {
    let prevIdx = -1
    _.forEach(layer, function (v) {
      let ws = neighborFn(v)
      if (ws.length) {
        ws = _.sortBy(ws, function (w) { return pos[w] })
        const mp = (ws.length - 1) / 2
        for (let i = Math.floor(mp), il = Math.ceil(mp); i <= il; ++i) {
          const w = ws[i]
          if (align[v] === v && prevIdx < pos[w] && !hasConflict(conflicts, v, w)) {
            align[w] = v
            align[v] = root[v] = root[w]
            prevIdx = pos[w]
          }
        }
      }
    })
  })

  return { root: root, align: align }
}

function horizontalCompaction (g, layering, root, align, reverseSep) {
  // This portion of the algorithm differs from BK due to a number of problems.
  // Instead of their algorithm we construct a new block graph and do two
  // sweeps. The first sweep places blocks with the smallest possible
  // coordinates. The second sweep removes unused space by moving blocks to the
  // greatest coordinates without violating separation.
  const xs = {}
  const blockG = buildBlockGraph(g, layering, root, reverseSep)

  // First pass, assign smallest coordinates via DFS
  const visited = {}
  function pass1 (v) {
    if (!_.has(visited, v)) {
      visited[v] = true
      xs[v] = _.reduce(blockG.inEdges(v), function (max, e) {
        pass1(e.v)
        return Math.max(max, xs[e.v] + blockG.edge(e))
      }, 0)
    }
  }
  _.forEach(blockG.nodes(), pass1)

  const borderType = reverseSep ? 'borderLeft' : 'borderRight'
  function pass2 (v) {
    if (visited[v] !== 2) {
      visited[v]++
      const node = g.node(v)
      const min = _.reduce(blockG.outEdges(v), function (min, e) {
        pass2(e.w)
        return Math.min(min, xs[e.w] - blockG.edge(e))
      }, Number.POSITIVE_INFINITY)
      if (min !== Number.POSITIVE_INFINITY && node.borderType !== borderType) {
        xs[v] = Math.max(xs[v], min)
      }
    }
  }
  _.forEach(blockG.nodes(), pass2)

  // Assign x coordinates to all nodes
  _.forEach(align, function (v) {
    xs[v] = xs[root[v]]
  })

  return xs
}

function buildBlockGraph (g, layering, root, reverseSep) {
  const blockGraph = new Graph()
  const graphLabel = g.graph()
  const sepFn = sep(graphLabel.nodesep, graphLabel.edgesep, reverseSep)

  _.forEach(layering, function (layer) {
    let u
    _.forEach(layer, function (v) {
      const vRoot = root[v]
      blockGraph.setNode(vRoot)
      if (u) {
        const uRoot = root[u]
        const prevMax = blockGraph.edge(uRoot, vRoot)
        blockGraph.setEdge(uRoot, vRoot, Math.max(sepFn(g, v, u), prevMax || 0))
      }
      u = v
    })
  })

  return blockGraph
}

/*
 * Returns the alignment that has the smallest width of the given alignments.
 */
function findSmallestWidthAlignment (g, xss) {
  return _.minBy(_.values(xss), function (xs) {
    const min = (_.minBy(_.toPairs(xs), (pair) => pair[1] - width(g, pair[0]) / 2) || ['k', 0])[1]
    const max = (_.maxBy(_.toPairs(xs), (pair) => pair[1] + width(g, pair[0]) / 2) || ['k', 0])[1]
    return max - min
  })
}

/*
 * Align the coordinates of each of the layout alignments such that
 * left-biased alignments have their minimum coordinate at the same point as
 * the minimum coordinate of the smallest width alignment and right-biased
 * alignments have their maximum coordinate at the same point as the maximum
 * coordinate of the smallest width alignment.
 */
function alignCoordinates (xss, alignTo) {
  const alignToVals = _.values(alignTo)
  const alignToMin = _.min(alignToVals)
  const alignToMax = _.max(alignToVals)

  _.forEach(['u', 'd'], function (vert) {
    _.forEach(['l', 'r'], function (horiz) {
      const alignment = vert + horiz
      const xs = xss[alignment]
      if (xs === alignTo) {
        return
      }
      const xsVals = _.values(xs)
      const delta = horiz === 'l' ? alignToMin - _.min(xsVals) : alignToMax - _.max(xsVals)
      if (delta) {
        xss[alignment] = _.mapValues(xs, function (x) { return x + delta })
      }
    })
  })
}

function balance (xss, align) {
  return _.mapValues(xss.ul, function (ignore, v) {
    if (align) {
      return xss[align.toLowerCase()][v]
    } else {
      const xs = _.sortBy(_.map(xss, v))
      return (xs[1] + xs[2]) / 2
    }
  })
}

export function positionX (g) {
  const layering = util.buildLayerMatrix(g)
  const conflicts = _.merge(findType1Conflicts(g, layering), findType2Conflicts(g, layering))

  const xss = {}
  let adjustedLayering
  _.forEach(['u', 'd'], function (vert) {
    adjustedLayering = vert === 'u' ? layering : _.values(layering).reverse()
    _.forEach(['l', 'r'], function (horiz) {
      if (horiz === 'r') {
        adjustedLayering = _.map(adjustedLayering, function (inner) {
          return _.values(inner).reverse()
        })
      }

      const neighborFn = _.bind(vert === 'u' ? g.predecessors : g.successors, g)
      const align = verticalAlignment(g, adjustedLayering, conflicts, neighborFn)
      let xs = horizontalCompaction(g, adjustedLayering,
        align.root, align.align,
        horiz === 'r')
      if (horiz === 'r') {
        xs = _.mapValues(xs, function (x) { return -x })
      }
      xss[vert + horiz] = xs
    })
  })

  const smallestWidth = findSmallestWidthAlignment(g, xss)
  alignCoordinates(xss, smallestWidth)
  return balance(xss, g.graph().align)
}

function sep (nodeSep, edgeSep, reverseSep) {
  return function (g, v, w) {
    const vLabel = g.node(v)
    const wLabel = g.node(w)
    let sum = 0
    let delta

    sum += vLabel.width / 2
    if (_.has(vLabel, 'labelpos')) {
      switch (vLabel.labelpos.toLowerCase()) {
        case 'l': delta = -vLabel.width / 2; break
        case 'r': delta = vLabel.width / 2; break
      }
    }
    if (delta) {
      sum += reverseSep ? delta : -delta
    }
    delta = 0

    sum += (vLabel.dummy ? edgeSep : nodeSep) / 2
    sum += (wLabel.dummy ? edgeSep : nodeSep) / 2

    sum += wLabel.width / 2
    if (_.has(wLabel, 'labelpos')) {
      switch (wLabel.labelpos.toLowerCase()) {
        case 'l': delta = wLabel.width / 2; break
        case 'r': delta = -wLabel.width / 2; break
      }
    }
    if (delta) {
      sum += reverseSep ? delta : -delta
    }
    delta = 0

    return sum
  }
}

function width (g, v) {
  return g.node(v).width
}

export default {
  positionX: positionX,
  findType1Conflicts: findType1Conflicts,
  findType2Conflicts: findType2Conflicts,
  addConflict: addConflict,
  hasConflict: hasConflict,
  verticalAlignment: verticalAlignment,
  horizontalCompaction: horizontalCompaction,
  alignCoordinates: alignCoordinates,
  findSmallestWidthAlignment: findSmallestWidthAlignment,
  balance: balance
}


text:
AsteroidManager::AsteroidManager(SDL_Renderer *renderer, Stats *stats)
	: mAsteroidSpawnInterval(20)
{
	mAsteroidMinInterval = 300;
	mAsteroidMaxInterval = 1000;
	mAsteroidMinVelocityInterval = 1;
	mAsteroidMaxVelocityInterval = 3; // This range will rise by 2 every wave
	mNextAsteroidIntervalWaitTime = 500; // Half a second to begin with
	mGameScore = stats;
	mLastAsteroidTime = 0;

	init(renderer);
}

AsteroidManager::~AsteroidManager()
{
	// Delete the asteroid texture
	SDL_DestroyTexture(mAsteroidTexture);
	mAsteroidTexture = NULL;
} // Stats is none of my concern!

void AsteroidManager::init(SDL_Renderer *renderer)
{
	// Create the list of asteroids
	std::string asteroidImagePath = getResourcePath() + "img/asteroid.png";
	mAsteroidTexture = IMG_LoadTexture(renderer, asteroidImagePath.c_str());
	Asteroid::asteroidTexture = mAsteroidTexture; // Set the asteroid texture

	// Create a set of at most X number of asteroids
	for (int i = 0; i < NUMBER_ASTEROIDS; ++i)
		mAsteroids.push_back(AsteroidPtr(new Asteroid(renderer, this)));
}

void AsteroidManager::update()
{
	int waveScore = mGameScore->getWaveScore();
	if ((waveScore > 0)
			&& (waveScore % 10 == 0))
	{
		mGameScore->defeatWave();
		int numWavesDefeated = mGameScore->getNumWavesDefeated();

		// Reduce the wait time unless we've hit rock bottom
		mAsteroidMaxInterval =
				(mAsteroidMaxInterval <= ABS_MIN_INTERVAL) ? mAsteroidMaxInterval = ABS_MIN_INTERVAL
						: 1000 - (mAsteroidSpawnInterval * (numWavesDefeated));

		// Raise the max velocity every wave
		// Raise the min velocity every 2 waves
		mAsteroidMaxVelocityInterval =
			(mAsteroidMaxVelocityInterval >= ABS_MAX_VELOCITY)
				? ABS_MAX_VELOCITY : mAsteroidMaxVelocityInterval + 1;

		if (numWavesDefeated % 2)
		{
			mAsteroidMinVelocityInterval =
				(mAsteroidMinVelocityInterval >= ABS_MIN_VELOCITY)
					? ABS_MIN_VELOCITY : mAsteroidMinVelocityInterval + 1;
		}
	}

	// Fire an asteroid if enough time has passed
	if (mLastAsteroidTime + mNextAsteroidIntervalWaitTime <= SDL_GetTicks())
	{
		int range = mAsteroidMaxInterval - mAsteroidMinInterval;
		if (range <= 0)
			mNextAsteroidIntervalWaitTime = mAsteroidMinInterval;
		else
			mNextAsteroidIntervalWaitTime = rand() % range + mAsteroidMinInterval;

		mLastAsteroidTime = SDL_GetTicks();
		activateAsteroid();
	}

	// Update my container (ie update the stats and the asteroids array
	for (int i = 0; i < NUMBER_ASTEROIDS; ++i)
		mAsteroids[i].get()->update();
}

void AsteroidManager::recordAsteroidMissed()
{
	mGameScore->loseLife();
}

void AsteroidManager::draw()
{
	for (int i=0; i < NUMBER_ASTEROIDS; ++i)
		mAsteroids[i].get()->draw();
}

void AsteroidManager::activateAsteroid()
{
	for (int i = 0; i < NUMBER_ASTEROIDS; ++i)
	{
		Asteroid *currAsteroid = mAsteroids[i].get();
		if (!currAsteroid->checkIsActivated())
		{
//			SDL_Log("Asteroid min vel: %d\tAsteroid max vel: %d\n", mAsteroidMinVelocityInterval,
//						mAsteroidMaxVelocityInterval);
			// Pick a random velocity to apply to the asteroid
			int velocity = 0;
			if (mAsteroidMinVelocityInterval >= mAsteroidMaxVelocityInterval)
			{
				velocity = ABS_MAX_VELOCITY;
			}
			else
			{
				velocity =
					rand() % mAsteroidMaxVelocityInterval + mAsteroidMinVelocityInterval;
			}

			currAsteroid->setVelocity(velocity);

//			SDL_Log("Activating an asteroid with velocity: %d\n", velocity);

			// Pick a random yPosition for the asteroid
			currAsteroid->activate();
			break;
		}
	}
}

void AsteroidManager::reset()
{
	mAsteroidMinInterval = 300;
	mAsteroidMaxInterval = 1000;
	mAsteroidMinVelocityInterval = 1;
	mAsteroidMaxVelocityInterval = 3; // This range will rise by 2 every wave
	mNextAsteroidIntervalWaitTime = 500;
	mLastAsteroidTime = 0;

	for (int i=0; i < NUMBER_ASTEROIDS; ++i)
		mAsteroids[i].get()->reset();
}


text:
@interface XHHSettings : NSObject
@property bool isFirstTime;
@end


text:
using UnityEngine;
using System.Collections;

public class FakeGif : MonoBehaviour
{
    [SerializeField]
    private Texture[] stills;
    [SerializeField]
    private float frameHold = 0.2f;

    private float currentTime = 0;
    private int currentFrame = 0;
    private Material mat;

    void Start()
    {
        this.mat = GetComponent<MeshRenderer>().material;
    }

    void Update()
    {
        if (this.currentTime < this.frameHold)
        {
            this.currentTime += Time.deltaTime;
            return;
        }

        this.currentTime = 0;
        this.mat.mainTexture = this.stills[this.currentFrame];
        this.currentFrame++;
        if (this.currentFrame >= this.stills.Length)
        {
            this.currentFrame = 0;
        }
    }
}


text:
using System.Collections.Generic;
using System.Security;
using Xunit;

namespace System.Reflection.Tests
{
    public class GetCustomAttributes_MemberInfo
    {
        private static readonly Type s_typeWithoutAttr = typeof(TestClassWithoutAttribute);
        private static readonly Type s_typeBaseClass = typeof(TestBaseClass);
        private static readonly Type s_typeTestClass = typeof(TestClass);

        [Fact]
        public void IsDefined_Inherit()
        {
            Assert.False(CustomAttributeExtensions.IsDefined(s_typeTestClass.GetTypeInfo(), typeof(MyAttribute_Single_Inherited), false));
        }

        [Fact]
        public void IsDefined()
        {
            Assert.True(CustomAttributeExtensions.IsDefined(s_typeTestClass.GetTypeInfo(), typeof(MyAttribute_Single_M)));

            Assert.Throws<ArgumentException>(() =>
            {
                CustomAttributeExtensions.IsDefined(s_typeTestClass.GetTypeInfo(), typeof(String));
            });

            Assert.Throws<ArgumentNullException>(() =>
            {
                CustomAttributeExtensions.IsDefined(s_typeTestClass.GetTypeInfo(), null);
            });
        }

        [Fact]
        public void GetCustomAttributeOfT_Single_NotInherited()
        {
            Attribute attribute = CustomAttributeExtensions.GetCustomAttribute<MyAttribute_Single_Inherited>(s_typeTestClass.GetTypeInfo(), false);
            Assert.Null(attribute);
        }

        [Fact]
        public void GetCustomAttributeOfT_Single()
        {
            Attribute attribute = CustomAttributeExtensions.GetCustomAttribute<MyAttribute_Single_Inherited>(s_typeTestClass.GetTypeInfo());
            Assert.NotNull(attribute);

            Assert.Throws<AmbiguousMatchException>(() =>
            {
                attribute = CustomAttributeExtensions.GetCustomAttribute<MyAttribute_AllowMultiple_Inherited>(s_typeTestClass.GetTypeInfo());
            });
        }

        [Fact]
        public void GetCustomAttributeT_Multiple_NoInheirit()
        {
            var attributes = CustomAttributeExtensions.GetCustomAttributes<MyAttribute_AllowMultiple_Inherited>(s_typeTestClass.GetTypeInfo(), false);
            Assert.Equal(1, attributes.Count());
        }

        [Fact]
        public void GetCustomAttributeOfT_Multiple()
        {
            IEnumerable<Attribute> attributes = CustomAttributeExtensions.GetCustomAttributes<MyAttribute_Single_Inherited>(s_typeTestClass.GetTypeInfo());
            Assert.Equal(1, attributes.Count());

            attributes = CustomAttributeExtensions.GetCustomAttributes<SecurityCriticalAttribute>(s_typeTestClass.GetTypeInfo());
            Assert.Equal(0, attributes.Count());
        }

        [Fact]
        public void GetCustomAttribute_Multiple_NotInherited()
        {
            var attribute = CustomAttributeExtensions.GetCustomAttribute(s_typeTestClass.GetTypeInfo(), typeof(MyAttribute_AllowMultiple_Inherited), false);
            Assert.NotNull(attribute);

            var attributes = CustomAttributeExtensions.GetCustomAttributes(s_typeTestClass.GetTypeInfo(), typeof(MyAttribute_AllowMultiple_Inherited), false);
            Assert.Equal(1, attributes.Count());
        }

        [Fact]
        public void GetCustomAttributeSingle()
        {
            Attribute attribute = CustomAttributeExtensions.GetCustomAttribute(s_typeTestClass.GetTypeInfo(), typeof(MyAttribute_Single_M));
            Assert.NotNull(attribute);

            Assert.Throws<AmbiguousMatchException>(() =>
            {
                attribute = CustomAttributeExtensions.GetCustomAttribute(s_typeTestClass.GetTypeInfo(), typeof(MyAttribute_AllowMultiple_Inherited));
            });

            Assert.Throws<ArgumentException>(() =>
            {
                attribute = CustomAttributeExtensions.GetCustomAttribute(s_typeTestClass.GetTypeInfo(), typeof(String));
            });

            Assert.Throws<ArgumentNullException>(() =>
            {
                attribute = CustomAttributeExtensions.GetCustomAttribute(s_typeTestClass.GetTypeInfo(), null);
            });
        }

        [Fact]
        public void GetCustomAttribute4()
        {
            IEnumerable<Attribute> attributes = CustomAttributeExtensions.GetCustomAttributes(s_typeTestClass.GetTypeInfo(), typeof(MyAttribute_AllowMultiple_Inherited));
            Assert.Equal(2, attributes.Count());

            attributes = CustomAttributeExtensions.GetCustomAttributes(s_typeTestClass.GetTypeInfo(), typeof(SecurityCriticalAttribute));
            Assert.Equal(0, attributes.Count());

            Assert.Throws<ArgumentException>(() =>
            {
                attributes = CustomAttributeExtensions.GetCustomAttributes(s_typeTestClass.GetTypeInfo(), typeof(String));
            });

            Assert.Throws<ArgumentNullException>(() =>
            {
                attributes = CustomAttributeExtensions.GetCustomAttributes(s_typeTestClass.GetTypeInfo(), null);
            });
        }

        [Fact]
        public void GetCustomAttribute5()
        {
            IEnumerable<Attribute> attributes = CustomAttributeExtensions.GetCustomAttributes(s_typeTestClass.GetTypeInfo(), false);
            Assert.Equal(4, attributes.Count());
            Assert.Equal(1, attributes.Count(attr => attr.ToString().Equals("System.Reflection.Tests.MyAttribute_Single_M single", StringComparison.Ordinal)));
            Assert.Equal(1, attributes.Count(attr => attr.ToString().Equals("System.Reflection.Tests.MyAttribute_AllowMultiple_M multiple1", StringComparison.Ordinal)));
            Assert.Equal(1, attributes.Count(attr => attr.ToString().Equals("System.Reflection.Tests.MyAttribute_AllowMultiple_M multiple2", StringComparison.Ordinal)));
            Assert.Equal(1, attributes.Count(attr => attr.ToString().Equals("System.Reflection.Tests.MyAttribute_AllowMultiple_Inherited multiple", StringComparison.Ordinal)));
        }

        [Fact]
        public void GetCustomAttributeAll()
        {
            IEnumerable<Attribute> attributes = CustomAttributeExtensions.GetCustomAttributes(s_typeWithoutAttr.GetTypeInfo());
            Assert.Equal(0, attributes.Count());

            attributes = CustomAttributeExtensions.GetCustomAttributes(s_typeTestClass.GetTypeInfo(), true);

            IEnumerator<Attribute> customAttrs = attributes.GetEnumerator();

            Assert.Equal(6, attributes.Count());
            Assert.Equal(1, attributes.Count(attr => attr.ToString().Equals("System.Reflection.Tests.MyAttribute_Single_M single", StringComparison.Ordinal)));
            Assert.Equal(1, attributes.Count(attr => attr.ToString().Equals("System.Reflection.Tests.MyAttribute_AllowMultiple_M multiple1", StringComparison.Ordinal)));
            Assert.Equal(1, attributes.Count(attr => attr.ToString().Equals("System.Reflection.Tests.MyAttribute_AllowMultiple_M multiple2", StringComparison.Ordinal)));
            Assert.Equal(1, attributes.Count(attr => attr.ToString().Equals("System.Reflection.Tests.MyAttribute_Single_Inherited singleBase", StringComparison.Ordinal)));
            Assert.Equal(1, attributes.Count(attr => attr.ToString().Equals("System.Reflection.Tests.MyAttribute_AllowMultiple_Inherited multiple", StringComparison.Ordinal)));
            Assert.Equal(1, attributes.Count(attr => attr.ToString().Equals("System.Reflection.Tests.MyAttribute_AllowMultiple_Inherited multipleBase", StringComparison.Ordinal)));

            IEnumerable<CustomAttributeData> attributeData = s_typeTestClass.GetTypeInfo().CustomAttributes;

            IEnumerator<CustomAttributeData> customAttrsdata = attributeData.GetEnumerator();

            Assert.Equal(4, attributeData.Count());
            Assert.Equal(3, attributeData.Count(attr => attr.ToString().Contains("MyAttribute_AllowMultiple")));
            Assert.Equal(1, attributeData.Count(attr => attr.ToString().Contains("MyAttribute_Single_M")));
        }
    }

    public class MyAttributeBase_M : Attribute
    {
        private String _name;
        public MyAttributeBase_M(String name)
        {
            _name = name;
        }
        public override String ToString() { return this.GetType() + " " + _name; }
    }

    [AttributeUsage(AttributeTargets.All, AllowMultiple = false, Inherited = false)]
    public class MyAttribute_Single_M : MyAttributeBase_M
    {
        public MyAttribute_Single_M(String name) : base(name) { }
    }

    [AttributeUsage(AttributeTargets.All, AllowMultiple = true, Inherited = false)]
    public class MyAttribute_AllowMultiple_M : MyAttributeBase_M
    {
        public MyAttribute_AllowMultiple_M(String name) : base(name) { }
    }

    [AttributeUsage(AttributeTargets.All, AllowMultiple = false, Inherited = true)]
    public class MyAttribute_Single_Inherited : MyAttributeBase_M
    {
        public MyAttribute_Single_Inherited(String name) : base(name) { }
    }

    [AttributeUsage(AttributeTargets.All, AllowMultiple = true, Inherited = true)]
    public class MyAttribute_AllowMultiple_Inherited : MyAttributeBase_M
    {
        public MyAttribute_AllowMultiple_Inherited(String name) : base(name) { }
    }

    public class TestClassWithoutAttribute
    {
    }

    [MyAttribute_Single_M("singleBase"),
     MyAttribute_AllowMultiple_M("multiple1Base"),
     MyAttribute_AllowMultiple_M("multiple2Base"),
     MyAttribute_Single_Inherited("singleBase"),
     MyAttribute_AllowMultiple_Inherited("multipleBase")]
    public class TestBaseClass
    {
    }

    [MyAttribute_Single_M("single"),
     MyAttribute_AllowMultiple_M("multiple1"),
     MyAttribute_AllowMultiple_M("multiple2"),
     MyAttribute_AllowMultiple_Inherited("multiple")]
    public class TestClass : TestBaseClass
    {
    }
}


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

  <title>spgl.gobjects.G3DRect</title>
  <link rel="stylesheet" href="epydoc.css" type="text/css" />

         Home

         Trees

         Indices

         Help

        Package spgl ::
        Module gobjects ::
        Class G3DRect

[hide private]

[frames] | no frames]

Class G3DRect

source code

GObject --+
          |
      GRect --+
              |
             G3DRect

This graphical object subclass represents a rectangular box that can
  be raised or lowered.

        Instance Methods
        [hide private]

      void

          __init__(self,
        width,
        height,
        x=0,
        y=0,
        raised=False)

      Initializes a new 3D rectangle with the specified width and height.

            source code

      void

          setRaised(self,
        raised)

      Indicates whether this object appears raised.

            source code

      boolean

          isRaised(self)

      Returns true if this object appears raised.

            source code

      string

          getType(self)

      Returns the type of this object

            source code

      string

          toString(self)

      Returns the string form of this object

            source code

Inherited from GRect:
      create,
      getBounds,
      getFillColor,
      isFilled,
      setBounds,
      setFillColor,
      setFilled,
      setSize

Inherited from GObject:
      contains,
      getColor,
      getHeight,
      getLineWidth,
      getLocation,
      getParent,
      getSize,
      getWidth,
      getX,
      getY,
      isVisible,
      move,
      rotate,
      scale,
      sendBackward,
      sendForward,
      sendToBack,
      sendToFront,
      setColor,
      setLineWidth,
      setLocation,
      setVisible

        Method Details
        [hide private]

__init__(self,
        width,
        height,
        x=0,
        y=0,
        raised=False)

(Constructor)

  	source code

Initializes a new 3D rectangle with the specified width and height.
  If the x and y parameters are specified, they are used to specify the
  origin.  The raised parameter determines whether the rectangle should be
  drawn with highlights that suggest that it is raised about the
  background.

Parameters:

y (float)

width (float)

raised (boolean)

x (float)

height (float)

Returns: void

Overrides:
        GObject.__init__

setRaised(self,
        raised)

  	source code

Indicates whether this object appears raised.

Parameters:

raised (boolean)

Returns: void

getType(self)

  	source code

Returns the type of this object

Returns: string

Overrides:
        GObject.getType

toString(self)

  	source code

Returns the string form of this object

Returns: string

Overrides:
        GObject.toString

         Home

         Trees

         Indices

         Help

    Generated by Epydoc 3.0.1 on Fri May 10 02:58:16 2013

      http://epydoc.sourceforge.net


text:
<?php

declare(strict_types=1);

namespace MaxMind\MinFraud\Model;

/**
 * Model containing the IP address's risk for the Score response.
 *
 * @property-read float $risk This field contains the risk associated with the IP
 * address. The value ranges from 0.01 to 99. A higher score indicates a
 * higher risk.
 */
class ScoreIpAddress extends AbstractModel
{
    /**
     * @ignore
     *
     * @var float
     */
    protected $risk;

    public function __construct(?array $response, array $locales = ['en'])
    {
        parent::__construct($response, $locales);
        $this->risk = $this->safeArrayLookup($response['risk']);
    }
}


text:
//
// Copyright (c) 2019 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// TranslatorMetal:
//   A GLSL-based translator that outputs shaders that fit GL_KHR_vulkan_glsl.
//   It takes into account some considerations for Metal backend also.
//   The shaders are then fed into glslang to spit out SPIR-V (libANGLE-side).
//   See: https://www.khronos.org/registry/vulkan/specs/misc/GL_KHR_vulkan_glsl.txt
//
//   The SPIR-V will then be translated to Metal Shading Language later in Metal backend.
//

#ifndef LIBANGLE_RENDERER_METAL_TRANSLATORMETAL_H_
#define LIBANGLE_RENDERER_METAL_TRANSLATORMETAL_H_

#include "compiler/translator/TranslatorVulkan.h"

namespace sh
{

class TranslatorMetal : public TranslatorVulkan
{
  public:
    TranslatorMetal(sh::GLenum type, ShShaderSpec spec);

  protected:
    ANGLE_NO_DISCARD bool translate(TIntermBlock *root,
                                    ShCompileOptions compileOptions,
                                    PerformanceDiagnostics *perfDiagnostics) override;

    ANGLE_NO_DISCARD bool transformDepthBeforeCorrection(TIntermBlock *root,
                                                         const TVariable *driverUniforms) override;
};

}  // namespace sh

#endif /* LIBANGLE_RENDERER_METAL_TRANSLATORMETAL_H_ */


text:
var module = angular.module("frontpress.components.full-post");

function FullPostModel(PostsApi, TagsApi, CategoriesApi, $q, MediaApi, $FrontPress){
	var model = {
		addTag: addTag,
        categories: [],
        content: null,
        date: null,
        featuredImage: null,
        id: null,
        isLoadingCategories: null,
        isLoadingFullPost: false,
        isLoadingTags: false,
        setContent: setContent,
        setFeaturedImage: setFeaturedImage,
        setId: setId,
		setTitle: setTitle,
		slug: null,
		tags: [],
		title: null,
	};

	function addCategory(category){
		model.categories.push(category);
	}

	function addTag(tag){
		model.tags.push(tag);
	}

	function setTitle(title){
		model.title = title;
	}

	function setContent(content){
		model.content = content;
	}

	function setDate(date){
		model.date = date;
	}

	function setFeaturedImage(featuredImage){
		model.featuredImage = featuredImage;
		model.featured_image = featuredImage;
	}

	function setCategoryNames(categoryNames){
		model.categoryNames = categoryNames;
	}

	function setSlug(slug){
		model.slug = slug;
	}

	function setId(id){
		model.id = id;
	}

    model.addCategory = addCategory;
    model.setSlug = setSlug;
    model.setDate = setDate;

	function loadFullPostById(id){
		var defer = $q.defer();

		model.isLoadingFullPost = true;
		var configs = {
			fields: "ID,title,featured_image,featured_media,date,categories,content,slug,tags"
		};

		var postPromise = PostsApi.getPostById(id, configs);
		postPromise.success(function(result){
			model.setTitle(result.title);
			model.setContent(result.content);
			model.setDate(result.date);
			model.setSlug(result.slug);

			switch($FrontPress.apiVersion){
				case "v2":

					var categoriesIds = result.categories;
					for(var i=0; i < categoriesIds.length; i++){
						model.isLoadingCategories = true;

						CategoriesApi.getCategoryById(categoriesIds[i]).success(function(categoryResult){
							var category = {};
							category.name = categoryResult.name;
							model.addCategory(category);
							model.isLoadingCategories = false;
						});
					}

					var tagsIds = result.tags;
					for(var j=0; j < tagsIds.length; j++){
						model.isLoadingTags = true;

						TagsApi.getTagById(tagsIds[j]).success(function(tagResult){
							var tag = {};
							tag.name = tagResult.name;
							model.addTag(tag);
							model.isLoadingTags = false;
						});
					}

					var featuredImagesPromise = MediaApi.getMediaById(result.featured_media);

					featuredImagesPromise.success(function(result){
						model.setFeaturedImage(result.source_url);
					});

					break;

				case "v1":
					model.setFeaturedImage(result.featured_image);

					for (var category in result.categories){
						model.addCategory(result.categories[category]);
					}

					model.isLoadingCategories = false;

					for (var tag in result.tags){
						model.addTag(result.tags[tag]);
					}

					model.isLoadingTags = false;
					break;
			}

			model.isLoadingFullPost = false;
			defer.resolve(model);
		});

		return defer.promise;
	}

    model.loadFullPostById = loadFullPostById;

	return model;
}

module.factory("FullPostModel", FullPostModel);


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

<title>CompLess</title>
<meta name="date" content="2014-04-10">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

JSHOP2

Class CompLess

java.lang.Object

JSHOP2.CompLess

All Implemented Interfaces:

java.util.Comparator<Term[]>

public class CompLess
extends java.lang.Object
implements java.util.Comparator<Term[]>

This class handles :sort-by logical preconditions that use
  numerical less than as the sorting function.

Version:

1.0.3

Author:

Okhtay Ilghami, http://www.cs.umd.edu/~okhtay

Field Summary

Fields

Modifier and Type
Field and Description

private int
varIdx

The index of the variable according to the value of which the satisfiers
  should be sorted.

Constructor Summary

Constructors

Constructor and Description

CompLess(int varIdxIn)

To initialize this object.

Method Summary

Methods

Modifier and Type
Method and Description

int
compare(Term[] t1,
       Term[] t2)

The function that implements the actual comparison.

Methods inherited from class java.lang.Object

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

Methods inherited from interface java.util.Comparator

equals

Field Detail

varIdx

private int varIdx

The index of the variable according to the value of which the satisfiers
  should be sorted.

Constructor Detail

CompLess

public CompLess(int varIdxIn)

To initialize this object.

Parameters:

varIdxIn - The index of the variable according to the value of which the
          satisfiers should be sorted.

Method Detail

compare

public int compare(Term[] t1,
          Term[] t2)

The function that implements the actual comparison.

Specified by:

compare in interface java.util.Comparator<Term[]>

Parameters:

t1 - the first binding.

t2 - the second binding.

Returns:

-1 if the first binding should come first, 1 if the second
          binding should come first, 0 if the variable according to value
          of which the satisfiers are being sorted has the same value in
          these two bindings.

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:
module Vulkan
    class VkInstanceCreateInfo < FFI::Struct
        layout sType:                   :VkStructureType,
               pNext:                   :pointer,
               flags:                   :VkInstanceCreateFlags,
               pApplicationInfo:        :pointer,
               enabledLayerCount:       :uint32_t,
               ppEnabledLayerNames:     :pointer,
               enabledExtensionCount:   :uint32_t,
               ppEnabledExtensionNames: :pointer
    end
end


text:
{-|
  This module offers a `Bounded` supervisor variant,
  where `SupervisionEvent`(s) are written on a `TBQueue`,
  and simply discarded if the queue is full.
-}

{-# LANGUAGE GADTs #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}

module Control.Concurrent.Supervisor.Bounded
  ( Supervisor
  , Child
  , newSupervisor
  , defaultEventQueueSize
  , module T
  ) where

import           Control.Concurrent.STM
import           Control.Concurrent.Supervisor.Types as T hiding (Supervisor, newSupervisor)
import qualified Control.Concurrent.Supervisor.Types as Types
import           Numeric.Natural

type Supervisor = Types.Supervisor TBQueue

--------------------------------------------------------------------------------
type Child = Types.Child_ TBQueue

--------------------------------------------------------------------------------
-- | The default size of the queue where `SupervisionEvent`(s) are written.
defaultEventQueueSize :: Natural
defaultEventQueueSize = 10000

--------------------------------------------------------------------------------
newSupervisor :: RestartStrategy -> Natural -> IO Supervisor
newSupervisor = Types.newSupervisor


text:
class GoalIntegrationsController < ApplicationController
  before_action :set_goal_integration, except: [:create, :new]

  def edit
  end

  def create
    @goal_integration = GoalIntegration.new(goal_integration_params)
    @goal_integration.user_id = current_user.id
    if @goal_integration.save
      @goal_integration.get_activity
      @user.reload
      redirect_to root_url, notice: 'Goal integration created.'
    else
      render :new
    end
  end

  def update
    respond_to do |format|
      if @goal_integration.update(goal_integration_params)
        format.html { redirect_to edit_user_url(current_user), notice: 'Goal integration created.' }
      else
        format.html { render edit_user_url(current_user) }
      end
    end
  end

  # DELETE /users/1
  # DELETE /users/1.json
  def destroy
    @goal_integration.destroy
    respond_to do |format|
      format.html { redirect_to edit_user_url(current_user) }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_goal_integration
      @goal_integration = GoalIntegration.find(params[:id])
    end

    def goal_integration_params
      params.require(:goal_integration).permit(:goal_title, :activity_type, :unit)
    end
end


text:
package internalversion

import (
	api "github.com/openshift/origin/pkg/sdn/api"
	"k8s.io/kubernetes/pkg/api/errors"
	"k8s.io/kubernetes/pkg/client/cache"
	"k8s.io/kubernetes/pkg/labels"
)

// ClusterNetworkLister helps list ClusterNetworks.
type ClusterNetworkLister interface {
	// List lists all ClusterNetworks in the indexer.
	List(selector labels.Selector) (ret []*api.ClusterNetwork, err error)
	// ClusterNetworks returns an object that can list and get ClusterNetworks.
	ClusterNetworks(namespace string) ClusterNetworkNamespaceLister
	ClusterNetworkListerExpansion
}

// clusterNetworkLister implements the ClusterNetworkLister interface.
type clusterNetworkLister struct {
	indexer cache.Indexer
}

// NewClusterNetworkLister returns a new ClusterNetworkLister.
func NewClusterNetworkLister(indexer cache.Indexer) ClusterNetworkLister {
	return &clusterNetworkLister{indexer: indexer}
}

// List lists all ClusterNetworks in the indexer.
func (s *clusterNetworkLister) List(selector labels.Selector) (ret []*api.ClusterNetwork, err error) {
	err = cache.ListAll(s.indexer, selector, func(m interface{}) {
		ret = append(ret, m.(*api.ClusterNetwork))
	})
	return ret, err
}

// ClusterNetworks returns an object that can list and get ClusterNetworks.
func (s *clusterNetworkLister) ClusterNetworks(namespace string) ClusterNetworkNamespaceLister {
	return clusterNetworkNamespaceLister{indexer: s.indexer, namespace: namespace}
}

// ClusterNetworkNamespaceLister helps list and get ClusterNetworks.
type ClusterNetworkNamespaceLister interface {
	// List lists all ClusterNetworks in the indexer for a given namespace.
	List(selector labels.Selector) (ret []*api.ClusterNetwork, err error)
	// Get retrieves the ClusterNetwork from the indexer for a given namespace and name.
	Get(name string) (*api.ClusterNetwork, error)
	ClusterNetworkNamespaceListerExpansion
}

// clusterNetworkNamespaceLister implements the ClusterNetworkNamespaceLister
// interface.
type clusterNetworkNamespaceLister struct {
	indexer   cache.Indexer
	namespace string
}

// List lists all ClusterNetworks in the indexer for a given namespace.
func (s clusterNetworkNamespaceLister) List(selector labels.Selector) (ret []*api.ClusterNetwork, err error) {
	err = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {
		ret = append(ret, m.(*api.ClusterNetwork))
	})
	return ret, err
}

// Get retrieves the ClusterNetwork from the indexer for a given namespace and name.
func (s clusterNetworkNamespaceLister) Get(name string) (*api.ClusterNetwork, error) {
	obj, exists, err := s.indexer.GetByKey(s.namespace + "/" + name)
	if err != nil {
		return nil, err
	}
	if !exists {
		return nil, errors.NewNotFound(api.Resource("clusternetwork"), name)
	}
	return obj.(*api.ClusterNetwork), nil
}


text:
<?php

namespace League\CLImate\TerminalObject\Helper;

interface SleeperInterface
{
    /**
     * @param int|float $percentage
     */
    public function speed($percentage);

    public function sleep();
}


text:
<!DOCTYPE html>
<meta charset="utf-8">
<title>CSS Grid Layout Test: Grid Track Sizing Algorithm Flexible Tracks and Gutters</title>
<link rel="author" title="Manuel Rego Casasnovas" href="mailto:rego@igalia.com">
<link rel="help" href="https://drafts.csswg.org/css-grid/#gutters">
<link rel="help" href="https://drafts.csswg.org/css-grid/#algo-find-fr-size">
<meta name="assert" content="This test checks that the size of flexible tracks is properly computed when the grid container is content based and you have items spanning flexbile tracks that are smaller than the gutter sizes.">
<link rel="stylesheet" type="text/css" href="/fonts/ahem.css" />

 { checkLayout('.grid'); })">

X

X

X

X

X

X


text:
        {{> _common/totop-btn/totop-btn}}

Координатор сайта: {{phone}}

© FaceMaster — Фейсмастер

При полном или частичном воспроизведении информации
                    активная ссылка на Фейсмастер обязательна.

                {{#each links}}
                {{{title}}}
                {{/each}}


text:
.row.fullRow {
  max-width: 100%;
  width: 100%;
}

.hidden {
  display: none;
}
.vAlignOuterContainer {
  display: table;
  height: 180px;
  overflow: hidden;
  width: 100%;
}
.vAlignInnerContainer {
  display: table-cell;
  vertical-align: middle;
  width: 100%;
  margin: 0 auto;
  text-align: center;
}
.vAlignElementContainer {
  display: block;
}


text:
# Configure Rails Environment
ENV["RAILS_ENV"] = "test"

require File.expand_path("../dummy/config/environment.rb",  __FILE__)
require "rails/test_help"

Rails.backtrace_cleaner.remove_silencers!

# Load support files
Dir["#{File.dirname(__FILE__)}/support/**/*.rb"].each { |f| require f }

# Stub for requests
require 'webmock/minitest'

# Load fixtures from the engine
if ActiveSupport::TestCase.method_defined?(:fixture_path=)
  ActiveSupport::TestCase.fixture_path = File.expand_path("../fixtures", __FILE__)
end


text:
// Copyright 2016 Circonus, Inc. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

'use strict';

const assert = require('assert');
const fs = require('fs');
const path = require('path');

const chalk = require('chalk');

const cosi = require(path.resolve(path.join(__dirname, '..')));
const api = require(path.resolve(cosi.lib_dir, 'api'));

module.exports = class Worksheet {

    /**
     * initialize a worksheet object
     * @arg {String} configFile for worksheet
     */
    constructor(configFile) {
        // configFile must be either a "config-" or "registration-"

        if (!configFile) {
            throw new Error('Missing Argument: configFile');
        }

        if (!configFile.match(/\/(config|registration)-worksheet-/)) {
            throw new Error(`Invalid worksheet configuration/registration file '${configFile}'`);
        }

        const cfgFile = path.resolve(configFile);

        try {
            const config = require(cfgFile); // eslint-disable-line global-require

            this._init(config);
        } catch (err) {
            if (err.code === 'MODULE_NOT_FOUND') {
                console.error(chalk.red('ERROR - worksheet configuration file not found:'), cfgFile);
                process.exit(1); // eslint-disable-line no-process-exit
            } else {
                throw err;
            }
        }
    }

    /**
     * save current worksheet object to a config file
     * @arg {String} configFile for worksheet
     * @arg {Boolean} force overwrite of existing file
     * @returns {String} config file name
     */
    save(configFile, force) {
        assert.strictEqual(typeof configFile, 'string', 'configFile is required');

        const cfgFile = path.resolve(configFile);

        try {
            fs.writeFileSync(
                cfgFile,
                JSON.stringify(this, null, 4), {
                    encoding : 'utf8',
                    flag     : force ? 'w' : 'wx',
                    mode     : 0o644
                });
        } catch (err) {
            // fs write errors are passed up (not handled, e.g. ENOENT, EEXIST, etc.)
            throw err;
        }

        return cfgFile;
    }

    /**
     * verifies all attributes are present for create but *does not* validate the values of each attribute!!! (yet)
     * @arg {Boolean} existing stricter validation
     * @returns {Boolean} whether config is valid
     */
    verifyConfig(existing) {
        // default existing to false, most restrictive verify
        // (ensures attributes which could alter an *existing* worksheet are not present)
        existing = typeof existing === 'undefined' ? false : existing; // eslint-disable-line no-param-reassign

        const requiredAttributes = [
            'description',          // string
            'favorite',             // boolean
            'notes',                // string
            'tags',                 // array (of strings)
            'title'                 // string
        ];

        // note - at least ONE of these is required to make the worksheet valid
        const optionalAttributes = [
            'graphs',           // array (of objects)
            'smart_queries'     // array (of objects)
        ];

        const requiredGraphsAttributes = [
            'graph'             // string (graph cid)
        ];

        const requiredSmartQueriesAttributes = [
            'name',             // string
            'order',            // array (of string - graph cids)
            'query'             // string
        ];

        const requiredExistingAttributes = [
            '_cid'              // string
        ];

        let errors = 0;

        // for (const attr of requiredExistingAttributes) {
        for (let i = 0; i < requiredExistingAttributes.length; i++) {
            const attr = requiredExistingAttributes[i];

            if (existing && !{}.hasOwnProperty.call(this, attr)) {
                console.error(chalk.red('Missing attribute'), attr, 'required for', chalk.bold('existing'), 'worksheet');
                errors += 1;
            }

            if (!existing && {}.hasOwnProperty.call(this, attr)) {
                console.error(chalk.red('Invalid attribute'), attr, 'for', chalk.bold('new'), 'worksheet');
                errors += 1;
            }
        }

        for (const attr of requiredAttributes) {
            if (!{}.hasOwnProperty.call(this, attr)) {
                console.error(chalk.red('Missing attribute'), attr);
                errors += 1;
            }
        }

        let hasOne = false;

        for (const attr of optionalAttributes) {
            if ({}.hasOwnProperty.call(this, attr)) {
                if (Array.isArray(this[attr]) && this[attr].length > 0) {
                    hasOne = true;
                }
            } else {
                console.error(`Missing ${chalk.yellow('OPTIONAL')} attribute ${attr}, ignoring.`);
            }
        }

        if (!hasOne) {
            console.error(chalk.red('ERROR'), "One of 'graphs' or 'smart_queries' is requried.");
            errors += 1;
        }

        if ({}.hasOwnProperty.call(this, 'graphs')) {
            for (let idx = 0; idx < this.graphs.length; idx++) {
                for (const attr of requiredGraphsAttributes) {
                    if (!{}.hasOwnProperty.call(this.graphs[idx], attr)) {
                        console.error(chalk.red('Missing attribute'), `graphs item #${idx}requires '${attr}'`);
                        errors += 1;
                    }
                }
            }
        }

        if ({}.hasOwnProperty.call(this, 'smart_queries')) {
            for (const query of this.smart_queries) {
                for (const attr of requiredSmartQueriesAttributes) {
                    if (!{}.hasOwnProperty.call(query, attr)) {
                        console.error(chalk.red('Missing attribute'), `smart query '${query.name || query.query}' requires '${attr}'`);
                        errors += 1;
                    }
                }
            }
        }

        return errors === 0;
    }

    /**
     * call api to create a worksheet
     * @returns {Object} promise
     */
    create() {
        return new Promise((resolve, reject) => {
            if (!this.verifyConfig(false)) {
                reject(new Error('Invalid configuration'));

                return;
            }

            api.post('/worksheet', this).
                then((res) => {
                    if (res.parsed_body === null || res.code !== 200) {
                        const err = new Error();

                        err.code = res.code;
                        err.message = 'UNEXPECTED_API_RETURN';
                        err.body = res.parsed_body;
                        err.raw_body = res.raw_body;

                        reject(err);

                        return;
                    }

                    this._init(res.parsed_body);

                    resolve(res.parsed_body);
                }).
                catch((err) => {
                    reject(err);
                });
        });
    }

    /**
     * call api to update a worksheet
     * @returns {Object} promise
     */
    update() {
        return new Promise((resolve, reject) => {
            if (!this.verifyConfig(true)) {
                reject(new Error('Invalid configuration'));

                return;
            }

            api.put(this._cid, this).
                then((res) => {
                    if (res.parsed_body === null || res.code !== 200) {
                        const err = new Error();

                        err.code = res.code;
                        err.message = 'UNEXPECTED_API_RETURN';
                        err.body = res.parsed_body;
                        err.raw_body = res.raw_body;

                        reject(err);

                        return;
                    }

                    this._init(res.parsed_body);

                    resolve(res.parsed_body);
                }).
                catch((err) => {
                    reject(err);
                });
        });
    }

    /**
     * initializes the current object with values from a loaded configuration
     * @arg {Object} config loaded or retrieved from api
     * @returns {undefined} nothing
     */
    _init(config) {
        for (const key of Object.keys(config)) {
            if ({}.hasOwnProperty.call(config, key)) {
                this[key] = config[key];
            }
        }
    }

};


text:
class FixName < ActiveRecord::Migration
  def change
    remove_column :users, :aligment_id
    add_column :users, :alignment_id, :integer
  end
end


text:
import os
import json
import time
import sys
import collections
import copy

from pymongo import Connection

from smcredentials import CredentialsResolver
from smprocess import kill_by_test_id, test_has_running_processes, SmProcess
from servicemanager.service.smplayservice import SmPlayService, SmPlayServiceStarter
from service.smdropwizardservice import SmDropwizardService, SmDropwizardServiceStarter
from service.smexternalservice import SmExternalService, SmExternalServiceStarter
from service.smpythonservice import SmPythonServiceStarter, SmPythonService
from smutil import pretty_print_list, if_not, unify_lists
from actions.colours import BColors

b = BColors()

def validate_always_run_from(value):
    if value in ["RELEASE", "SNAPSHOT", "SOURCE"]:
        return True
    return False

def merge_dict(d1, d2):
    """
    Modifies d1 in-place to contain values from d2.  If any value
    in d1 is a dictionary (or dict-like), *and* the corresponding
    value in d2 is also a dictionary, then merge them in-place.
    """
    for k,v2 in d2.items():
        v1 = d1.get(k) # returns None if v1 has no value for this key
        if ( isinstance(v1, collections.Mapping) and
             isinstance(v2, collections.Mapping) ):
            merge_dict(v1, v2)
        else:
            d1[k] = v2

class ServiceManagerException(Exception):
    def __init__(self, message):
        Exception.__init__(self, message)

class SmApplication():
    # Application context object - loads, validates and stores global configuration

    def __init__(self, configuration_dir_parameter=None, features=None, process_manager=SmProcess):

        self.workspace = SmApplication._required_environment_directory("WORKSPACE", "your workspace root dir")
        self.java_home = SmApplication._required_environment_directory("JAVA_HOME", "path/to/jdk")

        self.configuration_dir = SmApplication._get_configuration_dir(self, configuration_dir_parameter)

        self.services = SmApplication._read_json_config(self, "services.json")
        self.profiles = SmApplication._read_json_config(self, "profiles.json")
        self.config = SmApplication._read_json_config(self, "config.json")

        self.templates = SmApplication._read_json_config(self, "templates.json")
        self.merge_template_config()

        self.nexus_repo_host = SmApplication._read_json_config(self, "config.json")["nexus"]["host"]
        self.play_extraction_dir = SmApplication._read_json_config(self, "config.json")["playExtractionDir"]
        self.service_mappings = SmApplication._read_json_config(self, "service_mappings.json")
        self.features = features

        self.process_manager = process_manager

        for profile in self.profiles:
            if profile in self.services:
                print b.warning + "WARNING: The profile %s conflicts with a service of the same name, this hides the profile and makes it unusable!!!" % profile + b.endc

    def service_data(self, service_name):
        if not service_name in self.services:
            raise ServiceManagerException("Unknown service: %s" % service_name)
        return self.services[service_name]

    def services_for_profile(self, profile):
        if self.is_profile(profile):
            return self.profiles[profile]
        raise ServiceManagerException("The requested profile '%s' does not exist" % profile)

    def has_service(self, service_name):
        return service_name in self.services

    def is_profile(self, profile):
        return profile in self.profiles

    def get_merged_services_config(self):
        # the services have been merged with templates at this point
        return self.services

    def merge_template_config(self):
        for service in self.services:
            template_key = "template"
            if template_key in self.services[service]:
                template_to_use = self.services[service][template_key]
                if template_to_use in self.templates:
                    copied = copy.deepcopy(self.templates[template_to_use]) #merge_dict(self.templates[template_to_use], self.services[service])
                    original_config = copy.deepcopy(self.services[service])
                    merge_dict(copied, original_config)
                    str_version = json.dumps(copied)
                    str_replaced = str_version.replace("${SERVICE-ID}", service)
                    new_config = json.loads(str_replaced)
                    self.services[service] = new_config #hehe, take that recursion! (O)1

    def describe(self):
        print "Services:"

        for service_name in collections.OrderedDict(sorted(self.services.items())):
            print "\t" + service_name.ljust(12) + " =>\t" + self.services[service_name]["name"]

        print "Profiles:"

        for profile_name in collections.OrderedDict(sorted(self.profiles.items())):
            print "\t" + profile_name.ljust(12) + " =>\t" + ", ".join(self.profiles[profile_name])

    def _read_json_config(self, filename):
        config_file = os.path.join(self.configuration_dir, filename)

        if not os.path.isfile(config_file):
            SmApplication.exit_with_error("Cannot find configuration file: %s" % config_file)

        try:
            with open(config_file) as f:
                return json.load(f)
        except Exception as e:
            SmApplication.exit_with_error("Unable to load configuration file '%s' due to exception: %s" % (config_file, str(e)))

    def _get_configuration_dir(self, configuration_dir_parameter):

        if configuration_dir_parameter:
            configuration_dir = configuration_dir_parameter
        else:
            configuration_dir = os.path.join(self.workspace, "service-manager-config")

        configuration_dir = os.path.abspath(configuration_dir)

        if not configuration_dir.endswith(os.sep):
            configuration_dir += os.sep

        if not os.path.isdir(configuration_dir):
            SmApplication.exit_with_error("Cannot find configuration directory: %s" % configuration_dir)

        return configuration_dir

    @staticmethod
    def _required_environment_directory(environment_variable, description_for_error):

        directory = os.environ.get(environment_variable, None)

        if not directory:
            SmApplication.exit_with_error("'%s' environment variable is required. You can add this to your ~/.bash_profile by adding the line %s=[%s]" %
                                          (environment_variable, environment_variable, description_for_error))

        directory = os.path.abspath(directory)

        if not os.path.isdir(directory):
            SmApplication.exit_with_error("'%s' environment variable points to non-existent directory: %s" % (environment_variable, directory))

        return directory

    @staticmethod
    def exit_with_error(message):
        print "Error: " + message
        sys.exit(1)

class SmContext():

    # Invocation context object - representing a call to sm.py, or a request received by SmServer

    MAX_TIME_TO_DIE_SECONDS = 3

    def __init__(self, application, test_id, offline=False, show_progress=True, request_specific_features=None):
        self.application = application
        self.test_id = test_id
        self.instance_id = if_not(self.test_id, "LOCAL")
        self.database_name_prefix = test_id
        self.offline = offline
        self.show_progress = show_progress
        self.is_test = test_id is not None
        self.features = unify_lists(request_specific_features, self.application.features)
        self.credentials = CredentialsResolver(self)
        self.process_manager = application.process_manager
        self.assets_versions = []

    def config_value(self, key, default=None):
        if key in self.application.config:
            return self.application.config[key]
        else:
            return default

    def exception(self, message):
        self.log(message)
        return ServiceManagerException(message)

    def log(self, message):
        if self.test_id:
            print "[%s] %s" % (self.test_id, message)
        else:
            print message

    def services(self):
        return (self.get_service(service_name) for service_name in self.application.services)

    def get_service(self, service_name):
        service_type = self.service_type(service_name)

        if service_type == "external":
            return SmExternalService(self, service_name)
        elif service_type == "dropwizard":
            return SmDropwizardService(self, service_name)
        elif service_type == "play":
            return SmPlayService(self, service_name)
        elif service_type == "assets":
            return SmPythonService(self, service_name)
        else:
            raise self.exception("Unknown service type '%s' for service '%s' - please check services.json" % (service_type, service_name))

    def drop_database_for_service(self, service_name):
        self._drop_database(self.database_name_prefix + "-" + service_name)

    def drop_database_for_test(self):
        self._drop_database(self.database_name_prefix)

    def _drop_database(self, database_name):
        c = Connection()
        try:
            if database_name in c.database_names():
                self.log("Dropping database: %s" % database_name)
                c.drop_database(database_name)
        finally:
            c.close()

    def service_data(self, service_name):
        return self.application.service_data(service_name)

    def get_microservice_target_path(self, service_name):
        data = self.service_data(service_name)
        return self.application.workspace + data["location"] + "/target/"

    def _create_extension(self, service_name, run_from):
        if self.service_type(service_name) == "play" or self.service_type(service_name) == "assets":
            ext = self.service_data(service_name)["binary"].get('ext', 'tgz')
            return "." + ext
        else:
            return "-%s-shaded.jar" % run_from

    def get_jar_filename(self, service_name, run_from):
        data = self.service_data(service_name)
        binary = data["binary"]
        artifact = binary["artifact"]
        extension = self._create_extension(service_name, run_from)
        return artifact + extension

    def assets_versions_to_start(self, version):
        self.assets_versions = self.assets_versions + version

    def kill(self, service_name=None):
        if service_name:
            self._kill_service(service_name)
        elif self.test_id:
            self._kill_test()
        else:
            self.kill_everything()

    def _kill_service(self, service_name):
        service = self.get_service(service_name)
        print "killing service name: " + service_name
        service.stop()

    def _kill_test(self):
        services_stopped = kill_by_test_id(self, False)
        seconds_remaining = SmContext.MAX_TIME_TO_DIE_SECONDS
        while seconds_remaining > 0 and test_has_running_processes(self):
            time.sleep(1)
            seconds_remaining -= 1
        services_stopped |= kill_by_test_id(self, True)
        self._clean_up_services(services_stopped)

    def kill_everything(self):
        for service_name in self.application.services:
            self._kill_service(service_name)

    def _clean_up_services(self, services):
        for service_name in services:
            self.get_service(service_name).clean_up()

    def has_service(self, service_name):
        return self.application.has_service(service_name)

    def service_type(self, service_name):
        service_type = self.service_data(service_name)["type"]
        if service_type not in ["dropwizard", "play", "external", "assets"]:
            raise self.exception("Unknown service type '%s' in services.json for service '%s'" % (service_type, service_name))
        return service_type

    def get_ports_used(self):
        ports_used = {}
        for service_name in self.application.services:
            service = self.application.services[service_name]
            if "defaultPort" in service:
                ports_used[service["defaultPort"]] = service_name
                if "defaultAdminPort" in service:
                    ports_used[service["defaultAdminPort"]] = service_name
        return ports_used

    def is_profile(self, profile):
        return self.application.is_profile(profile)

    def get_run_from_service_override_value_or_use_default(self, service, original_runfrom):
        if "always_run_from" in service.service_data:
            if validate_always_run_from(service.service_data["always_run_from"]):
                self.log("Service '%s' has been overridden to always use '%s' version" % (service.service_name, service.service_data["always_run_from"]))
                return service.service_data["always_run_from"]
        return original_runfrom

    def get_service_starter(self, service_name, run_from, proxy, classifier=None, service_mapping_ports=None, port=None, admin_port=None, version=None, append_args=None):
        service = self.get_service(service_name)
        run_from = self.get_run_from_service_override_value_or_use_default(service, run_from)

        if not service_mapping_ports:
            service_mapping_ports = {}

        service_type = self.service_type(service_name)

        if (not self.is_test) and service.is_started_on_default_port():
            print service_name + " is already running on its default port, not starting a new one"
            return None

        if service_type == "external":
            starter = SmExternalServiceStarter(self, service_name, append_args)
        elif service_type == "dropwizard":
            starter = SmDropwizardServiceStarter(self, service_name, run_from, port, admin_port, classifier, service_mapping_ports, version, proxy, append_args)
        elif service_type == "play":
            starter = SmPlayServiceStarter(self, service_name, run_from, port, classifier, service_mapping_ports, version, proxy, append_args)
        elif service_type == "assets":
            proxy = None
            starter = SmPythonServiceStarter(self, service_name, run_from, port, classifier, service_mapping_ports, version, proxy, append_args)
        else:
            raise self.exception("Unknown service type '%s' for service '%s' - please check services.json" % (service_type, service_name))

        return starter

    def start_service(self, service_name, run_from, proxy, classifier=None, service_mapping_ports=None, port=None, admin_port=None, version=None, appendArgs=None):
        service_starter = self.get_service_starter(service_name, run_from, proxy, classifier, service_mapping_ports, port, admin_port, version, appendArgs)
        feature_string = pretty_print_list(" with feature$s $list enabled", self.features)
        self.log("Starting '%s' from %s%s..." % (service_name, run_from, feature_string))
        service_process_id = service_starter.start()

        if service_process_id:
            feature_string = pretty_print_list(" and feature$s $list enabled", self.features)
            self.log("'%s' version '%s' started with PID = %d%s" % (service_name, version, service_process_id, feature_string))
        else:
            self.log("'%s' version does not appear to have started" % service_name)

        return service_process_id


text:
#ifndef BACKENDS_P4TOOLS_MODULES_TESTGEN_CORE_TARGET_H_
#define BACKENDS_P4TOOLS_MODULES_TESTGEN_CORE_TARGET_H_

#include <stdint.h>

#include <string>
#include <vector>

#include <boost/filesystem.hpp>
#include <boost/optional/optional.hpp>

#include "backends/p4tools/common/core/solver.h"
#include "backends/p4tools/common/core/target.h"
#include "ir/ir.h"
#include "ir/vector.h"

#include "backends/p4tools/modules/testgen/core/arch_spec.h"
#include "backends/p4tools/modules/testgen/core/exploration_strategy/exploration_strategy.h"
#include "backends/p4tools/modules/testgen/core/program_info.h"
#include "backends/p4tools/modules/testgen/core/small_step/cmd_stepper.h"
#include "backends/p4tools/modules/testgen/core/small_step/expr_stepper.h"
#include "backends/p4tools/modules/testgen/lib/execution_state.h"
#include "backends/p4tools/modules/testgen/lib/namespace_context.h"
#include "backends/p4tools/modules/testgen/lib/test_backend.h"

namespace P4Tools {

namespace P4Testgen {

class TestgenTarget : public Target {
 public:
    /// @returns the singleton instance for the current target.
    static const TestgenTarget& get();

    /// Produces a @ProgramInfo for the given P4 program.
    ///
    /// @returns nullptr if the program is not supported by this target.
    static const ProgramInfo* initProgram(const IR::P4Program* program) {
        return get().initProgram_impl(program);
    }

    /// Returns the test back end associated with this P4Testgen target.
    static TestBackEnd* getTestBackend(const ProgramInfo& programInfo, ExplorationStrategy& symbex,
                                       const boost::filesystem::path& testPath,
                                       boost::optional<uint32_t> seed) {
        return get().getTestBackend_impl(programInfo, symbex, testPath, seed);
    }

    /// The width of a port number, in bits.
    static int getPortNumWidth_bits() { return get().getPortNumWidth_bits_impl(); }

    /// Provides a CmdStepper implementation for this target.
    static CmdStepper* getCmdStepper(ExecutionState& state, AbstractSolver& solver,
                                     const ProgramInfo& programInfo) {
        return get().getCmdStepper_impl(state, solver, programInfo);
    }

    /// Provides a ExprStepper implementation for this target.
    static ExprStepper* getExprStepper(ExecutionState& state, AbstractSolver& solver,
                                       const ProgramInfo& programInfo) {
        return get().getExprStepper_impl(state, solver, programInfo);
    }

    /// A vector that maps the architecture parameters of each pipe to the corresponding
    /// global architecture variables. For example, this map specifies which parameter of each pipe
    /// refers to the input header.
    // The arch map needs to be public to be subclassed.
    /// @returns a reference to the architecture map defined in this target
    static const ArchSpec* getArchSpec() { return get().getArchSpecImpl(); }

 protected:
    /// @see @initProgram.
    const ProgramInfo* initProgram_impl(const IR::P4Program* program) const;

    /// @see @initProgram.
    virtual const ProgramInfo* initProgram_impl(const IR::P4Program* program,
                                                const IR::Declaration_Instance* mainDecl) const = 0;

    /// @see getPortNumWidth_bits.
    virtual int getPortNumWidth_bits_impl() const = 0;

    /// @see getTestBackend.
    virtual TestBackEnd* getTestBackend_impl(const ProgramInfo& programInfo,
                                             ExplorationStrategy& symbex,
                                             const boost::filesystem::path& testPath,
                                             boost::optional<uint32_t> seed) const = 0;

    /// @see getCmdStepper.
    virtual CmdStepper* getCmdStepper_impl(ExecutionState& state, AbstractSolver& solver,
                                           const ProgramInfo& programInfo) const = 0;

    /// @see getExprStepper.
    virtual ExprStepper* getExprStepper_impl(ExecutionState& state, AbstractSolver& solver,
                                             const ProgramInfo& programInfo) const = 0;

    /// @see getArchSpec
    virtual const ArchSpec* getArchSpecImpl() const = 0;

    /// Utility function. Converts the list of arguments @inputArgs to a list of type declarations
    ///  and appends the result to @v. Any names appearing in the arguments are
    /// resolved with @ns.
    //
    static void argumentsToTypeDeclarations(const NamespaceContext* ns,
                                            const IR::Vector<IR::Argument>* inputArgs,
                                            std::vector<const IR::Type_Declaration*>& resultDecls);

    explicit TestgenTarget(std::string deviceName, std::string archName);

 private:
};

}  // namespace P4Testgen

}  // namespace P4Tools

#endif /* BACKENDS_P4TOOLS_MODULES_TESTGEN_CORE_TARGET_H_ */


text:
<add description>

| Works with | Author(s) | Project URL(s) | PowerShell Gallery | Creation Date | Tags |
|------------|--------|-------------------|--------------------|---------------|------|
| <one or mutiple> | <author 1> (b \| <a href="https://twitter.com/<handle>" target="_blank">t) | [Github](urltoprojectGithub) \| [official project site](urltoofficialprojectsite) | [ModuleName on PowerShell Gallery](urltoPowerShellGalleryModule) | <MonthFullName Year> | <one or mutiple> |
____
### Shared blog posts:
<author 1 name> (b | <a href="https://twitter.com/<handle>" target="_blank">t)
- [Another Blog Post Title](URLToBlogPost) @ <Blog post date YYYY-MM-DD>
- [Blog Post Title](URLToBlogPost) @ <Blog post date YYYY-MM-DD>

<author 2 name> (b | <a href="https://twitter.com/<handle>" target="_blank">t)
- [Blog Post Title](URLToBlogPost) @ <Blog post date YYYY-MM-DD>
____
### Shared videos:
<author 1 name> (b | <a href="https://twitter.com/<handle>" target="_blank">t)
- [Blog Post Title](URLToBlogPost) @ <Blog post date YYYY-MM-DD> - Sound: <Which language is used on the video example pt-PT or us-US>

<author 2 name> (b | <a href="https://twitter.com/<handle>" target="_blank">t)
- [Blog Post Title](URLToBlogPost) @ <Blog post date YYYY-MM-DD> - Sound: <Which language is used on the video example pt-PT or us-US>