text:
#pragma once

#include <algorithm>
#include <map>
#include <type_traits>

// struct to allow partial specialisation for enums
template <typename T, bool isEnum = std::is_enum<T>::value>
struct TypeConversion
{
  static swig_type_info *GetTypeInfo()
  {
    static swig_type_info *cached_type_info = NULL;

    if(cached_type_info)
      return cached_type_info;

    std::string baseTypeName = TypeName<T>();
    baseTypeName += " *";
    cached_type_info = SWIG_TypeQuery(baseTypeName.c_str());

    return cached_type_info;
  }

  static int ConvertFromPy(PyObject *in, T &out)
  {
    swig_type_info *type_info = GetTypeInfo();
    if(type_info == NULL)
      return SWIG_ERROR;

    T *ptr = NULL;
    int res = SWIG_ConvertPtr(in, (void **)&ptr, type_info, 0);
    if(SWIG_IsOK(res))
      out = *ptr;

    return res;
  }

  static PyObject *ConvertToPy(const T &in)
  {
    swig_type_info *type_info = GetTypeInfo();
    if(type_info == NULL)
      return NULL;

    T *pyCopy = new T(in);
    return SWIG_InternalNewPointerObj((void *)pyCopy, type_info, SWIG_POINTER_OWN);
  }
};

// specialisations for pointer types (opaque handles to be moved not copied)
template <typename Opaque>
struct TypeConversion<Opaque *, false>
{
  static swig_type_info *GetTypeInfo()
  {
    static swig_type_info *cached_type_info = NULL;

    if(cached_type_info)
      return cached_type_info;

    std::string baseTypeName = TypeName<Opaque>();
    baseTypeName += " *";
    cached_type_info = SWIG_TypeQuery(baseTypeName.c_str());

    return cached_type_info;
  }

  static int ConvertFromPy(PyObject *in, Opaque *&out)
  {
    swig_type_info *type_info = GetTypeInfo();
    if(type_info == NULL)
      return SWIG_ERROR;

    Opaque *ptr = NULL;
    int res = SWIG_ConvertPtr(in, (void **)&ptr, type_info, 0);
    if(SWIG_IsOK(res))
      out = ptr;

    return res;
  }

  static PyObject *ConvertToPy(const Opaque *&in)
  {
    swig_type_info *type_info = GetTypeInfo();
    if(type_info == NULL)
      return NULL;

    return SWIG_InternalNewPointerObj((void *)in, type_info, 0);
  }

  static PyObject *ConvertToPy(Opaque *in) { return ConvertToPy((const Opaque *&)in); }
};

// specialisations for basic types
template <>
struct TypeConversion<bool, false>
{
  static int ConvertFromPy(PyObject *in, bool &out)
  {
    if(!PyBool_Check(in))
      return SWIG_TypeError;

    if(in == Py_True)
      out = true;
    else
      out = false;

    return SWIG_OK;
  }

  static PyObject *ConvertToPy(const bool &in)
  {
    if(in)
    {
      Py_IncRef(Py_True);
      return Py_True;
    }
    else
    {
      Py_IncRef(Py_False);
      return Py_False;
    }
  }
};

template <>
struct TypeConversion<uint8_t, false>
{
  static int ConvertFromPy(PyObject *in, uint8_t &out)
  {
    if(!PyLong_Check(in))
      return SWIG_TypeError;

    uint32_t longval = PyLong_AsUnsignedLong(in);

    if(PyErr_Occurred() || longval > 0xff)
      return SWIG_OverflowError;

    out = uint8_t(longval & 0xff);

    return SWIG_OK;
  }

  static PyObject *ConvertToPy(const uint8_t &in) { return PyLong_FromUnsignedLong(in); }
};

template <>
struct TypeConversion<uint16_t, false>
{
  static int ConvertFromPy(PyObject *in, uint16_t &out)
  {
    if(!PyLong_Check(in))
      return SWIG_TypeError;

    uint32_t longval = PyLong_AsUnsignedLong(in);

    if(PyErr_Occurred() || longval > 0xffff)
      return SWIG_OverflowError;

    out = uint16_t(longval & 0xff);

    return SWIG_OK;
  }

  static PyObject *ConvertToPy(const uint16_t &in) { return PyLong_FromUnsignedLong(in); }
};

template <>
struct TypeConversion<uint32_t, false>
{
  static int ConvertFromPy(PyObject *in, uint32_t &out)
  {
    if(!PyLong_Check(in))
      return SWIG_TypeError;

    out = PyLong_AsUnsignedLong(in);

    if(PyErr_Occurred())
      return SWIG_OverflowError;

    return SWIG_OK;
  }

  static PyObject *ConvertToPy(const uint32_t &in) { return PyLong_FromUnsignedLong(in); }
};

template <>
struct TypeConversion<int32_t, false>
{
  static int ConvertFromPy(PyObject *in, int32_t &out)
  {
    if(!PyLong_Check(in))
      return SWIG_TypeError;

    out = PyLong_AsLong(in);

    if(PyErr_Occurred())
      return SWIG_OverflowError;

    return SWIG_OK;
  }

  static PyObject *ConvertToPy(const int32_t &in) { return PyLong_FromLong(in); }
};

template <>
struct TypeConversion<uint64_t, false>
{
  static int ConvertFromPy(PyObject *in, uint64_t &out)
  {
    if(!PyLong_Check(in))
      return SWIG_TypeError;

    out = PyLong_AsUnsignedLongLong(in);

    if(PyErr_Occurred())
      return SWIG_OverflowError;

    return SWIG_OK;
  }

  static PyObject *ConvertToPy(const uint64_t &in) { return PyLong_FromUnsignedLongLong(in); }
};

template <>
struct TypeConversion<float, false>
{
  static int ConvertFromPy(PyObject *in, float &out)
  {
    if(!PyFloat_Check(in))
      return SWIG_TypeError;

    out = (float)PyFloat_AsDouble(in);

    if(PyErr_Occurred())
      return SWIG_OverflowError;

    return SWIG_OK;
  }

  static PyObject *ConvertToPy(const float &in) { return PyFloat_FromDouble(in); }
};

template <>
struct TypeConversion<double, false>
{
  static int ConvertFromPy(PyObject *in, double &out)
  {
    if(!PyFloat_Check(in))
      return SWIG_TypeError;

    out = PyFloat_AsDouble(in);

    if(PyErr_Occurred())
      return SWIG_OverflowError;

    return SWIG_OK;
  }

  static PyObject *ConvertToPy(const double &in) { return PyFloat_FromDouble(in); }
};

// partial specialisation for enums, we just convert as their underlying type,
// whatever integer size that happens to be
template <typename T>
struct TypeConversion<T, true>
{
  typedef typename std::underlying_type<T>::type etype;

  static int ConvertFromPy(PyObject *in, T &out)
  {
    etype int_out = 0;
    int ret = TypeConversion<etype>::ConvertFromPy(in, int_out);
    out = T(int_out);
    return ret;
  }

  static PyObject *ConvertToPy(const T &in)
  {
    return TypeConversion<etype>::ConvertToPy(etype(in));
  }
};

// specialisation for datetime
template <>
struct TypeConversion<rdcdatetime, false>
{
  static int ConvertFromPy(PyObject *in, rdcdatetime &out)
  {
    if(!PyDateTime_Check(in))
      return SWIG_TypeError;

    out.year = PyDateTime_GET_YEAR(in);
    out.month = PyDateTime_GET_MONTH(in);
    out.day = PyDateTime_GET_DAY(in);
    out.hour = PyDateTime_DATE_GET_HOUR(in);
    out.minute = PyDateTime_DATE_GET_MINUTE(in);
    out.second = PyDateTime_DATE_GET_SECOND(in);
    out.microsecond = PyDateTime_TIME_GET_MICROSECOND(in);

    return SWIG_OK;
  }

  static PyObject *ConvertToPy(const rdcdatetime &in)
  {
    return PyDateTime_FromDateAndTime(in.year, in.month, in.day, in.hour, in.minute, in.second,
                                      in.microsecond);
  }
};

// specialisation for pair
template <typename A, typename B>
struct TypeConversion<rdcpair<A, B>, false>
{
  static int ConvertFromPy(PyObject *in, rdcpair<A, B> &out, int *failIdx)
  {
    if(!PyTuple_Check(in))
      return SWIG_TypeError;

    Py_ssize_t size = PyTuple_Size(in);

    if(size != 2)
      return SWIG_TypeError;

    int ret = TypeConversion<A>::ConvertFromPy(PyTuple_GetItem(in, 0), out.first);

    if(!SWIG_IsOK(ret))
    {
      if(failIdx)
        *failIdx = 0;
      return ret;
    }

    ret = TypeConversion<B>::ConvertFromPy(PyTuple_GetItem(in, 1), out.second);

    if(!SWIG_IsOK(ret))
    {
      if(failIdx)
        *failIdx = 1;
      return ret;
    }

    return ret;
  }

  static int ConvertFromPy(PyObject *in, rdcpair<A, B> &out)
  {
    return ConvertFromPy(in, out, NULL);
  }

  static PyObject *ConvertToPy(const rdcpair<A, B> &in, int *failIdx)
  {
    PyObject *first = TypeConversion<A>::ConvertToPy(in.first);
    if(!first)
    {
      if(failIdx)
        *failIdx = 0;
      return NULL;
    }

    PyObject *second = TypeConversion<B>::ConvertToPy(in.second);
    if(!second)
    {
      if(failIdx)
        *failIdx = 1;
      return NULL;
    }

    PyObject *ret = PyTuple_New(2);
    if(!ret)
      return NULL;

    PyTuple_SetItem(ret, 0, first);
    PyTuple_SetItem(ret, 1, second);

    return ret;
  }

  static PyObject *ConvertToPy(const rdcpair<A, B> &in) { return ConvertToPy(in, NULL); }
};

// specialisation for bytebuf
template <>
struct TypeConversion<bytebuf, false>
{
  // we add some extra parameters so the typemaps for array can use these to get
  // nicer failure error messages out with the index that failed
  static int ConvertFromPy(PyObject *in, bytebuf &out, int *failIdx)
  {
    if(!PyBytes_Check(in))
      return SWIG_TypeError;

    Py_ssize_t len = PyBytes_Size(in);

    out.resize((size_t)len);
    memcpy(out.data(), PyBytes_AsString(in), out.size());

    return SWIG_OK;
  }

  static int ConvertFromPy(PyObject *in, bytebuf &out) { return ConvertFromPy(in, out, NULL); }
  static PyObject *ConvertToPyInPlace(PyObject *list, const bytebuf &in, int *failIdx)
  {
    // can't modify bytes objects
    return SWIG_Py_Void();
  }

  static PyObject *ConvertToPy(const bytebuf &in, int *failIdx)
  {
    return PyBytes_FromStringAndSize((const char *)in.data(), (Py_ssize_t)in.size());
  }

  static PyObject *ConvertToPy(const bytebuf &in) { return ConvertToPy(in, NULL); }
};

// specialisation for array
template <typename U>
struct TypeConversion<rdcarray<U>, false>
{
  static swig_type_info *GetTypeInfo()
  {
    static swig_type_info *cached_type_info = NULL;
    static std::string typeName = std::string("rdcarray < ") + TypeName<U>() + " > *";

    if(cached_type_info)
      return cached_type_info;

    cached_type_info = SWIG_TypeQuery(typeName.c_str());

    return cached_type_info;
  }

  // we add some extra parameters so the typemaps for array can use these to get
  // nicer failure error messages out with the index that failed
  static int ConvertFromPy(PyObject *in, rdcarray<U> &out, int *failIdx)
  {
    if(!PyList_Check(in))
      return SWIG_TypeError;

    out.resize((size_t)PyList_Size(in));

    for(int i = 0; i < out.count(); i++)
    {
      int ret = TypeConversion<U>::ConvertFromPy(PyList_GetItem(in, i), out[i]);
      if(!SWIG_IsOK(ret))
      {
        if(failIdx)
          *failIdx = i;
        return ret;
      }
    }

    return SWIG_OK;
  }

  static int ConvertFromPy(PyObject *in, rdcarray<U> &out) { return ConvertFromPy(in, out, NULL); }
  static PyObject *ConvertToPyInPlace(PyObject *list, const rdcarray<U> &in, int *failIdx)
  {
    for(int i = 0; i < in.count(); i++)
    {
      PyObject *elem = TypeConversion<U>::ConvertToPy(in[i]);

      if(elem)
      {
        PyList_Append(list, elem);
        // release our reference
        Py_DecRef(elem);
      }
      else
      {
        if(failIdx)
          *failIdx = i;

        return NULL;
      }
    }

    return list;
  }

  static PyObject *ConvertToPy(const rdcarray<U> &in, int *failIdx)
  {
    PyObject *list = PyList_New(0);
    if(!list)
      return NULL;

    PyObject *ret = ConvertToPyInPlace(list, in, failIdx);

    // if a failure happened, don't leak the list we created
    if(!ret)
      Py_XDECREF(list);

    return ret;
  }

  static PyObject *ConvertToPy(const rdcarray<U> &in) { return ConvertToPy(in, NULL); }
};

// specialisation for string
template <>
struct TypeConversion<rdcstr, false>
{
  static swig_type_info *GetTypeInfo()
  {
    static swig_type_info *cached_type_info = NULL;

    if(cached_type_info)
      return cached_type_info;

    cached_type_info = SWIG_TypeQuery("rdcstr *");

    return cached_type_info;
  }

  static int ConvertFromPy(PyObject *in, rdcstr &out)
  {
    if(PyUnicode_Check(in))
    {
      PyObject *bytes = PyUnicode_AsUTF8String(in);

      if(!bytes)
        return SWIG_ERROR;

      char *buf = NULL;
      Py_ssize_t size = 0;

      int ret = PyBytes_AsStringAndSize(bytes, &buf, &size);

      if(ret == 0)
      {
        out.assign(buf, size);

        Py_DecRef(bytes);

        return SWIG_OK;
      }

      Py_DecRef(bytes);

      return SWIG_ERROR;
    }

    swig_type_info *type_info = GetTypeInfo();
    if(!type_info)
      return SWIG_ERROR;

    rdcstr *ptr = NULL;
    int res = SWIG_ConvertPtr(in, (void **)&ptr, type_info, 0);
    if(SWIG_IsOK(res))
      out = *ptr;

    return res;
  }

  static PyObject *ConvertToPy(const rdcstr &in)
  {
    return PyUnicode_FromStringAndSize(in.c_str(), in.size());
  }
};

#include "structured_conversion.h"

// free functions forward to struct
template <typename T>
int ConvertFromPy(PyObject *in, T &out)
{
  return TypeConversion<T>::ConvertFromPy(in, out);
}

template <typename T>
PyObject *ConvertToPy(const T &in)
{
  return TypeConversion<T>::ConvertToPy(in);
}

namespace
{
template <typename T, bool is_pointer = std::is_pointer<T>::value>
struct pointer_unwrap;

template <typename T>
struct pointer_unwrap<T, false>
{
  static void tempset(T &ptr, T *tempobj) {}
  static void tempalloc(T &ptr, unsigned char *tempmem) {}
  static void tempdealloc(T &ptr) {}
  static T &indirect(T &ptr) { return ptr; }
};

template <typename T>
struct pointer_unwrap<T, true>
{
  typedef typename std::remove_pointer<T>::type U;

  static void tempset(U *&ptr, U *tempobj) { ptr = tempobj; }
  static void tempalloc(U *&ptr, unsigned char *tempmem) { ptr = new(tempmem) U; }
  static void tempdealloc(U *ptr)
  {
    if(ptr)
      ptr->~U();
  }
  static U &indirect(U *ptr) { return *ptr; }
};
};

template <typename T>
inline void tempalloc(T &ptr, unsigned char *tempmem)
{
  pointer_unwrap<T>::tempalloc(ptr, tempmem);
}

template <typename T, typename U>
inline void tempset(T &ptr, U *tempobj)
{
  pointer_unwrap<T>::tempset(ptr, tempobj);
}

template <typename T>
inline void tempdealloc(T ptr)
{
  pointer_unwrap<T>::tempdealloc(ptr);
}

template <typename T>
inline typename std::remove_pointer<T>::type &indirect(T &ptr)
{
  return pointer_unwrap<T>::indirect(ptr);
}

#include "function_conversion.h"

#include "container_handling.h"

#include "ext_refcounts.h"


text:
function HookStep(keyword) {
  var Cucumber = require('../../cucumber');
  var self = Cucumber.Ast.Step(keyword, HookStep.NAME, global.CUKE_LAST_CODE_PATH, HookStep.UNDEFINED_LINE);
  var hook;

  self.isHidden = function isHidden() {
    return true;
  };

  self.hasUri = function hasUri() {
    return false;
  };

  self.setHook = function setHook(newHook) {
    hook = newHook;
  };

  self.getStepDefinition = function getStepDefinition() {
    return hook;
  };

  return self;
}

HookStep.NAME           = undefined;
HookStep.UNDEFINED_URI  = undefined;
HookStep.UNDEFINED_LINE = undefined;

module.exports = HookStep;

redpajama_set_name: RedPajamaGithub


text:
<?php $this->load->view('admin/common_header');?>
<link rel="stylesheet" href="/static/css/appmsg.css" media="screen" />
<link rel="stylesheet" href="/static/css/uploadify.css" media="screen" />

单图文

        <?php if($keywords == 'first_follow'){?>

<button class="btn btn-success btn-xs" onclick="location.href='/admin/first_follow'">纯文本</button>

<button class="btn btn-success btn-xs" onclick="location.href='/admin/multiply_material_manage/first_follow'">多图文</button>

        <?php }?>

						<?php if ($material){ echo $material->title;}else{?>标题<?php }?>

						<?php if ($material){ echo $material->createtime;}else{?>2013-06-25<?php }?>

						<p class="default-tip" <?php if ($material){ ?>style="display: none;"<?php }?>>封面图片

						<img class="i-img"  <?php if ($material){ ?>src="<?php echo $material->coverurl;}?>" style="">

<?php if ($material){ echo $material->summary;}?>

					<form id="appmsg-form" class="form-horizontal form-label-left">

                      标题 *

                        <input type="text" id="title" name="title" required="required" value="<?php if ($material){ echo $material->title;}?>" class="form-control col-md-4 col-xs-12">

							封面

										<input id="file_upload" class="file_upload" name="file_upload" type="file" />
										<input id="coverurl" value="<?php if ($material){ echo $material->coverurl;}?>" name="coverurl" type="hidden" />

大图片建议尺寸:700像素 * 300像素

									<p id="imgArea" class="cover-bd" <?php if(!$material){?>style="display: none;"<?php }?>>
									<img src="<?php if ($material){ echo $material->coverurl;}?>" id="img">
									删除

					  	<div id="desc-block" <?php if ($material){ if (!$material->summary){?> style="display: none;" <?php }}?> class="item form-group">
							摘要

								<textarea name="summary" id="summary" class="msg-txta"><?php if ($material){ echo $material->summary;}?></textarea>

						正文

					  	<div id="url-block" <?php if ($material){ if (!$material->source_url){?>style="display: none;"<?php }}?> class="item form-group">
							来源

								<input type="text" id="source_url" class="form-control col-md-4 col-xs-12" value="<?php if ($material){ echo $material->source_url;}?>"  name="source_url" />

							关键词*

						    	<input type="text" value="<?php echo $keywords;?>" id="keywords" class="form-control col-md-4 col-xs-12" name="keywords" />

                        <button class="btn btn-success" type="submit">Submit</button>
                        <button class="btn btn-primary form_go_back" type="button">Back</button>

					    <input id="m_id" name="m_id" type="hidden" value="<?php  echo $m_id; ?>" />
					</form>

<?php $this->load->view('admin/common_footer');?>


text:
import { RotateCounterclockwiseAlt32 } from "../../";

export = RotateCounterclockwiseAlt32;


text:
/* globals module require */
"use strict";
module.exports = (server, userController) => {
    server.post("/api/users", userController.createUser);
    server.post("/api/authenticate", userController.loginLocal);
    server.get("/api/users", userController.viewAllUsers);
    server.get("/api/profile/:name", userController.viewUserByName);
};


text:
package com.quinn.githubknife.presenter;

import android.content.Context;

import com.quinn.githubknife.view.ListFragmentView;

/**
 * Created by Quinn on 9/25/15.
 */
public class BranchesPresenterImpl extends PresenterAdapter{

    public static final String TAG = BranchesPresenterImpl.class.getSimpleName();

    public BranchesPresenterImpl(Context context, ListFragmentView view){
        super(context, view);
    }

    @Override
    public void onPageLoad(String owner,String repo,int page){
        super.onPageLoad(owner,repo,page);
        interactor.loadBranches(owner, repo);
    }
}


text:
from etk.timeseries.annotation.table_processor import parsed_table
from etk.timeseries.annotation.utility import column_orientation
from etk.timeseries.annotation import date_utilities

class complex_table(parsed_table):
    # finding the overlapp in the time block based on monotonicity of the time block
    @classmethod
    def check_for_overlapping_time(cls, date_block, orientation, raw_sheet):
        check_points = []
        is_increasing = True
        if orientation == column_orientation:  # times are in columns
            check_points.append(date_block.upper_row)
            if date_block.lower_row - date_block.upper_row >= 2:
                d = date_utilities.parse_row_as_date(
                    raw_sheet[date_block.upper_row][date_block.left_col:date_block.right_col])
                d2 = date_utilities.parse_row_as_date(
                    raw_sheet[date_block.upper_row + 1][date_block.left_col:date_block.right_col])
                is_increasing = date_utilities.is_greater(d, d2)
            for row in range(date_block.upper_row, date_block.lower_row - 1):
                d = date_utilities.parse_row_as_date(raw_sheet[row][date_block.left_col:date_block.right_col])

                d2 = date_utilities.parse_row_as_date(raw_sheet[row + 1][date_block.left_col:date_block.right_col])
                if not date_utilities.is_greater(d, d2) and is_increasing:
                    check_points.append(row + 1)
                if not date_utilities.is_greater(d2, d) and not is_increasing:
                    check_points.append(row + 1)
            check_points.append(date_block.lower_row)
        else:
            check_points.append(date_block.left_col)
            check_points.append(date_block.right_col)
        # ToDO: write the same process for the row_orientation
        if len(check_points) == 2:
            return False, check_points

        return True, check_points


text:
"""This example creates a creative group associated with a given advertiser.

To get an advertiser ID, run get_advertisers.py. Valid group numbers are limited
to 1 or 2.

The LoadFromStorage method is pulling credentials and properties from a
"googleads.yaml" file. By default, it looks for this file in your home
directory. For more information, see the "Caching authentication information"
section of our README.

"""

# Import appropriate modules from the client library.
from googleads import dfa

ADVERTISER_ID = 'INSERT_ADVERTISER_ID_HERE'
GROUP_NUMBER = 'INSERT_GROUP_NUMBER_HERE'
CREATIVE_GROUP_NAME = 'INSERT_CREATIVE_GROUP_NAME_HERE'

def main(client, advertiser_id, group_number, creative_group_name):
  # Initialize appropriate service.
  creative_group_service = client.GetService(
      'creativegroup', 'v1.20', 'https://advertisersapitest.doubleclick.net')

  # Construct and save creative group.
  creative_group = {
      'name': creative_group_name,
      'id': '-1',
      'advertiserId': advertiser_id,
      'groupNumber': group_number
  }
  result = creative_group_service.saveCreativeGroup(creative_group)

  # Display results.
  print 'Creative group with ID \'%s\' was created.' % result['id']

if __name__ == '__main__':
  # Initialize client object.
  dfa_client = dfa.DfaClient.LoadFromStorage()
  main(dfa_client, ADVERTISER_ID, GROUP_NUMBER, CREATIVE_GROUP_NAME)


text:
const ProtocolAction = require('./_base-action.js');

/**
 * Navigate forward in the browser history, if possible (the equivalent of hitting the browser forward button).
 *
 * @link /#back
 * @param {function} [callback] Optional callback function to be called when the command finishes.
 * @api protocol.navigation
 */
module.exports = class Action extends ProtocolAction {
  command(callback) {
    return this.transportActions.navigateForward(callback);
  }
};


text:
<!DOCTYPE html>

  This test is verifying that when the focus is removed from an element we
  correctly invalidate continuations and remove the focus ring.

  If this test passes, you should see no focus ring.

CONTENTS


text:
import abc
import numpy as np
from scipy.misc import factorial
from scipy.special import poch, gammaln
from scipy.stats import poisson
from scipy._lib._util import check_random_state
from scipy.stats._multivariate import _squeeze_output

from ..utils import _logsumexp

class GenericProcess(object):
    """
    Class which encapsulates common functionality between all process models.
    """

    __metaclass__  = abc.ABCMeta

    default_sampler = None

    def __init__(self, mixture_model, sampler=None, seed=None):

        super(GenericProcess, self).__init__()

        self._mixture_model = self._check_mixture_model(mixture_model)
        self._sampler = self._check_sampler(sampler)
        self._random_state = check_random_state(seed)

    def _check_mixture_model(self, mixture_model):

        from .mixtures import GenericMixture

        if issubclass(mixture_model, GenericMixture):
            return mixture_model()

        if isinstance(mixture_model, GenericMixture):
            return mixture_model

        raise ValueError("'mixture_model' must be a mixture model."
                         " Got mixture_model = %r" % mixture_model)

    @property
    def mixture_model(self):

        return self._mixture_model

    def _check_sampler(self, sampler):

        if sampler is None:
            return self.default_sampler(self)

        from ..samplers import GenericSampler

        if issubclass(sampler, GenericSampler):
            return sampler(self)

        if isinstance(sampler, GenericSampler):
            if not sampler.process_model == self:
                raise ValueError('%r was initialized with a different process'
                                 ' model and is thus incompatible.' % sampler)
            return sampler

        raise ValueError("'sampler' must be a compatible sampler."
                         " Got sampler = %r" % sampler)

    @property
    def random_state(self):
        """
        Get or set the RandomState object for generating random variates.
        This can be either None or an existing RandomState object.
        If None (or np.random), use the RandomState singleton used by
        np.random. If already a RandomState instance, use it.
        If an int, use a new RandomState instance seeded with seed.
        """
        return self._random_state

    @random_state.setter
    def random_state(self, seed):

        self._random_state = check_random_state(seed)

    def _get_random_state(self, random_state):

        if random_state is not None:
            return check_random_state(random_state)
        else:
            return self._random_state

    @property
    def sampler(self):

        return self._sampler

    @sampler.setter
    def sampler(self, sampler):

        self._sampler = self._check_sampler(sampler)

    def _get_sampler(self, sampler):

        if sampler is not None:
            return self._check_sampler(sampler)
        else:
            return self._sampler

    @staticmethod
    def _process_size(size):

        size = np.asarray(size, dtype=int)

        if size.ndim == 0:
            n = np.asscalar(size)
            size = np.asarray([1])
        elif size.ndim == 1:
            n = size[0]
            if len(size) == 1:
                size = np.asarray([1])
            elif len(size) > 1:
                size = size[1:]
        elif size.ndim > 1:
            raise ValueError('Size must be an integer or tuple of integers;'
                             ' thus must have dimension <= 1.'
                             ' Got size.ndim = %s' % str(tuple(size)))

        m = size.prod()
        shape = tuple(size)

        return n, m, shape

    class _Param(object):

        __metaclass__  = abc.ABCMeta

        def __init__(self, random_state):

            self._random_state = check_random_state(random_state)

        @abc.abstractmethod
        def dump(self):

            raise NotImplementedError

    class DrawParam(_Param):

        __metaclass__  = abc.ABCMeta

        @abc.abstractmethod
        def log_prior(self, n, n_c):

            raise NotImplementedError

    class InferParam(_Param):

        __metaclass__  = abc.ABCMeta

        @abc.abstractmethod
        def log_prior(self, n, n_c, m):

            raise NotImplementedError

        @abc.abstractmethod
        def iterate(self, n, k):

            raise NotImplementedError

    def draw(self, size, random_state=None):
        """
        Draw from the Chinese restaurant process.
        """

        mm = self._mixture_model

        n, m, shape = self._process_size(size)

        random_state = self._get_random_state(random_state)

        # Array of vectors of component indicator variables. In the beginning,
        # assign every example to the component with indicator value 0
        c_n = np.empty(m*n, dtype=int).reshape((shape+(n,)))

        # Maximum number of components is number of examples
        c_max = n

        # Array of examples
        # TODO: Make this truly model-agnostic, i.e. get rid of mm.dim and
        #       dtype=float
        x_n = np.empty((m*n*mm.dim), dtype=float).reshape((shape+(n,mm.dim)))

        for index in np.ndindex(shape):
            process_param = self.DrawParam(self, random_state)

            n_c = np.zeros(c_max, dtype=int)

            active_components = set()
            inactive_components = set(range(c_max))

            # Lazily instantiate the components
            mixture_params = [mm.DrawParam(mm, random_state)
                    for _ in range(c_max)]

            for i in range(n):
                # Draw a component k for example i from the Chinese restaurant
                # process

                # Get a new component from the stack
                prop_k = inactive_components.pop()
                active_components.add(prop_k)

                # Initialize and populate the log probability accumulator
                log_dist = np.empty(c_max, dtype=float)
                log_dist.fill(-np.inf)
                for k in active_components:
                    # Calculate the process prior
                    log_dist[k] = process_param.log_prior(i+1, n_c[k])

                # Sample from log_dist. Normalization is required
                log_dist -= _logsumexp(c_max, log_dist)
                next_k = random_state.choice(a=c_max, p=np.exp(log_dist))

                # cdf = np.cumsum(np.exp(log_dist - log_dist.max()))
                # r = random_state.uniform(size=1) * cdf[-1]
                # [next_k] = cdf.searchsorted(r)

                c_n[index+(i,)] = next_k

                # Update component counter
                n_c[next_k] += 1

                # New components are instantiated automatically when needed
                x_n[index+(i,)] = mixture_params[next_k].draw_x_n()

                # Cleanup
                if next_k != prop_k:
                    active_components.remove(prop_k)
                    inactive_components.add(prop_k)

        # TODO: Make it possible to return the component parameters

        return _squeeze_output(x_n), _squeeze_output(c_n)

    def infer(self, *args, **kwargs):

        sampler = self._get_sampler(kwargs.pop('sampler', None))

        c_n, phi_c = sampler.infer(*args, **kwargs)

        return _squeeze_output(c_n), phi_c

class DP(GenericProcess):
    """
    Dirichlet process.

    Parameters
    ----------
    alpha : None or float, optional
        alpha hyperparameter
    a : None or float, optional
        shape of Gamma hyperprior on alpha
    b : None or float, optional
        scale of Gamma hyperprior on alpha
    random_state : None or int or np.random.RandomState instance, optional
        If int or RandomState, use it for drawing the random variates.
        If None (or np.random), the global np.random state is used.
        Default is None.
    """

    def __init__(self, mixture_model, alpha=1.0, a=None, b=None, sampler=None,
            seed=None):

        from ..samplers import GibbsSampler
        self.default_sampler = GibbsSampler

        super(DP, self).__init__(mixture_model, sampler, seed)

        self.alpha, self.a, self.b = self._check_parameters(alpha, a, b)

    @staticmethod
    def _check_parameters(alpha, a, b):

        for (var, varname) in zip([alpha, a, b], ['alpha', 'a', 'b']):
            if var is not None:
                if not np.isscalar(var):
                    raise ValueError("Float '%s' must be a scalar." % varname)
                var = float(var)
                if var <= 0.0:
                    raise ValueError("Float '%s' must be larger than zero,"
                                     " but %s = %f" % (varname, varname, var))

        if alpha is None:
            if a is None or b is None:
                alpha = 1.0

        return alpha, a, b

    @classmethod
    def _check_process_model(cls, process_model):

        if not isinstance(process_model, cls):
            raise ValueError("'process_model' must be a Dirichlet"
                             " process (DP) model."
                             " Got process_model = %r" % process_model)

        return process_model

    def _ms_log_prior_pre(self, n, t, tp, process_param):
        """
        First term in the logarithm of the prior appearing in the M-H
        acceptance ratio used by the merge-split samplers.
        """

        ret = (t-tp) * np.log(process_param.alpha)

        return ret

    def _ms_log_prior_post(self, nc, process_param):
        """
        Second term in the logarithm of the prior appearing in the M-H
        acceptance ratio used by the merge-split samplers.
        """

        ret = gammaln(nc)

        return ret

    class DrawParam(GenericProcess.DrawParam):

        def __init__(self, process_model, random_state):

            super(DP.DrawParam, self).__init__(random_state)

            self._process_model = DP._check_process_model(process_model)

            self._alpha = None

        @property
        def alpha(self):

            if self._alpha is None:
                pm = self._process_model

                # TODO: Use try-except instead?
                if pm.a is not None and pm.b is not None:
                    self._alpha = self._random_state.gamma(pm.a, pm.b)
                else:
                    self._alpha = pm.alpha

            return self._alpha

        def log_prior(self, n, n_c):
            """
            Return the logarithm of the conditional prior.
            """

            if n_c == 0:
                return np.log(self.alpha)
            elif n_c > 0:
                return np.log(n_c)
            else:
                raise ValueError("'n_c' must be non-negative.")

        def dump(self):

            return self._alpha

    class InferParam(GenericProcess.InferParam):

        def __init__(self, process_model, random_state):

            super(DP.InferParam, self).__init__(random_state)

            self._process_model = DP._check_process_model(process_model)

            self._alpha = None

        @property
        def alpha(self):

            if self._alpha is None:
                return self._process_model.alpha
            else:
                return self._alpha

        def log_prior(self, n, n_c, m):
            """
            Return the logarithm of the conditional prior.
            """

            if n_c == 0:
                # The conditional prior of a new component is proportional to
                # alpha
                return np.log(self.alpha) - np.log(m)
            elif n_c > 0:
                # The conditional priors of all existing components are
                # proportional to the number of examples assigned to them
                return np.log(n_c)
            else:
                raise ValueError("'n_c' must be non-negative.")

        def iterate(self, n, k):
            """
            Sample a new value for alpha.
            """

            pm = self._process_model

            if pm.a is not None and pm.b is not None:

                x = self._random_state.beta(alpha+1.0, n)

                shape = pm.a + k - 1.0
                scale = pm.b - np.log(x)

                pi_x = shape / (shape + n * scale)

                alpha = pi_x * self._random_state.gamma(shape+1.0, scale)
                alpha += (1-pi_x) * self._random_state.gamma(shape, scale)

                self._alpha = alpha

        def dump(self):

            return self._alpha

class MFM(GenericProcess):
    """
    Mixture of finite mixtures.

    Parameters
    ----------
    gamma : None or float, optional
        gamma hyperparameter
    mu : None or float, optional
        parameter of the Poisson distribution for the number of components
    random_state : None or int or np.random.RandomState instance, optional
        If int or RandomState, use it for drawing the random variates.
        If None (or np.random), the global np.random state is used.
        Default is None.
    """

    def __init__(self, mixture_model, gamma=1.0, mu=1.0, sampler=None,
            seed=None):

        from ..samplers import GibbsSampler
        self.default_sampler = GibbsSampler

        super(MFM, self).__init__(mixture_model, sampler, seed)

        self.gamma, self.mu = self._check_parameters(gamma, mu)

    @staticmethod
    def _check_parameters(gamma, mu):

        if gamma is not None:
            if not np.isscalar(gamma):
                raise ValueError("Float 'gamma' must be a scalar.")
            elif gamma <= 0.0:
                raise ValueError("Float 'gamma' must be larger than zero, but"
                                 " gamma = %f" % b)
        else:
            gamma = 1.0

        if mu is not None:
            if not np.isscalar(mu):
                raise ValueError("Float 'mu' must be a scalar.")
            elif mu <= 0.0:
                raise ValueError("Float 'mu' must be larger than zero, but"
                                 " mu = %f" % b)
        else:
            mu = 1.0

        return gamma, mu

    @classmethod
    def _check_process_model(cls, process_model):

        if not isinstance(process_model, cls):
            raise ValueError("'process_model' must be a mixture of"
                             " finite mixtures (MFM) model."
                             " Got process_model = %r" % process_model)

        return process_model

    @staticmethod
    def _log_v_quotient(n, t, tp, gamma, mu, k_max=1000, diff=50.0, memo={}):
        # TODO: Make it possible to use a custom pmf p_K, e.g.
        #       - Geometric: p_K(k) = (1-r)^(k-1) * r
        #       - Poisson: p_K(k) = mu^(k-1)/(k-1)! * exp(-mu)

        try:

            return memo[(n, t, tp)]

        except KeyError:

            def help(s):
                comp = gammaln(n) - gammaln(n+s*gamma) - diff
                ret = np.empty(k_max, dtype=float)
                for k in range(k_max):
                    ret[k] = gammaln(n) + k*np.log(mu) - gammaln(1.0+k) - \
                            gammaln(1.0+s*gamma) - gammaln(n+(k+s)*gamma) + \
                            gammaln(1.0+(k+s)*gamma)
                    if ret[k] < comp:
                        break
                ret = s*gamma*np.log(n) + _logsumexp(k+1, ret[:k+1])
                return ret

            ret = help(t) - help(tp)
            ret += (t-tp) * (np.log(mu) - gamma*np.log(n))
            ret += gammaln(1.0 + t*gamma) - gammaln(1.0 + tp*gamma)

            memo[(n, t, tp)] = ret

            return ret

    def _ms_log_prior_pre(self, n, t, tp, process_param):
        """
        First term in the logarithm of the prior appearing in the M-H
        acceptance ratio used by the merge-split samplers.
        """

        ret = self._log_v_quotient(n, t, tp, process_param.gamma,
                process_param.mu, memo=process_param._log_v_quotient_memo)

        return ret

    def _ms_log_prior_post(self, nc, process_param):
        """
        Second term in the logarithm of the prior appearing in the M-H
        acceptance ratio used by the merge-split samplers.
        """

        ret = gammaln(process_param.gamma + nc) - gammaln(process_param.gamma)

        return ret

    class DrawParam(GenericProcess.DrawParam):

        def __init__(self, process_model, random_state):

            super(MFM.DrawParam, self).__init__(random_state)

            self._process_model = MFM._check_process_model(process_model)

            self._gamma = None
            self._mu = None
            self._log_v_quotient_memo = {}

        @property
        def gamma(self):

            if self._gamma is None:
                return self._process_model.gamma
            else:
                return self._gamma

        @property
        def mu(self):

            if self._mu is None:
                return self._process_model.mu
            else:
                return self._mu

        def log_prior(self, n, n_c):
            """
            Return the logarithm of the conditional prior.
            """

            if n_c == 0:
                pm = self._process_model
                ret = np.log(self.gamma) + pm._log_v_quotient(n, n_c+1, n_c,
                        self.gamma, self.mu, memo=self._log_v_quotient_memo)
                return ret
            elif n_c > 0:
                return np.log(n_c + self.gamma)
            else:
                raise ValueError("'n_c' must be non-negative.")

        def dump(self):

            return self._gamma, self._mu

    class InferParam(GenericProcess.InferParam):

        def __init__(self, process_model, random_state):

            super(MFM.InferParam, self).__init__(random_state)

            self._process_model = MFM._check_process_model(process_model)

            self._gamma = None
            self._mu = None
            self._log_v_quotient_memo = {}

        @property
        def gamma(self):

            if self._gamma is None:
                return self._process_model.gamma
            else:
                return self._gamma

        @property
        def mu(self):

            if self._mu is None:
                return self._process_model.mu
            else:
                return self._mu

        def log_prior(self, n, n_c, m):
            """
            Return the logarithm of the conditional prior.
            """

            if n_c == 0:
                # a new component

                pm = self._process_model

                ret = np.log(self.gamma)
                ret += pm._log_v_quotient(n, n_c+1, n_c, self.gamma, self.mu,
                        memo=self._log_v_quotient_memo)
                # TODO: Check that!
                ret -= np.log(m)

                return ret

            elif n_c > 0:
                # an existing Component

                return np.log(n_c + self.gamma)

            else:
                raise ValueError("'n_c' must be non-negative.")

        def iterate(self, n, k):

            pass

        def dump(self):

            return self._gamma, self._mu


text:
def create_graph(contents):
	"""
	if you are given a -1 then it does not point to anything.
	"""
	d = {}
	for i in xrange(len(contents)):
		d[i] = int(contents[i])
	return d

def _cycle(graph, key, stack, stacks):
	# print graph, key, stack
	if ( key , graph[key] ) in stack: # you have found a cycle
		stacks.append(stack)
		return # True
	elif graph[key] == -1: # dead end
		return None # False
	else:
		stack.append( ( key , graph[key] ) )
		_cycle( graph, graph[key], stack, stacks )
		# print stack

def find_cycles(graph):
	"""
	find all the cycles in a Directed Acyclic Graph.
	"""
	stacks = []
	for k,v in graph.items():
		stack = []
		_cycle(graph, k, stack, stacks)
	results = []
	for i in stacks:
		i.sort()
		if i not in results:
			results.append(i)
		#print i
	print len(results)

if __name__ == "__main__":
	import sys
	l = sys.argv[1:]
	r = open(l[0],'r').read().split('\n')
	r.remove('')
	# print r
	N = r[0]
	graph = create_graph(r[1:])
	# print graph
	find_cycles(graph)


text:
#ifndef HECMW_GEOMETRIC_INCLUDED
#define HECMW_GEOMETRIC_INCLUDED

struct hecmw_coord {
  double x;
  double y;
  double z;
};

extern double HECMW_degree_to_radian(double deg);

extern double HECMW_radian_to_degree(double rad);

extern int HECMW_cylindrical_to_cartesian(const struct hecmw_coord *coord,
                                          struct hecmw_coord *result);

#endif


text:
@import url(reset.css);
html, body {
  height: 100%;
  line-height: 1.42857143; }

a {
  text-decoration: none; }

button:focus {
  outline: 0; }

input:focus, textarea:focus, keygen:focus, select:focus, button:focus {
  outline: 0; }

.wrap-header {
  position: relative;
  height: 100%; }
  .wrap-header .shadow {
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    background-color: #000;
    opacity: 0;
    z-index: 1; }
  .wrap-header .header {
    position: relative;
    height: 100%;
    z-index: 2; }
    .wrap-header .header .top .hint-left {
      position: absolute;
      top: 50px;
      left: 50px;
      font-size: 24px; }
      .wrap-header .header .top .hint-left .table {
        display: table; }
        .wrap-header .header .top .hint-left .table .table-cell {
          display: table-cell;
          vertical-align: middle; }
          .wrap-header .header .top .hint-left .table .table-cell div.text {
            display: inline-block;
            width: 100%; }
      .wrap-header .header .top .hint-left img {
        display: inline-block;
        margin-bottom: 20px; }
    .wrap-header .header .top .hint-right {
      position: absolute;
      top: 50px;
      right: 50px;
      font-size: 24px; }
    .wrap-header .header .wrap-center-block {
      display: table;
      height: 100%;
      width: 100%; }
      .wrap-header .header .wrap-center-block .center-block {
        display: table-cell;
        vertical-align: middle;
        text-align: center; }
        .wrap-header .header .wrap-center-block .center-block h1 {
          padding: 20px 0px; }
        .wrap-header .header .wrap-center-block .center-block h2 {
          padding: 10px 0px; }
        .wrap-header .header .wrap-center-block .center-block .btn {
          font-size: 24px;
          background: none;
          border: solid 2px #fff;
          height: 50px;
          padding: 0 50px;
          margin-top: 50px;
          border-radius: 50px;
          cursor: pointer; }
    .wrap-header .header .arrow {
      position: absolute;
      display: block;
      bottom: 25px;
      left: 0px;
      right: 0px;
      margin: 0 auto;
      height: 28px;
      width: 43px;
      background: url("../images/icon-arrow.png") 0 0 no-repeat;
      cursor: pointer !important; }
      .wrap-header .header .arrow.arrow-blink {
        animation: blinker 1s linear infinite; }
@keyframes blinker {
  50% {
    opacity: 0.0; } }
.wrap-line {
  position: relative;
  height: 100%; }
  .wrap-line .shadow {
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    background-color: #000;
    opacity: 0;
    z-index: 1; }
  .wrap-line .line {
    position: relative;
    height: 100%;
    z-index: 2; }
    .wrap-line .line .wrap-center-block {
      display: table;
      height: 100%;
      width: 100%; }
      .wrap-line .line .wrap-center-block .center-block {
        display: table-cell; }
        .wrap-line .line .wrap-center-block .center-block .text-block {
          margin: 0 auto; }

.wrap-square {
  position: relative; }
  .wrap-square .square {
    position: relative;
    height: 100%; }
    .wrap-square .square ul {
      font-size: 0; }
      .wrap-square .square ul li {
        position: relative;
        display: inline-block;
        vertical-align: top;
        overflow: hidden; }
        .wrap-square .square ul li .wrap_wrap {
          position: absolute;
          height: 100%;
          width: 100%; }
          .wrap-square .square ul li .wrap_wrap .wrap {
            display: table;
            height: 100%;
            width: 100%; }
            .wrap-square .square ul li .wrap_wrap .wrap .inner {
              display: table-cell;
              vertical-align: middle; }
        .wrap-square .square ul li .shadow {
          position: absolute;
          top: 0;
          bottom: 0;
          left: 0;
          right: 0;
          background-color: #000;
          opacity: 0;
          z-index: 1; }
        .wrap-square .square ul li .blur {
          position: absolute;
          top: 0;
          bottom: 0;
          left: 0;
          right: 0;
          z-index: 1; }
        .wrap-square .square ul li .icon {
          position: relative;
          text-align: center;
          padding: 50px;
          z-index: 2; }
        .wrap-square .square ul li .title {
          position: relative;
          padding: 50px;
          z-index: 2; }

.wrap-map {
  position: relative;
  height: 100%; }

.wrap-comment {
  overflow: hidden; }
  .wrap-comment .wrap-head .head {
    text-align: center; }
  .wrap-comment .comment {
    text-align: center; }
    .wrap-comment .comment .wrap_wrap {
      position: absolute;
      display: table;
      margin: auto;
      top: 0;
      bottom: 0;
      left: 0;
      right: 0;
      width: 100%; }
      .wrap-comment .comment .wrap_wrap .wrap {
        display: table-cell;
        text-align: center;
        vertical-align: middle; }
    .wrap-comment .comment .icon {
      display: inline-block;
      border-radius: 50%;
      overflow: hidden;
      margin-bottom: 50px; }

.contact-form {
  display: none; }

#contact-form {
  padding: 30px; }

#contact-form input.error {
  border: red solid 1px; }

#contact-form label.error {
  font-size: 12px;
  color: red; }

#cboxLoadedContent .alert {
  color: #000;
  margin: 30px; }

form h2 {
  font-size: 30px;
  margin-top: 20px;
  margin-bottom: 10px;
  font-family: inherit;
  font-weight: 500;
  line-height: 1.1;
  color: #000; }
form .form-group {
  margin-bottom: 15px; }
form .form-control {
  display: block;
  width: 100%;
  padding: 6px 12px;
  font-size: 14px;
  line-height: 1.42857143;
  color: #555;
  background-color: #fff;
  background-image: none;
  border: 1px solid #ccc;
  border-radius: 4px;
  -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
  box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
  -webkit-transition: border-color ease-in-out .15s, -webkit-box-shadow ease-in-out .15s;
  -o-transition: border-color ease-in-out .15s, box-shadow ease-in-out .15s;
  transition: border-color ease-in-out .15s, box-shadow ease-in-out .15s;
  box-sizing: border-box; }
form .btn {
  display: inline-block;
  padding: 6px 12px;
  margin-bottom: 0;
  font-size: 14px;
  font-weight: normal;
  line-height: 1.42857143;
  text-align: center;
  white-space: nowrap;
  vertical-align: middle;
  cursor: pointer;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
  background-image: none;
  border: 1px solid transparent;
  border-radius: 4px;
  color: #333;
  background-color: #fff;
  border-color: #ccc; }

@media screen and (max-width: 768px) {
  .wrap-header .header .top {
    height: 10px !important; }
    .wrap-header .header .top .hint-left {
      position: relative !important;
      top: 25px;
      left: 0 !important;
      right: 0 !important;
      font-size: 24px !important;
      text-align: center !important; }
      .wrap-header .header .top .hint-left .table {
        display: table !important;
        width: 100% !important; }
        .wrap-header .header .top .hint-left .table .table-cell div.text {
          display: inline-block !important;
          width: 100% !important; }
    .wrap-header .header .top .hint-right {
      position: relative !important;
      top: 50px !important;
      left: 0 !important;
      right: 0 !important;
      font-size: 24px !important;
      text-align: center !important; }
  .wrap-header .header .wrap-center-block .center-block img {
    max-width: 100px !important; }
  .wrap-header .header .wrap-center-block .center-block .btn {
    font-size: 18px !important;
    margin-top: 15px !important; }

  .wrap-line {
    height: auto !important; }
    .wrap-line .line .wrap-center-block .center-block .text-block {
      margin: 0 auto !important;
      padding: 20px 0 !important;
      width: auto !important; }
      .wrap-line .line .wrap-center-block .center-block .text-block img {
        width: 100% !important;
        height: auto !important; }
      .wrap-line .line .wrap-center-block .center-block .text-block p {
        padding: 0 15px !important; }

  .wrap-square ul li {
    width: 100% !important; } }
@media screen and (max-width: 320px) {
  h1 {
    font-size: 24px !important; }

  h2 {
    font-size: 18px !important; }

  .wrap-header .header .top .hint-left {
    position: relative !important;
    top: 25px;
    left: 0 !important;
    right: 0 !important;
    font-size: 18px !important;
    text-align: center !important; }
    .wrap-header .header .top .hint-left .table {
      display: table !important;
      width: 100% !important; }
      .wrap-header .header .top .hint-left .table .table-cell div.text {
        display: inline-block !important;
        width: 100% !important; }
  .wrap-header .header .top .hint-right {
    position: relative !important;
    top: 50px !important;
    left: 0 !important;
    right: 0 !important;
    font-size: 18px !important;
    text-align: center !important; }
  .wrap-header .header .wrap-center-block .center-block img {
    max-width: 100px !important; }
  .wrap-header .header .wrap-center-block .center-block .btn {
    font-size: 16px !important;
    margin-top: 15px !important; }

  .wrap-line {
    height: auto !important; }
    .wrap-line .line .wrap-center-block .center-block .text-block {
      margin: 0 auto !important;
      padding: 20px 0 !important;
      width: auto !important; }
      .wrap-line .line .wrap-center-block .center-block .text-block img {
        width: 100% !important;
        height: auto !important; }
      .wrap-line .line .wrap-center-block .center-block .text-block p {
        padding: 0 15px !important; }

  .wrap-square ul li {
    width: 100% !important; }
    .wrap-square ul li .title {
      font-size: 18px !important; } }

/*# sourceMappingURL=main.css.map */


text:
using strange.extensions.signal.impl;

namespace VisualiseR.Presentation
{
    /// <summary>
    /// Signals that the slide positions changed.
    /// </summary>
    public class SlidePositionChangedSignal : Signal
    {

    }
}


text:
namespace content {

class RenderProcessHostUnitTest : public RenderViewHostTestHarness {};

// Tests that guest RenderProcessHosts are not considered suitable hosts when
// searching for RenderProcessHost.
TEST_F(RenderProcessHostUnitTest, GuestsAreNotSuitableHosts) {
  GURL test_url("http://foo.com");

  MockRenderProcessHost guest_host(browser_context());
  guest_host.set_is_for_guests_only(true);

  EXPECT_FALSE(RenderProcessHostImpl::IsSuitableHost(
      &guest_host, browser_context(), test_url));
  EXPECT_TRUE(RenderProcessHostImpl::IsSuitableHost(
      process(), browser_context(), test_url));
  EXPECT_EQ(
      process(),
      RenderProcessHost::GetExistingProcessHost(browser_context(), test_url));
}

#if !defined(OS_ANDROID)
TEST_F(RenderProcessHostUnitTest, RendererProcessLimit) {
  // This test shouldn't run with --site-per-process mode, which prohibits
  // the renderer process reuse this test explicitly exercises.
  if (AreAllSitesIsolatedForTesting())
    return;

  // Disable any overrides.
  RenderProcessHostImpl::SetMaxRendererProcessCount(0);

  // Verify that the limit is between 1 and kMaxRendererProcessCount.
  EXPECT_GT(RenderProcessHostImpl::GetMaxRendererProcessCount(), 0u);
  EXPECT_LE(RenderProcessHostImpl::GetMaxRendererProcessCount(),
      kMaxRendererProcessCount);

  // Add dummy process hosts to saturate the limit.
  ASSERT_NE(0u, kMaxRendererProcessCount);
  ScopedVector<MockRenderProcessHost> hosts;
  for (size_t i = 0; i < kMaxRendererProcessCount; ++i) {
    hosts.push_back(new MockRenderProcessHost(browser_context()));
  }

  // Verify that the renderer sharing will happen.
  GURL test_url("http://foo.com");
  EXPECT_TRUE(RenderProcessHostImpl::ShouldTryToUseExistingProcessHost(
        browser_context(), test_url));
}
#endif

#if defined(OS_ANDROID)
TEST_F(RenderProcessHostUnitTest, NoRendererProcessLimitOnAndroid) {
  // Disable any overrides.
  RenderProcessHostImpl::SetMaxRendererProcessCount(0);

  // Verify that by default the limit on Android returns max size_t.
  EXPECT_EQ(std::numeric_limits<size_t>::max(),
      RenderProcessHostImpl::GetMaxRendererProcessCount());

  // Add a few dummy process hosts.
  ASSERT_NE(0u, kMaxRendererProcessCount);
  ScopedVector<MockRenderProcessHost> hosts;
  for (size_t i = 0; i < kMaxRendererProcessCount; ++i) {
    hosts.push_back(new MockRenderProcessHost(browser_context()));
  }

  // Verify that the renderer sharing still won't happen.
  GURL test_url("http://foo.com");
  EXPECT_FALSE(RenderProcessHostImpl::ShouldTryToUseExistingProcessHost(
        browser_context(), test_url));
}
#endif

}  // namespace content


text:
package db

import (
	"database/sql"
)

type Executor interface {
	QueryRow(query string, args ...interface{}) *sql.Row
	Exec(query string, args ...interface{}) (sql.Result, error)
	Query(query string, args ...interface{}) (*sql.Rows, error)
}

type DbExecutor struct {
	*sql.DB
}

type TxExecutor struct {
	*sql.Tx
}

type DBClient interface {
	Init() error
	ID() string
	SetDebug(open bool)
	Begin(is_readonly bool) DBClient
	Rollback()
	Commit()
	GetOne(_sql string, val ...interface{}) interface{}
	Insert(table string, vals map[string]interface{}) int
	Replace(table string, vals map[string]interface{}) int
	Update(table string, vals map[string]interface{}, where string, val ...interface{}) int
	Execute(_sql string, val ...interface{}) int
	GetRow(_sql string, val ...interface{}) map[string]interface{}
	GetAll(_sql string, val ...interface{}) []map[string]interface{}
}


text:
import logging
LOG_FORMAT = ('%(levelname) -10s %(asctime)s %(name) -30s %(funcName) '
              '-35s %(lineno) -5d: %(message)s')
LOGGER = logging.getLogger(__name__)
logging.basicConfig(filename='module.log',level=logging.INFO, format=LOG_FORMAT)

import pika
import sys
import argparse
import os
pythonModulesPath = os.getenv('HOMYPI_PYTHON_MODULES');
sys.path.append( pythonModulesPath )
from rabbitConsumer import RabbitConsumer
from rabbitEmitter import RabbitEmitter, ServerRequester
from spotify_player import SpotifyPlayer
from player import Player
from playlist import Track, Album, Playlist
from serverHttpRequest import ServerHttpRequest
from dynamicModule import DynamicModule
import alsaaudio
from os.path import expanduser
from ConfigParser import SafeConfigParser
import json
import time
import traceback
import signal
import setproctitle
from scheduler import Sched
LOGGER.info("imports ready")

queue_name = "player"
class PlayerManager:
    spotifyPlayer = None
    def __init__(self, config, playersConfig):
        LOGGER.info("__init__ player")
        PlayerManager.config = config
        self.rabbitConnection = None
        self.name = config.get("Server", "name")
        self.serverHttpRequest = ServerHttpRequest(config.get("Server", "url"),
                                                   config.get("Server", "username"),
                                                   config.get("Server", "password"))
        Playlist.serverHttpRequest = self.serverHttpRequest;
        LOGGER.info("=====================+++>" + str(Playlist.serverHttpRequest))
        self.modules = DynamicModule(playersConfig).load()
        #self.players = self.moduleLoader.load()
        #name, modules, config, serverHttpRequest, serverMq):
        self.job = None;
        signal.signal(signal.SIGINT, self.stopApp)
        LOGGER.info("starting player module")
        self.server = ServerRequester("serverRequest.player")

        self.player = Player(self.name, self.modules, config, self.serverHttpRequest, self.server)

        self.rabbitConnection = RabbitConsumer("module.player", "module.player")
        Playlist.rabbitConnection = self.server;
        try:
            #for p in players:
            #    self.spotifyPlayer = p["class"](config, self.next)
            print("starting spotify player")
            self.setHandlers()
            self.rabbitConnection.onConnected(self.init)
            self.rabbitConnection.start()
            self.onSocketReconnect();

            while True:
                  time.sleep(0.2)
        except KeyboardInterrupt, SystemExit:
            self.stopApp()
        except:
            LOGGER.error("player module crashed")
            LOGGER.error(traceback.format_exc())
            self.stopApp()
    def setSendProgressJob(self):
        if self.job is not None:
            self.job.remove()
            self.job = None;
        try:
            LOGGER.info("setSendProgressJob => create job")
            self.job = Sched.scheduler.add_job(self.sendProgress, "interval", seconds=5)
        except e:
            LOGGER.error("error")
            LOGGER.error(traceback.format_exc())

        LOGGER.info("setSendProgressJob => job created, sending progress")
        self.sendProgress();

    def onSocketReconnect(self):
        self.server.emit("raspberry:module:new", {
                "name": "music",
                "status": "PAUSED",
                "volume": self.getVolume()
            });

    def stopApp(self, arg1=None, arg2=None):
        try:
            if self.spotifyPlayer is not None:
                self.spotifyPlayer.exit()
            if self.rabbitConnection is not None:
                self.rabbitConnection.stop()
                self.rabbitConnection.join()
            if self.job is not None:
                self.job.remove()
        except:
            LOGGER.error(traceback.format_exc())
        sys.exit(0)

    def play(self, data=None):
        LOGGER.info("play========>" + str(data));
        if "source" in data:
            obj = False
            #self.player.playlist.clear()
            if "track" in data:
                success = self.player.playlist.set(Track(data["source"], data["track"]["uri"], data["track"]["serviceId"]))
            elif "album" in data:
                if "startAtTrack" in data:
                    success = self.player.playlist.set(Album(data["source"], data["album"]["uri"], data["album"]["serviceId"]), startAtTrack=data["startAtTrack"])
                else:
                    success = self.player.playlist.set(Album(data["source"], data["album"]["uri"], data["album"]["serviceId"]))
            elif "playlist" in data:
                success = self.player.playlist.set(data);
            if success:
                self.player.play();

    def playTrackFromRequest(self, data):
        if "source" in data and "uri" in data:
            self.player.playlist.clear()
            LOGGER.info(str(data));
            self.player.playlist.add(Track(data["source"], data["uri"]))
            self.player.play()

    def playIdInPlaylist(self, data):
        self.spotifyPlayer.playIdInPlaylist(data)
    def playListAdd(self, data, fromDB=False):
        LOGGER.info(str(data))
        if "track" in data:
            if "source" in data["track"] and "uri" in data["track"]:
                self.player.playlist.add(Track(data["track"]["source"], data["track"]["uri"], data["track"].get("_id"), data["track"].get("name")), fromDB)
        elif "trackset" in data:
            for track in data["trackset"]:
                self.player.playlist.add(Track(track["source"], track["uri"], data["track"].get("_id"), data["track"].get("name")), fromDB)

    def playListSet(self, data, fromDb=False):
        LOGGER.info("set playlist: " + str(data.get("tracks")))
        LOGGER.info("from DB = " + str(fromDb))
        self.player.playlist.clear(fromDb);
        LOGGER.info("data = " + str(data));
        trackList = [];
        for track in data.get("tracks", []):
            if "source" in track and "uri" in track:
                LOGGER.info("adding " + str(track["uri"]) + "   _id=" + str(track.get("_id")))
                trackList.append(Track(track["source"], track["uri"], track.get("_id"), track.get("name")))
            else:
                LOGGER.warn("missing source or uri in: " + str(track))
        self.player.playlist.concat(trackList, fromDb);
        if not fromDb:
            self.player.play();

    def removeInPlaylist(self, data):
        LOGGER.info("Remove in playlist: " + str(data));
        if "_id" in data:
            self.player.playlist.removeById(data["_id"])
        elif "key" in data:
            self.player.playlist.remove(data["key"])
    def playListLoad(self, data):
        self.spotifyPlayer.playListLoad(data)
    def play_local(self):
        print("local")
    def getVolume(self):
        LOGGER.info("get volume");
        mixer = alsaaudio.Mixer("PCM");
        LOGGER.info("Volume = " + str(mixer.getvolume()[0]))
        vol = mixer.getvolume()[0];
        return vol

    def setVolume(self, data):
        mixer = alsaaudio.Mixer("PCM");
        LOGGER.info("SET Volume = " + str(data['volume']))
        volBase = int(data['volume'])
        if (volBase > 100):
            volBase = 100
        if (volBase < 0):
            volBase = 0
        vol = (volBase/2)+50
        mixer.setvolume(vol);
        self.rabbitConnection.emit("player:volume:isSet", {"volume": self.getVolume()}, type="server_request")

    def init(self):
        LOGGER.info("inititalize player data")
        res = self.serverHttpRequest.get("api/modules/music/playlists/" + self.name);
        LOGGER.info("Got playlist: " + str(res));
        if "playlist" in res and "tracks" in res["playlist"]:
            self.playListSet(res["playlist"], True)

    def sendProgress(self):
        LOGGER.info("new progress = " + str(self.spotifyPlayer.position))
        self.server.emit("playlist:track:progress", {"progress": self.spotifyPlayer.position})
    def seek(self, data):
        if "progress_ms" in data:
            self.spotifyPlayer.seek(data["progress_ms"])
            self.sendProgress()
    def setHandlers(self):
        LOGGER.info("set handlers")
        self.rabbitConnection.addHandler("playTrack", self.play)
        self.rabbitConnection.addHandler("resume", self.player.resume)
        self.rabbitConnection.addHandler("pause", self.player.pause)
        self.rabbitConnection.addHandler("next", self.player.next)
        self.rabbitConnection.addHandler("previous", self.player.previous)
        self.rabbitConnection.addHandler("playIdInPlaylist", self.playIdInPlaylist)
        self.rabbitConnection.addHandler("playListAdd", self.playListAdd)
        self.rabbitConnection.addHandler("playListSet", self.playListSet)
        self.rabbitConnection.addHandler("removeInPlaylist", self.removeInPlaylist)
        self.rabbitConnection.addHandler("setVolume", self.setVolume)
        self.rabbitConnection.addHandler("getVolume", self.getVolume)
        self.rabbitConnection.addHandler("setVolume", self.setVolume)
        self.rabbitConnection.addHandler("seek", self.seek)
        self.rabbitConnection.addHandler("reconnected", self.onSocketReconnect)

if __name__ == '__main__':
    LOGGER.info("Starting player module")
    setproctitle.setproctitle("homyPi_player")
    parser = argparse.ArgumentParser(description='Client for the HAPI server')
    parser.add_argument('--conf', help='Path to the configuration file')
    parser.add_argument('--players', help='Players')
    args = parser.parse_args()
    confPath = expanduser("~") + '/.hommyPi_conf'
    LOGGER.info("Checking args")
    try:
        if args.conf is not None:
           confPath = args.conf
        if args.players is not None:
            LOGGER.info(args.players)
            players = json.loads(args.players);
        else:
            players = [];
    except:
        LOGGER.error("player module crashed")
        LOGGER.error(traceback.format_exc())
    LOGGER.info("Checking config")
    config = SafeConfigParser()
    config.read(confPath)
    playerManager = PlayerManager(config, players);


text:
package com.jayway.jsonpath;

import org.junit.Ignore;
import org.junit.Test;

import java.io.ByteArrayInputStream;
import java.net.URL;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import static java.util.Arrays.asList;
import static junit.framework.Assert.*;

/**
 * Created by IntelliJ IDEA.
 * User: kallestenflo
 * Date: 11/8/11
 * Time: 7:52 PM
 */
public class JsonModelTest {

    public final static String DOCUMENT =
            "{ \"store\": {\n" +
                    "    \"book\": [ \n" +
                    "      { \"category\": \"reference\",\n" +
                    "        \"author\": \"Nigel Rees\",\n" +
                    "        \"title\": \"Sayings of the Century\",\n" +
                    "        \"price\": 8.95\n" +
                    "      },\n" +
                    "      { \"category\": \"fiction\",\n" +
                    "        \"author\": \"Evelyn Waugh\",\n" +
                    "        \"title\": \"Sword of Honour\",\n" +
                    "        \"price\": 12.99\n" +
                    "      },\n" +
                    "      { \"category\": \"fiction\",\n" +
                    "        \"author\": \"Herman Melville\",\n" +
                    "        \"title\": \"Moby Dick\",\n" +
                    "        \"isbn\": \"0-553-21311-3\",\n" +
                    "        \"price\": 8.99\n" +
                    "      },\n" +
                    "      { \"category\": \"fiction\",\n" +
                    "        \"author\": \"J. R. R. Tolkien\",\n" +
                    "        \"title\": \"The Lord of the Rings\",\n" +
                    "        \"isbn\": \"0-395-19395-8\",\n" +
                    "        \"price\": 22.99\n" +
                    "      }\n" +
                    "    ],\n" +
                    "    \"bicycle\": {\n" +
                    "      \"color\": \"red\",\n" +
                    "      \"price\": 19.95,\n" +
                    "      \"foo:bar\": \"fooBar\",\n" +
                    "      \"dot.notation\": \"new\"\n" +
                    "    }\n" +
                    "  }\n" +
                    "}";

    public final static String INVALID_DOCUMENT = "{?\\?\\?!!?~q`}}}}}\"\" \"store\": {\n";

    @Test(expected = InvalidJsonException.class)
    public void invalid_json_throws() throws Exception {
        JsonModel.model(INVALID_DOCUMENT).get("store.id");
    }

    @Test(expected = InvalidPathException.class)
    public void invalid_path_throws() throws Exception {
        JsonModel.model(DOCUMENT).get("a(");
    }

    @Test
    public void a_model_can_be_pretty_printed() throws Exception {
        JsonModel model = JsonModel.model(DOCUMENT);

        model.print();
    }

    @Test
    public void has_path_validates() throws Exception {
        assertFalse(JsonModel.model(DOCUMENT).hasPath("store.invalid"));
        assertFalse(JsonModel.model(DOCUMENT).hasPath("store.book[0].foo"));

        assertTrue(JsonModel.model(DOCUMENT).hasPath("store.book"));
        assertTrue(JsonModel.model(DOCUMENT).hasPath("store.book[0].title"));
    }

    @Test
    public void a_json_document_can_be_fetched_with_a_URL() throws Exception {
        URL url = new URL("http://maps.googleapis.com/maps/api/geocode/json");
        assertEquals("REQUEST_DENIED", JsonModel.model(url).get("status"));
    }

    @Test
    public void a_json_document_can_be_fetched_with_a_InputStream() throws Exception {
        ByteArrayInputStream bis = new ByteArrayInputStream(DOCUMENT.getBytes());
        assertEquals("Nigel Rees", JsonModel.model(bis).get("store.book[0].author"));
    }

    @Test
    public void maps_and_list_can_queried() throws Exception {
        Map<String, Object> doc = new HashMap<String, Object>();
        doc.put("items", asList(0, 1, 2));
        doc.put("child", Collections.singletonMap("key", "value"));

        JsonModel model = JsonModel.model(doc);

        assertEquals("value", model.get("$child.key"));
        assertEquals(1, model.get("$items[1]"));
        assertEquals("{\"child\":{\"key\":\"value\"},\"items\":[0,1,2]}", model.toJson());
    }

    @Test
    public void query_for_null_property_returns_null() {
        String documentWithNull =
                "{ \"store\": {\n" +
                        "    \"book\": { \n" +
                        "      \"color\": null\n" +
                        "    }\n" +
                        "  }\n" +
                        "}";

        Object color = JsonModel.model(documentWithNull).get("store.book.color");

        assertNull(color);
    }

    @Test(expected = InvalidPathException.class)
    public void query_for_property_on_array_throws() throws Exception {
        JsonModel.model(DOCUMENT).get("store.book.color");
    }

}


text:
import '../tests/frameworks';
import {ObjectId} from '../utils/utils';
import {DataTableService} from './DataTableService';

var mock = angular.mock;

describe('DataTableService', function () {
	before(() => {
		angular.module('DataTables.Mock', []);
	})
	beforeEach(mock.module('DataTables.Mock'));

	beforeEach(mock.module(($provide) => {
		$provide.constant('DataTableService', DataTableService);
	}));

	beforeEach(mock.inject((DataTableService, $parse) => {
		this.DataTableService = DataTableService;
		this.$parse = $parse;
	}));

	it('should build and save columns', () => {
		let id = ObjectId();
		let columnElements = [
			`<column name="Name" width="300" flex-grow="1"></column>`,
			`<column name="Gender" flex-grow="1">{{monkey}} ---- {{$cell}}</column>`
		].map((el) => angular.element(el)[0]);

		this.DataTableService.saveColumns(id, columnElements);
		this.DataTableService.buildColumns({}, this.$parse);

		this.DataTableService.columns.should.have.property(id).and.have.length(2);
	});

});


text:
<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>Ant Design Admin</title>
  <link rel="stylesheet" href="index.css" />
  <link rel="icon" href="https://t.alipayobjects.com/images/T1QUBfXo4fXXXXXXXX.png" type="image/x-icon">


text:
package de.is24.deadcode4j.analyzer;

import org.junit.Test;

public class A_ServletContainerInitializerAnalyzer extends AnAnalyzer<ServletContainerInitializerAnalyzer> {

    @Override
    protected ServletContainerInitializerAnalyzer createAnalyzer() {
        return new ServletContainerInitializerAnalyzer("JUnit", "de.is24.deadcode4j.junit.SomeInterface") {
        };
    }

    @Test
    public void shouldRecognizeServletContainerInitializerClasses() {
        analyzeFile("de/is24/deadcode4j/analyzer/v3-metadata-missing.web.xml");
        analyzeFile("SomeServletInitializer.class");

        assertThatDependenciesAreReported("SomeServletInitializer");
    }

    @Test
    public void shouldRecognizeServletContainerInitializerClassesIfMetadataCompleteAttributeIsFalse() {
        analyzeFile("de/is24/deadcode4j/analyzer/v3-metadata-incomplete.web.xml");
        analyzeFile("SomeServletInitializer.class");

        assertThatDependenciesAreReported("SomeServletInitializer");
    }

    @Test
    public void shouldRecognizeMetadataCompleteAttribute() {
        analyzeFile("de/is24/deadcode4j/analyzer/v3-metadata-complete.web.xml");
        analyzeFile("SomeServletInitializer.class");

        assertThatNoDependenciesAreReported();
    }
}


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

using Xamarin.Forms;

namespace Xamarin.Forms.Conference.WebRTC
{
	public partial class LoginPage : ContentPage
	{
		public LoginPage()
		{
			InitializeComponent();
		}

		protected override void OnAppearing()
		{
			base.OnAppearing();

			var vm = new LoginViewModel();
			this.BindingContext = vm;
			vm.OnAppearing();
		}
	}
}


text:
Bug #41337 (WSDL parsing doesn't ignore non soap bindings)
--SKIPIF--
<?php require_once('skipif.inc'); ?>
--FILE--
<?php
ini_set("soap.wsdl_cache_enabled",0);
$client = new SoapClient(dirname(__FILE__)."/bug41337_2.wsdl");
echo "ok\n";
?>
--EXPECT--
ok


text:
namespace Microsoft.Azure.Management.WebSites.Models
{
    using Microsoft.Azure;
    using Microsoft.Azure.Management;
    using Microsoft.Azure.Management.WebSites;
    using Newtonsoft.Json;
    using Newtonsoft.Json.Converters;
    using System.Runtime;
    using System.Runtime.Serialization;

    /// <summary>
    /// Defines values for BackupItemStatus.
    /// </summary>
    [JsonConverter(typeof(StringEnumConverter))]
    public enum BackupItemStatus
    {
        [EnumMember(Value = "InProgress")]
        InProgress,
        [EnumMember(Value = "Failed")]
        Failed,
        [EnumMember(Value = "Succeeded")]
        Succeeded,
        [EnumMember(Value = "TimedOut")]
        TimedOut,
        [EnumMember(Value = "Created")]
        Created,
        [EnumMember(Value = "Skipped")]
        Skipped,
        [EnumMember(Value = "PartiallySucceeded")]
        PartiallySucceeded,
        [EnumMember(Value = "DeleteInProgress")]
        DeleteInProgress,
        [EnumMember(Value = "DeleteFailed")]
        DeleteFailed,
        [EnumMember(Value = "Deleted")]
        Deleted
    }
    internal static class BackupItemStatusEnumExtension
    {
        internal static string ToSerializedValue(this BackupItemStatus? value)  =>
            value == null ? null : ((BackupItemStatus)value).ToSerializedValue();

        internal static string ToSerializedValue(this BackupItemStatus value)
        {
            switch( value )
            {
                case BackupItemStatus.InProgress:
                    return "InProgress";
                case BackupItemStatus.Failed:
                    return "Failed";
                case BackupItemStatus.Succeeded:
                    return "Succeeded";
                case BackupItemStatus.TimedOut:
                    return "TimedOut";
                case BackupItemStatus.Created:
                    return "Created";
                case BackupItemStatus.Skipped:
                    return "Skipped";
                case BackupItemStatus.PartiallySucceeded:
                    return "PartiallySucceeded";
                case BackupItemStatus.DeleteInProgress:
                    return "DeleteInProgress";
                case BackupItemStatus.DeleteFailed:
                    return "DeleteFailed";
                case BackupItemStatus.Deleted:
                    return "Deleted";
            }
            return null;
        }

        internal static BackupItemStatus? ParseBackupItemStatus(this string value)
        {
            switch( value )
            {
                case "InProgress":
                    return BackupItemStatus.InProgress;
                case "Failed":
                    return BackupItemStatus.Failed;
                case "Succeeded":
                    return BackupItemStatus.Succeeded;
                case "TimedOut":
                    return BackupItemStatus.TimedOut;
                case "Created":
                    return BackupItemStatus.Created;
                case "Skipped":
                    return BackupItemStatus.Skipped;
                case "PartiallySucceeded":
                    return BackupItemStatus.PartiallySucceeded;
                case "DeleteInProgress":
                    return BackupItemStatus.DeleteInProgress;
                case "DeleteFailed":
                    return BackupItemStatus.DeleteFailed;
                case "Deleted":
                    return BackupItemStatus.Deleted;
            }
            return null;
        }
    }
}


text:
<?php

namespace RickTap\Qriteria\Support;

class Parentheses
{
    public static $open  = "(";
    public static $close = ")";

    /**
     * Checks a string for balanced parantheses.
     * It checks if there is an equal amount of open and closed parens,
     * and if they the are in the right order.
     * Nesting and other characters are allowed.
     * Examples:
     * true:  (() test (a))
     * false: ())()
     *
     * @param  string  $string String to test the balance on.
     * @return boolean (true: balanced | false: unbalanced)
     */
    public static function isBalanced($string)
    {
        // Keep track of number of open parens
        $open = 0;

        // Loop through each char
        for ($i = 0; $i < strlen($string); $i++) {
            $char = $string[$i];
            switch ($char) {
                case static::$open:
                    $open++;
                    break;
                case static::$close:
                    $open--;
                    if ($open < 0) {
                        return false;
                    }
                    break;
            }
        }

        // there must be an equal amount of opened and closed parens
        return ($open === 0);
    }
}


text:
namespace MassTransit.MessageData.Converters
{
    using System.IO;
    using System.Text;
    using System.Threading;
    using System.Threading.Tasks;
    using Metadata;

    public class StringMessageDataConverter :
        IMessageDataConverter<string>
    {
        public async Task<string> Convert(Stream stream, CancellationToken cancellationToken)
        {
            using var ms = new MemoryStream();

            await stream.CopyToAsync(ms, 4096, cancellationToken).ConfigureAwait(false);

            return Encoding.UTF8.GetString(ms.ToArray());
        }
    }
}


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

import * as assert from 'assert';
import {describe, it, before, after, afterEach, beforeEach} from 'mocha';
import axiosModule from 'axios';
import * as semver from 'semver';

import {TraceSpan} from '../src/trace';
import {TraceLabels} from '../src/trace-labels';
import {StackFrame} from '../src/util';

import * as testTraceModule from './trace';
import {
  assertSpanDuration,
  DEFAULT_SPAN_DURATION,
  isServerSpan,
  wait,
} from './utils';
import {WebFramework, WebFrameworkConstructor} from './web-frameworks/base';
import {Connect3} from './web-frameworks/connect';
import {Express4} from './web-frameworks/express';
import {Hapi18, Hapi19} from './web-frameworks/hapi17';
import {Hapi16} from './web-frameworks/hapi8_16';
import {Koa1} from './web-frameworks/koa1';
import {Koa2} from './web-frameworks/koa2';
import {
  Restify3,
  Restify4,
  Restify5,
  Restify6,
  Restify7,
  Restify8,
} from './web-frameworks/restify';

// The type of a stack trace object after being parsed from a trace span's stack
// frame label.
interface TraceSpanStackFrames {
  stack_frame: StackFrame[];
}

// The number of times to retry counting spans in the aborted request test
const ABORTED_SPAN_RETRIES = 5;
// The list of web frameworks to test.
const FRAMEWORKS: WebFrameworkConstructor[] = [
  Connect3,
  Express4,
  // Hapi8,
  // Hapi12,
  // Hapi15,
  Hapi16,
  Hapi18,
  Hapi19,
  Koa1,
  Koa2,
  Restify3,
  Restify4,
  Restify5,
  Restify6,
  Restify7,
  Restify8,
];

/**
 * Main
 */

describe('Web framework tracing', () => {
  let axios: typeof axiosModule;
  before(() => {
    testTraceModule.setCLSForTest();
    testTraceModule.setPluginLoaderForTest();
    testTraceModule.start({ignoreUrls: [/ignore-me/], ignoreMethods: []});
    axios = require('axios');
  });

  after(() => {
    testTraceModule.setCLSForTest(testTraceModule.TestCLS);
    testTraceModule.setPluginLoaderForTest(testTraceModule.TestPluginLoader);
  });

  FRAMEWORKS.forEach(webFrameworkConstructor => {
    const commonName = webFrameworkConstructor.commonName;
    const expectedTopStackFrame = webFrameworkConstructor.expectedTopStackFrame;
    const versionRange = webFrameworkConstructor.versionRange;

    // Skip this set for incompatible versions of Node
    const skip = !semver.satisfies(process.version, versionRange);

    (skip ? describe.skip : describe)(`Tracing ${commonName}`, () => {
      let webFramework: WebFramework;
      let port: number;

      before(async () => {
        webFramework = new webFrameworkConstructor();
        webFramework.addHandler({
          path: '/one-handler',
          hasResponse: true,
          fn: async () => {
            await wait(DEFAULT_SPAN_DURATION);
            return {statusCode: 200, message: 'hello!'};
          },
        });
        webFramework.addHandler({
          path: '/two-handlers',
          hasResponse: false,
          blocking: true,
          fn: async () => {
            await wait(DEFAULT_SPAN_DURATION / 2);
          },
        });
        webFramework.addHandler({
          path: '/two-handlers',
          hasResponse: true,
          fn: async () => {
            await wait(DEFAULT_SPAN_DURATION / 2);
            return {statusCode: 200, message: 'hellohello!!'};
          },
        });
        webFramework.addHandler({
          path: '/propagate-hello',
          hasResponse: true,
          fn: async () => {
            await wait(0); // Add an additional link to the async execution chain.
            const response = await axios.get(`http://localhost:${port}/hello`);
            return {statusCode: response.status, message: response.data};
          },
        });
        webFramework.addHandler({
          path: '/hello',
          hasResponse: true,
          fn: async () => {
            return {statusCode: 200, message: '[incessant barking]'};
          },
        });
        webFramework.addHandler({
          path: '/error',
          hasResponse: true,
          fn: async () => {
            throw new Error('[restrained whimpering]');
          },
        });
        webFramework.addHandler({
          path: '/ignore-me',
          hasResponse: true,
          fn: async () => {
            return {statusCode: 200, message: '[unrestrained whimpering]'};
          },
        });
        port = await webFramework.listen(0);
      });

      after(() => {
        webFramework.shutdown();
      });

      afterEach(() => {
        testTraceModule.clearTraceData();
      });

      it('accurately measures get time (1 handler)', async () => {
        let recordedTime = 0;
        await testTraceModule
          .get()
          .runInRootSpan({name: 'outer'}, async span => {
            assert.ok(testTraceModule.get().isRealSpan(span));
            recordedTime = Date.now();
            await axios.get(`http://localhost:${port}/one-handler`);
            recordedTime = Date.now() - recordedTime;
            span!.endSpan();
          });
        assert.strictEqual(testTraceModule.getSpans().length, 3);
        const serverSpan = testTraceModule.getOneSpan(isServerSpan);
        assertSpanDuration(serverSpan, [DEFAULT_SPAN_DURATION, recordedTime]);
      });

      it('accurately measures get time (2 handlers)', async () => {
        let recordedTime = 0;
        await testTraceModule
          .get()
          .runInRootSpan({name: 'outer'}, async span => {
            assert.ok(testTraceModule.get().isRealSpan(span));
            recordedTime = Date.now();
            // Hit endpoint with two middlewares/handlers.
            await axios.get(`http://localhost:${port}/two-handlers`);
            recordedTime = Date.now() - recordedTime;
            span!.endSpan();
          });
        assert.strictEqual(testTraceModule.getSpans().length, 3);
        const serverSpan = testTraceModule.getOneSpan(isServerSpan);
        assertSpanDuration(serverSpan, [DEFAULT_SPAN_DURATION, recordedTime]);
      });

      it('handles errors', async () => {
        await testTraceModule
          .get()
          .runInRootSpan({name: 'outer'}, async span => {
            assert.ok(testTraceModule.get().isRealSpan(span));
            // Hit endpoint which always throws an error.
            await axios.get(`http://localhost:${port}/error`, {
              validateStatus: () => true, // Obviates try/catch.
            });
            span!.endSpan();
          });
        assert.strictEqual(testTraceModule.getSpans().length, 3);
        const serverSpan = testTraceModule.getOneSpan(isServerSpan);
        assert.strictEqual(
          serverSpan.labels[TraceLabels.HTTP_RESPONSE_CODE_LABEL_KEY],
          '500'
        );
      });

      it("doesn't trace ignored urls", async () => {
        await testTraceModule
          .get()
          .runInRootSpan({name: 'outer'}, async span => {
            assert.ok(testTraceModule.get().isRealSpan(span));
            // Hit endpoint that always gets ignored.
            await axios.get(`http://localhost:${port}/ignore-me`);
            span!.endSpan();
          });
        assert.strictEqual(testTraceModule.getSpans().length, 2);
        assert.strictEqual(testTraceModule.getSpans(isServerSpan).length, 0);
      });

      it('ends span upon client abort', async () => {
        await testTraceModule
          .get()
          .runInRootSpan({name: 'outer'}, async span => {
            assert.ok(testTraceModule.get().isRealSpan(span));
            // Hit endpoint, but time out before it has a chance to respond.
            // To ensure that a trace is written, also waits
            await axios
              .get(`http://localhost:${port}/one-handler`, {
                timeout: DEFAULT_SPAN_DURATION / 2,
              })
              .catch(() => {
                /* swallow */
              });
            // Wait remainder of server response time to ensure that trace is
            // written.
            await wait(DEFAULT_SPAN_DURATION / 2);
            span!.endSpan();
          });
        // Check that the aborted span is written.
        // Retry in intervals because to minimize flakes -- there is no way for
        // us to be notified client-side when the server has completed the
        // client-aborted request.
        for (let i = 0; i < ABORTED_SPAN_RETRIES; i++) {
          if (testTraceModule.getSpans().length === 3) {
            break;
          }
          if (i === ABORTED_SPAN_RETRIES - 1) {
            assert.fail(
              `Aborted span was not written after ${
                DEFAULT_SPAN_DURATION * ABORTED_SPAN_RETRIES
              } milliseconds.`
            );
          } else {
            await wait(DEFAULT_SPAN_DURATION);
          }
        }
      });

      it('assigns different trace IDs to distinct requests', async () => {
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        let requests: Array<Promise<any>>;
        // Setting the URL allows us not to record this root span, but also
        // not get warnings for child spans.
        await testTraceModule
          .get()
          .runInRootSpan({name: 'outer', url: '/ignore-me'}, async () => {
            requests = [
              axios.get(`http://localhost:${port}/hello?this-is=dog`),
              axios.get(`http://localhost:${port}/hello?this-is=puppy`),
            ];
            await Promise.all(requests);
          });
        assert.strictEqual(
          testTraceModule.getTraces(trace => trace.spans.some(isServerSpan))
            .length,
          requests!.length
        );
      });

      it('propagates trace context', async () => {
        await testTraceModule
          .get()
          .runInRootSpan({name: 'outer'}, async span => {
            assert.ok(testTraceModule.get().isRealSpan(span));
            // Hits endpoint that will make an additional outgoing HTTP
            // request (to another endpoint on the same server).
            await axios.get(`http://localhost:${port}/propagate-hello`);
            span!.endSpan();
          });
        assert.strictEqual(testTraceModule.getSpans().length, 5);
        const spans = [
          // outer
          testTraceModule.getOneSpan(s => s.name === 'outer'),
          // /propagate-hello client
          testTraceModule.getOneSpan(
            s =>
              s.kind === 'RPC_CLIENT' &&
              s.labels[TraceLabels.HTTP_URL_LABEL_KEY].includes(
                '/propagate-hello'
              )
          ),
          // /propagate-hello server
          testTraceModule.getOneSpan(
            s => s.kind === 'RPC_SERVER' && s.name.includes('/propagate-hello')
          ),
          // /hello client
          testTraceModule.getOneSpan(
            s =>
              s.kind === 'RPC_CLIENT' &&
              s.labels[TraceLabels.HTTP_URL_LABEL_KEY].includes('/hello')
          ),
          // /hello server
          testTraceModule.getOneSpan(
            s => s.kind === 'RPC_SERVER' && s.name.includes('/hello')
          ),
        ];
        for (let i = 0; i < spans.length - 1; i++) {
          // When i is odd, the following assert can only be true if distributed
          // context propagation works. When i is even, it can only be true if
          // application context propagation works.
          assert.strictEqual(spans[i].spanId, spans[i + 1].parentSpanId);
        }
      });

      describe('span properties', () => {
        let serverSpan: TraceSpan;

        beforeEach(async () => {
          await testTraceModule
            .get()
            .runInRootSpan({name: 'outer'}, async span => {
              assert.ok(testTraceModule.get().isRealSpan(span));
              // Hit an endpoint with a query parameter.
              await axios.get(`http://localhost:${port}/hello?this-is=dog`);
              span!.endSpan();
            });
          assert.strictEqual(testTraceModule.getSpans().length, 3);
          serverSpan = testTraceModule.getOneSpan(isServerSpan);
        });

        it('applies the correct labels', () => {
          const labels = serverSpan.labels;
          assert.strictEqual(
            labels[TraceLabels.HTTP_RESPONSE_CODE_LABEL_KEY],
            '200'
          );
          assert.strictEqual(labels[TraceLabels.HTTP_METHOD_LABEL_KEY], 'GET');
          assert.strictEqual(
            labels[TraceLabels.HTTP_URL_LABEL_KEY],
            `http://localhost:${port}/hello?this-is=dog`
          );
          assert.ok(labels[TraceLabels.HTTP_SOURCE_IP]);
        });

        it('removes trace frames from stack', () => {
          const stackTrace: TraceSpanStackFrames = JSON.parse(
            serverSpan.labels[TraceLabels.STACK_TRACE_DETAILS_KEY]
          );
          assert.strictEqual(
            stackTrace.stack_frame[0].method_name,
            expectedTopStackFrame
          );
        });

        it("doesn't include query parameters in span name", () => {
          assert.strictEqual(
            serverSpan.name.indexOf('dog'),
            -1,
            `span name ${serverSpan.name} includes query parameters`
          );
        });
      });

      it('uses the span name override option', async () => {
        const oldSpanNameOverride = testTraceModule
          .get()
          .getConfig().rootSpanNameOverride;
        testTraceModule.get().getConfig().rootSpanNameOverride = (
          path: string
        ) => `${path}-goodbye`;
        try {
          await testTraceModule
            .get()
            .runInRootSpan({name: 'outer'}, async span => {
              assert.ok(testTraceModule.get().isRealSpan(span));
              await axios.get(`http://localhost:${port}/hello`);
              span!.endSpan();
            });
          assert.strictEqual(testTraceModule.getSpans().length, 3);
          const serverSpan = testTraceModule.getOneSpan(isServerSpan);
          assert.strictEqual(serverSpan.name, '/hello-goodbye');
        } finally {
          testTraceModule.get().getConfig().rootSpanNameOverride =
            oldSpanNameOverride;
        }
      });
    });
  });
});


text:
package org.apache.shardingsphere.db.protocol.postgresql.packet.command.query.simple;

import org.apache.shardingsphere.db.protocol.postgresql.packet.command.PostgreSQLCommandPacketType;
import org.apache.shardingsphere.db.protocol.postgresql.payload.PostgreSQLPacketPayload;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;

import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

@RunWith(MockitoJUnitRunner.class)
public final class PostgreSQLComQueryPacketTest {

    @Mock
    private PostgreSQLPacketPayload payload;

    @Test
    public void assertNewInstance() {
        when(payload.readStringNul()).thenReturn("sql");
        PostgreSQLComQueryPacket actual = new PostgreSQLComQueryPacket(payload);
        actual.write(payload);
        verify(payload).readInt4();
        assertThat(actual.getSql(), is("sql"));
        assertThat(actual.getIdentifier(), is(PostgreSQLCommandPacketType.SIMPLE_QUERY));
    }
}