text:
                                Clients

                                    Clients Overview

                                    Clients Search

                                Domains

                                    Domain Search

                                    Register Domain

                                Others

                                    View Cancellation Requests

                                    Mass Mail

            <form name="submitForm" novalidate ng-submit="submit()" autocomplete="off">

                             First Name
                            *
                            <input type="text" class="form-control" name="fName" ng-model="session.fName" required/>

                             Last Name
                            <input type="text" class="form-control" name="lName"  ng-model="session.lName"/>

                             Company Name
                            *
                            <input type="text" class="form-control" name="cmpyName" ng-model="session.cmpyName" required/>

                             Email Address
                            *
                            <input type="email"   class="form-control" name="email" ng-model="session.eMail"  required />

                                Invalid email address.

                             Password
                            *
                            <input type="text" class="form-control" name="passWd" ng-model="session.passWd" required />

                             Security Question
                            <select class="form-control" ng-model="session.secQues">
                                <option value="">Select a Security Question</option>
                                <option ng-repeat="question in securityQuestions" value="{{question.sqID}}">{{question.question}}</option>
                            </select>

                             Security Answer
                            <input type="text" class="form-control" disabled ng-if="!session.secQues"/>
                            <input type="text" class="form-control" name="secAns" ng-model="session.secAns" ng-if="session.secQues"/>

                             Late Fees

                            <input type="checkbox" name="applyLateFees"  ng-model="session.applyLateFees"  ng-true-value="1" ng-false-value="0"/> Don't Apply Late Fees

                             Overdue Notices

                            <input type="checkbox" name="sendOverDueMails" ng-model="session.sendOverDueMails" ng-true-value="1" ng-false-value="0"/> Don't Send Overdue Emails

                             Tax Exempt

                            <input type="checkbox" name="taxExempt" ng-model="session.taxExempt" ng-true-value="1"
                                   ng-false-value="0"/> Don't Apply Tax to Invoices

                             Separate Invoices

                            <input type="checkbox" name="seprateInvoices" ng-model="session.seprateInvoices" ng-true-value="1" ng-false-value="0"/> Separate Invoices for Services

                             Disable CC Processing

                            <input type="checkbox" name="ccprocessing" ng-model="session.ccprocessing" ng-true-value="'1'" ng-false-value="0"/> Disable Automatic CC Processing

                            Address 1
                            <input type="text" class="form-control" name="address1" ng-model="session.address1"/>

                            Address 2
                            <input type="text" class="form-control" name="address2"  ng-model="session.address2"/>

                            City
                            <input type="text" class="form-control" name="city" ng-model="session.city"/>

                             State/Region
                            <input type="text" class="form-control" name="state" ng-model="session.state"/>

                             Zip Code

                                5 digits are required!
                            <input type="text" class="form-control" name="zip" ng-model="session.zip" ng-pattern="/^\d+$/" ng-minlength="5"/>

                                Not valid zip!

                             Country
                            <select class="form-control" ng-model="session.countryID" ng-change="selectedCountry(session.countryID)">
                                <option value="">Select a Country </option>
                                <option ng-repeat="country in countries" value="{{country.id_countries}}">{{country.name}}</option>
                            </select>

                             Currency
                            <select class="form-control" ng-model="session.currencyID" ng-change="selectedCountry(session.currencyID)">
                                <option value="">Select Currency </option>
                                <option ng-repeat="currency in currencies" value="{{currency.id_countries}}">{{currency.currency_code}}</option>
                            </select>

                             Phone No
                            *

                                10 digits are required!
                            <input type="text" name="phone" class="form-control" ng-model="session.phone"  required ng-pattern="/^\d+$/" ng-minlength="10">

                                Not valid number!

                             Payment Method
                            <select ng-model="session.payMethod"  class="form-control" ng-options="key1 as value for (key1 , value) in paymentMethods">
                                 <option value=""> Select a Payment Method </option>
                            </select>

                             Language
                            <input class="form-control" name="lang"  ng-model="session.lang">

                             Status
                            <select ng-model="session.status"  class="form-control" ng-options="key1 as value for (key1 , value) in status">
                                <option value=""> Select Client Status </option>
                            </select>

                            Admin Note
                            <textarea class="form-control" name="about" rows="5" ng-model="session.about"></textarea>

                            <input type="submit" class="btn btn-danger col-md-offset-3 col-md-6 "  ng-disabled="submitForm.$invalid" value="ADD CLIENT" />

            </form>

<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">


text:
<?php

namespace DataService\Form\Type;

use DataService\Model\Property;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class PropertyType extends AbstractType
{
    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('name')
            ->add('type')
            ->add('description')
            ->add('pattern')
            ->add('format')
        ;
    }

    /**
     * {@inheritdoc}
     */
    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class'      => 'DataService\Model\Property',
            'csrf_protection' => false,
            'empty_data'      => function (FormInterface $form) {
                return new Property(
                    $form->get('name')->getData(),
                    $form->get('type')->getData(),
                    $form->get('description')->getData(),
                    $form->get('pattern')->getData(),
                    $form->get('format')->getData()
                );
            }
        ));
    }

    /**
     * {@inheritdoc}
     */
    public function getName()
    {
        return 'property';
    }
}

redpajama_set_name: RedPajamaGithub


text:
package pub.ayada.scala.sparkUtils.etl.read.csv

import org.apache.spark.sql.types.StructType

case class Csv2DFProps(taskType : String = "Csv2DF",
                       id : String,
                       propsFile : String,
                       printSchema : Boolean = true,
                       loadCount : Boolean = false,
                       path : String,
                       header : Boolean = true,
                       delimiter : String = ",",
                       quote : String = "\"",
                       escape : String = "\\",
                       mode : String = "PERMISSIVE",
                       charset : String = "UTF-8",
                       commentChar : String = null.asInstanceOf[String],
                       dateFormat : String = "M/d/yyyy H:m:s a",
                       nullValue : String,
                       repartition : Int = 0,
                       broadcast : Boolean = false,
                       forceNoPersist : Boolean = false,
                       csvColumns : StructType) extends pub.ayada.scala.sparkUtils.etl.read.ReadProps


text:
import Cookies from "js-cookie";
import { facebookUserSessionCookieKey } from "./facebookUserSessionCookieKey";
export const deleteSessionCookie = () => Cookies.remove(facebookUserSessionCookieKey);


text:
package com.hack23.cia.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.access.annotation.Secured;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.hack23.cia.model.internal.application.data.committee.impl.ViewRiksdagenCommittee;
import com.hack23.cia.service.data.api.DataViewer;
import com.hack23.cia.service.data.api.ViewRiksdagenCommitteeDAO;

/**
 * The Class ViewRiksdagenCommitteeDataContainer.
 */
@Component("ViewRiksdagenCommitteeDataContainer")
@Transactional(propagation=Propagation.REQUIRED, readOnly = true)
@Secured({"ROLE_ANONYMOUS","ROLE_USER", "ROLE_ADMIN" })
public final class ViewRiksdagenCommitteeDataContainer extends GenericDataContainer<ViewRiksdagenCommittee,String>{

	/** The view riksdagen committee dao. */
	@Autowired
	private ViewRiksdagenCommitteeDAO viewRiksdagenCommitteeDAO;

	/**
	 * Instantiates a new view riksdagen committee data container.
	 *
	 * @param dataViewer the data viewer
	 */
	@Autowired
	public ViewRiksdagenCommitteeDataContainer(@Qualifier("DataViewer") final DataViewer dataViewer) {
		super(ViewRiksdagenCommittee.class,dataViewer);
	}

	@Override
	public ViewRiksdagenCommittee load(final String id) {
		for (final ViewRiksdagenCommittee riksdagenCommittee : viewRiksdagenCommitteeDAO.getAll()) {
			if (id.equals(riksdagenCommittee.getEmbeddedId().getOrgCode())) {
				return riksdagenCommittee;
			}

		}

		return null;
	}

}


text:
<!DOCTYPE html>

  	<title>Google Book Embedded Viewer API</title>
  	<meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta charset="utf-8">

Scroll the Source: Hartford Declared "Richest City in the US," 1876


text:
var assert = require('assert');
var toProperUpper = require('../index.js');

suite('Proper Upper', function() {

  test('all lowercase', function(done) {
    var ugly = 'bill murray';
    var gold = 'Bill Murray';
    var pretty = toProperUpper(ugly);

    assert.equal(pretty, gold, 'String should be formatted properly.');

    done();
  });

  test('all uppercase', function(done) {
    var ugly = 'BILL MURRAY';
    var gold = 'Bill Murray';
    var pretty = toProperUpper(ugly);

    assert.equal(pretty, gold, 'String should be formatted properly.');

    done();
  });

  test('random case', function(done) {
    var ugly = 'biLl mUrRAY';
    var gold = 'Bill Murray';
    var pretty = toProperUpper(ugly);

    assert.equal(pretty, gold, 'String should be formatted properly.');

    done();
  });

  test('hyphened words', function(done) {
      var ugly = "sir francis-smiTh-yOrkshire";
      var gold = "Sir Francis-Smith-Yorkshire";
      var pretty = toProperUpper(ugly, '-');

      assert.equal(pretty, gold, 'String should be formatted properly.');

      done();
    });

  test('apostrophed words', function(done) {
    var ugly = "chips o'toule";
    var gold = "Chips O'Toule";
    var pretty = toProperUpper(ugly, "'");

    assert.equal(pretty, gold, 'String should be formatted properly.');

    done();
  });

  test('hyphened and apostrophed words', function(done) {
    var ugly = "francis-smiTh-yOrkshire o'toule";
    var gold = "Francis-Smith-Yorkshire O'Toule";
    var pretty = toProperUpper(ugly, ["-", "'"]);

    assert.equal(pretty, gold, 'String should be formatted properly.');

    done();
  });
});


text:
package examples.spring;

import org.mybatis.dynamic.sql.SqlColumn;
import org.mybatis.dynamic.sql.SqlTable;

public final class AddressDynamicSqlSupport {
    public static final Address address = new Address();
    public static final SqlColumn<Integer> id = address.id;
    public static final SqlColumn<String> streetAddress = address.streetAddress;
    public static final SqlColumn<String> city = address.city;
    public static final SqlColumn<String> state = address.state;

    public static final class Address extends SqlTable {
        public final SqlColumn<Integer> id = column("address_id");
        public final SqlColumn<String> streetAddress = column("street_address");
        public final SqlColumn<String> city = column("city");
        public final SqlColumn<String> state = column("state");

        public Address() {
            super("Address");
        }
    }
}


text:
import uuid from 'uuid';
import { System } from './generic';

export default class Thrusters extends System {
  constructor(params) {
    super(params);
    this.class = 'Thrusters';
    this.type = 'Thruster';
    this.direction = params.direction || { x: 0, y: 0, z: 0 };
    this.rotation = params.rotation || { yaw: 0, pitch: 0, roll: 0 };
    this.rotationDelta = params.rotationDelta || { yaw: 0, pitch: 0, roll: 0 };
    this.rotationRequired = params.rotationRequired || { yaw: 0, pitch: 0, roll: 0 };
    this.manualThrusters = params.manualThrusters || false;
    this.thrusting = params.thrusting || false;
  }
  updateRotation(rotation, thrusting = false) {
    this.thrusting = thrusting;
    this.rotationDelta = rotation;
  }
  updateDirection(direction) {
    this.direction = direction;
    console.log(direction);
  }
  setRotation(rotation) {
    this.rotation = rotation;
  }
}


text:
using namespace llvm;

namespace crab_llvm {

  /// marks all internal functions with AlwaysInline attribute
  struct MarkInternalInline : public ModulePass
  {
    static char ID;
    MarkInternalInline () : ModulePass (ID) {}

    void getAnalysisUsage (AnalysisUsage &AU) const
    {AU.setPreservesAll ();}

    bool runOnModule (Module &M)
    {
      for (Function &F : M)
        if (!F.isDeclaration () && F.hasLocalLinkage ())
          F.addFnAttr (Attribute::AlwaysInline);
      return true;
    }

    virtual const char * getPassName() const {
      return "Mark internal functions with AlwaysInline attribute";
    }

  };

  char MarkInternalInline::ID = 0;
  Pass* createMarkInternalInlinePass () { return new MarkInternalInline (); }
}


text:
package term

import (
	"strings"
	"testing"
)

func TestReadInputFromTerminal(t *testing.T) {
	testcases := map[string]struct {
		Input  string
		Output string
	}{
		"empty":                             {},
		"empty newline":                     {Input: "\n"},
		"empty windows newline":             {Input: "\r\n"},
		"empty newline with extra":          {Input: "\nextra"},
		"leading space":                     {Input: " data", Output: " data"},
		"leading space newline":             {Input: " data\n", Output: " data"},
		"leading space windows newline":     {Input: " data\r\n", Output: " data"},
		"leading space newline with extra":  {Input: " data\nextra", Output: " data"},
		"trailing space":                    {Input: " data ", Output: " data "},
		"trailing space newline":            {Input: " data \n", Output: " data "},
		"trailing space windows newline":    {Input: " data \r\n", Output: " data "},
		"trailing space newline with extra": {Input: " data \nextra", Output: " data "},
	}

	for k, tc := range testcases {
		output := readInputFromTerminal(strings.NewReader(tc.Input))
		if output != tc.Output {
			t.Errorf("%s: Expected '%s', got '%s'", k, tc.Output, output)
		}
	}
}


text:
<?php
/**
 * RpcStatus
 *
 * PHP version 5
 *
 * @category Class
 * @package  Alfaview
 * @author   Swagger Codegen team
 * @link     https://github.com/swagger-api/swagger-codegen
 */

/**
 * quotaService/settings.proto
 *
 * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
 *
 * OpenAPI spec version: version not set
 *
 * Generated by: https://github.com/swagger-api/swagger-codegen.git
 * Swagger Codegen version: 2.4.27
 */

/**
 * NOTE: This class is auto generated by the swagger code generator program.
 * https://github.com/swagger-api/swagger-codegen
 * Do not edit the class manually.
 */

namespace Alfaview\Model;

use \ArrayAccess;
use \Alfaview\ObjectSerializer;

/**
 * RpcStatus Class Doc Comment
 *
 * @category Class
 * @package  Alfaview
 * @author   Swagger Codegen team
 * @link     https://github.com/swagger-api/swagger-codegen
 */
class RpcStatus implements ModelInterface, ArrayAccess
{
    const DISCRIMINATOR = null;

    /**
      * The original name of the model.
      *
      * @var string
      */
    protected static $swaggerModelName = 'rpcStatus';

    /**
      * Array of property to type mappings. Used for (de)serialization
      *
      * @var string[]
      */
    protected static $swaggerTypes = [
        'code' => 'int',
        'message' => 'string',
        'details' => '\Alfaview\Model\ProtobufAny[]'
    ];

    /**
      * Array of property to format mappings. Used for (de)serialization
      *
      * @var string[]
      */
    protected static $swaggerFormats = [
        'code' => 'int32',
        'message' => null,
        'details' => null
    ];

    /**
     * Array of property to type mappings. Used for (de)serialization
     *
     * @return array
     */
    public static function swaggerTypes()
    {
        return self::$swaggerTypes;
    }

    /**
     * Array of property to format mappings. Used for (de)serialization
     *
     * @return array
     */
    public static function swaggerFormats()
    {
        return self::$swaggerFormats;
    }

    /**
     * Array of attributes where the key is the local name,
     * and the value is the original name
     *
     * @var string[]
     */
    protected static $attributeMap = [
        'code' => 'code',
        'message' => 'message',
        'details' => 'details'
    ];

    /**
     * Array of attributes to setter functions (for deserialization of responses)
     *
     * @var string[]
     */
    protected static $setters = [
        'code' => 'setCode',
        'message' => 'setMessage',
        'details' => 'setDetails'
    ];

    /**
     * Array of attributes to getter functions (for serialization of requests)
     *
     * @var string[]
     */
    protected static $getters = [
        'code' => 'getCode',
        'message' => 'getMessage',
        'details' => 'getDetails'
    ];

    /**
     * Array of attributes where the key is the local name,
     * and the value is the original name
     *
     * @return array
     */
    public static function attributeMap()
    {
        return self::$attributeMap;
    }

    /**
     * Array of attributes to setter functions (for deserialization of responses)
     *
     * @return array
     */
    public static function setters()
    {
        return self::$setters;
    }

    /**
     * Array of attributes to getter functions (for serialization of requests)
     *
     * @return array
     */
    public static function getters()
    {
        return self::$getters;
    }

    /**
     * The original name of the model.
     *
     * @return string
     */
    public function getModelName()
    {
        return self::$swaggerModelName;
    }

    /**
     * Associative array for storing property values
     *
     * @var mixed[]
     */
    protected $container = [];

    /**
     * Constructor
     *
     * @param mixed[] $data Associated array of property values
     *                      initializing the model
     */
    public function __construct(array $data = null)
    {
        $this->container['code'] = isset($data['code']) ? $data['code'] : null;
        $this->container['message'] = isset($data['message']) ? $data['message'] : null;
        $this->container['details'] = isset($data['details']) ? $data['details'] : null;
    }

    /**
     * Show all the invalid properties with reasons.
     *
     * @return array invalid properties with reasons
     */
    public function listInvalidProperties()
    {
        $invalidProperties = [];

        return $invalidProperties;
    }

    /**
     * Validate all the properties in the model
     * return true if all passed
     *
     * @return bool True if all properties are valid
     */
    public function valid()
    {
        return count($this->listInvalidProperties()) === 0;
    }

    /**
     * Gets code
     *
     * @return int
     */
    public function getCode()
    {
        return $this->container['code'];
    }

    /**
     * Sets code
     *
     * @param int $code code
     *
     * @return $this
     */
    public function setCode($code)
    {
        $this->container['code'] = $code;

        return $this;
    }

    /**
     * Gets message
     *
     * @return string
     */
    public function getMessage()
    {
        return $this->container['message'];
    }

    /**
     * Sets message
     *
     * @param string $message message
     *
     * @return $this
     */
    public function setMessage($message)
    {
        $this->container['message'] = $message;

        return $this;
    }

    /**
     * Gets details
     *
     * @return \Alfaview\Model\ProtobufAny[]
     */
    public function getDetails()
    {
        return $this->container['details'];
    }

    /**
     * Sets details
     *
     * @param \Alfaview\Model\ProtobufAny[] $details details
     *
     * @return $this
     */
    public function setDetails($details)
    {
        $this->container['details'] = $details;

        return $this;
    }
    /**
     * Returns true if offset exists. False otherwise.
     *
     * @param integer $offset Offset
     *
     * @return boolean
     */
    public function offsetExists($offset)
    {
        return isset($this->container[$offset]);
    }

    /**
     * Gets offset.
     *
     * @param integer $offset Offset
     *
     * @return mixed
     */
    public function offsetGet($offset)
    {
        return isset($this->container[$offset]) ? $this->container[$offset] : null;
    }

    /**
     * Sets value based on offset.
     *
     * @param integer $offset Offset
     * @param mixed   $value  Value to be set
     *
     * @return void
     */
    public function offsetSet($offset, $value)
    {
        if (is_null($offset)) {
            $this->container[] = $value;
        } else {
            $this->container[$offset] = $value;
        }
    }

    /**
     * Unsets offset.
     *
     * @param integer $offset Offset
     *
     * @return void
     */
    public function offsetUnset($offset)
    {
        unset($this->container[$offset]);
    }

    /**
     * Gets the string presentation of the object
     *
     * @return string
     */
    public function __toString()
    {
        if (defined('JSON_PRETTY_PRINT')) { // use JSON pretty print
            return json_encode(
                ObjectSerializer::sanitizeForSerialization($this),
                JSON_PRETTY_PRINT
            );
        }

        return json_encode(ObjectSerializer::sanitizeForSerialization($this));
    }
}


text:
"""
Monitors an obiwan production run using qdo
"""
import os
import numpy as np
from glob import glob
import re
from collections import defaultdict

from obiwan.common import dobash,writelist,get_rsdir

import qdo

QDO_RESULT= ['running', 'succeeded', 'failed']

def get_interm_dir(outdir,brick,rowstart,
                do_skipids='no',do_more='no'):
    """Returns paths like outdir/bri/brick/rs0"""
    rsdir= get_rsdir(rowstart,
                     do_skipids,do_more)
    return os.path.join(outdir,brick[:3],brick,rsdir)

def get_final_dir(outdir,brick,rowstart,
                  do_skipids='no',do_more='no'):
    """Returns paths like outdir/replaceme/bri/brick/rs0"""
    rsdir= get_rsdir(rowstart,
                     do_skipids,do_more)
    return os.path.join(outdir,'replaceme',brick[:3],brick,
                        rsdir)

def get_deldirs(outdir,brick,rowstart,
                do_skipids='no',do_more='no'):
    """If slurm timeout or failed, logfile will exist in final dir but other outputs
        will be in interm dir. Return list of dirst to all of these
    """
    dirs= [get_final_dir(outdir,brick,rowstart,
                          do_skipids,do_more).replace('replaceme','logs')]
    dirs+= [get_interm_dir(outdir,brick,rowstart,
                          do_skipids,do_more)]
    return dirs

def get_checkpoint_fn(outdir,brick,rowstart):
    return os.path.join(outdir,'checkpoint',
                        brick[:3],brick,
                        'checkpoint_rs%d.pickle' % int(rowstart))

def get_logdir(outdir,brick,rowstart,
               do_skipids='no',do_more='no'):
   return (get_final_dir(outdir,brick,rowstart,
                        do_skipids,do_more)
           .replace('replaceme','logs'))

def get_logfile(outdir,brick,rowstart,
                do_skipids='no',do_more='no'):
    logdir= get_logdir(outdir,brick,rowstart,
                       do_skipids,do_more)
    return os.path.join(logdir,'log.'+brick)

def get_slurm_files(outdir):
    return glob( outdir + '/slurm-*.out')

class QdoList(object):
    """Queries the qdo db and maps log files to tasks and task status

    Args:
        outdir: obiwan outdir, the slurm*.out files are there
        que_name: ie. qdo create que_name
        skip_suceeded: number succeeded tasks can be very large for production runs,
            this slows down code so skip those tasks
    """
    def __init__(self,outdir,que_name='obiwan',
                 skip_succeed=False,
                 rand_num=None,
                 firstN=None):
        print('que_name= ',que_name.upper())
        self.outdir= outdir
        self.que_name= que_name
        self.skip_succeed= skip_succeed
        self.rand_num= rand_num
        self.firstN= firstN

    def isCosmos(self):
        return "cosmos" in self.que_name

    def get_tasks_logs(self):
        """get tasks and logs for the three types of qdo status"""
        # Logs for all Failed tasks
        tasks={}
        ids={}
        logs= defaultdict(list)
        #err= defaultdict(lambda: [])
        q = qdo.connect(self.que_name)
        for res in QDO_RESULT:
            if self.skip_succeed and res == 'succeeded':
                continue
            # List of "brick rs" for each QDO_RESULT
            qdo_tasks= np.array(q.tasks(state= getattr(qdo.Task, res.upper())))
            if self.rand_num:
                qdo_tasks= qdo_tasks[np.random.randint(0,len(qdo_tasks),size=self.rand_num)]
            elif not self.firstN is None:
                qdo_tasks= qdo_tasks[:self.firstN]
            if len(qdo_tasks) > 0:
                ids[res],tasks[res] = zip(*[(a.id,a.task)
                                             for a in qdo_tasks])
            else:
                ids[res],tasks[res]= [],[]
            # Corresponding log, slurm files
            for task in tasks[res]:
                # Logs
                if self.isCosmos():
                    brick,rs,do_skipids,do_more,subset = task.split(' ')
                    outdir= os.path.join(self.outdir,'subset%s' % subset)
                else:
                    brick,rs,do_skipids,do_more = task.split(' ')
                    outdir= self.outdir
                logfn= get_logfile(outdir,brick,rs,
                                   do_skipids=do_skipids,do_more=do_more)
                logs[res].append( logfn )
        return tasks,ids,logs

    def change_task_state(self,task_ids,to=None, modify=False,rm_files=False):
        """change qdo tasks state, for tasks with task_ids, to pending,failed, etc

        Args:
          to: change qdo state to this, pending,failed
          rm_files: delete the output files for that task
          modify: actually do the modifications (fail safe option)
        """
        assert(to in ['pending','failed'])
        q = qdo.connect(self.que_name)
        for task_id in task_ids:
            try:
                task_obj= q.tasks(id= int(task_id))
                if self.isCosmos():
                    brick,rs,do_skipids,do_more,subset = task_obj.task.split(' ')
                    outdir= os.path.join(self.outdir,'subset%s' % subset)
                else:
                    brick,rs,do_skipids,do_more = task_obj.task.split(' ')
                    outdir= self.outdir
                del_dirs= get_deldirs(outdir,brick,rs,
                                       do_skipids=do_skipids,
                                       do_more=do_more)
                del_fns= [get_checkpoint_fn(outdir,brick,rs)]
                if modify:
                    if to == 'pending':
                        # Stuck in pending b/c slurm job timed out
                        task_obj.set_state(qdo.Task.PENDING)
                        #print('id %s --> PENDING' % task_id)
                    elif to == 'failed':
                        # Manually force to failed, keep whatever outputs have
                        task_obj.set_state(qdo.Task.FAILED)
                        print('id %s --> FAILED' % task_id)
                    if rm_files:
                        for dr in del_dirs:
                            dobash('rm -r %s/*' % dr)
                        for fn in del_fns:
                            dobash('rm %s' % fn)
                else:
                    print('set --modify to affect id=%d, which corresponds to taks_obj=' % task_id,task_obj)
                    print('set --rm_files to remove',del_dirs,del_fns)
            except ValueError:
                print('cant find task_id=%d' % task_id)

class RunStatus(object):
    """Tallys which QDO_RESULTS actually finished, what errors occured, etc.

    Args:
    tasks: dict, each key is list of qdo tasks
    logs: dict, each key is list of log files for each task

    Defaults:
    regex_errs: list of regular expressions matching possible log file errors
    """

    def __init__(self,tasks,logs):
        self.tasks= tasks
        self.logs= logs
        self.regex_errs= [
            r'ValueError:\ starting\ row=[0-9]*?\ exceeds.*?sources',
            r'\No\ randoms\ in\ brick',
            r'pool\.py",\sline\s644,\sin\sget\n\s+raise\sself\._value\nAssertionError',
            r'assert\(len\(R\)\s==\slen\(blobsrcs\)\)\nAssertionError',
            r"ModuleNotFoundError:\sNo\smodule\snamed\s'fitsio'",
            r'psycopg2\.OperationalError:',
            r'MemoryError',
            r'astropy\.extern\.configobj\.configobj\.ParseError',
            r'RuntimeError:\ Command\ failed:\ sex\ -c',
            r'multiprocessing\/pool\.py\",\sline\s567',
            r"ImportError:\scannot\simport\sname\s'_fitsio_wrap'",
            r"OSError:\sFile\s not\sfound:",
            r"NothingToDoError:\sNo\sCCDs\stouching\sbrick",
            r'SystemError:\ \<built-in\ method\ flush']
        self.regex_errs_extra= ['Other','log does not exist']

    def get_tally(self):
        tally= defaultdict(list)
        for res in ['succeeded','failed','running']:
            print('res=%s' % res)
            if res == 'succeeded':
                for log in self.logs[res]:
                    with open(log,'r') as foo:
                        text= foo.read()
                    if "decals_sim:All done!" in text:
                        tally[res].append( 1 )
                    else:
                        tally[res].append( 0 )
            elif res == 'running':
                for log in self.logs[res]:
                    tally[res].append(1)
            elif res == 'failed':
                for cnt,log in enumerate(self.logs[res]):
                    if (cnt+1) % 25 == 0: print('%d/%d' % (cnt+1,len(self.logs[res])))
                    if not os.path.exists(log):
                        tally[res].append('log does not exist')
                        continue
                    with open(log,'r') as foo:
                        text= foo.read()
                    found_err= False
                    for regex in self.regex_errs:
                        foundIt= re.search(regex, text)
                        if foundIt:
                            tally[res].append(regex)
                            found_err=True
                            break
                    if not found_err:
                        tally[res].append('Other')
        # numpy array, not list, works with np.where()
        for res in tally.keys():
            tally[res]= np.array(tally[res])
        return tally

    def print_tally(self,tally):
        for res in self.tasks.keys():
            print('--- Tally %s ---' % res)
            if res == 'succeeded':
                print('%d/%d = done' % (len(tally[res]), np.sum(tally[res])))
            elif res == 'failed':
                for regex in self.regex_errs + self.regex_errs_extra:
                    print('%d/%d = %s' % (
                        np.where(tally[res] == regex)[0].size, len(tally[res]), regex))
            elif res == 'running':
                print('%d/%d : need rerun' % (len(tally[res]),len(tally[res])))

    def get_logs_for_failed(self,regex='Other'):
        """Returns log and slurm filenames for failed tasks labeled as regex"""
        return self.logs[ tally['failed'] == regex ]

if __name__ == '__main__':
    from argparse import ArgumentParser
    parser = ArgumentParser()
    parser.add_argument('--qdo_quename',default='obiwan_9deg',help='',required=False)
    parser.add_argument('--skip_succeed',action='store_true',default=False,help='speed up, number succeeded tasks can be very large for production runs and slows down status code',required=False)
    parser.add_argument('--rand_num',type=int,default=None,help='only process this many succeed,failed,running chosen at random from each',required=False)
    parser.add_argument('--firstN',type=int,default=None,help='speed up, instead of random 1000 do the first N (user specified) qdo tasks',required=False)
    parser.add_argument('--running_to_pending',action="store_true",default=False,help='set to reset all "running" jobs to "pending"')
    parser.add_argument('--running_to_failed',action="store_true",default=False,help='set to reset all "running" jobs to "failed"')
    parser.add_argument('--failed_message_to_pending',action='store',default=None,help='set to message of failed tak and reset all failed tasks with that message to pending')
    parser.add_argument('--failed_to_pending',action="store_true",default=False,help='set to reset all "failed" jobs to "pending"')
    parser.add_argument('--modify',action='store_true',default=False,help='set to actually reset the qdo tasks state AND to delete IFF running_to_pending or failed_message_to_pending are set')
    parser.add_argument('--outdir',default='.',help='',required=False)
    parser.add_argument('--no_write',action="store_true",default=False,help='modify the qdo DB but dont write out any text files',required=False)
    args = parser.parse_args()
    print(args)

    Q= QdoList(args.outdir,que_name=args.qdo_quename,
               skip_succeed=args.skip_succeed,
               rand_num=args.rand_num,
               firstN=args.firstN)
    print('Getting tasks,logs')
    tasks,ids,logs= Q.get_tasks_logs()

    # Logfile lists grouped by succeeded,running,failed
    if not args.no_write:
        for res in logs.keys():
            writelist(logs[res],"%s_%s_logfns.txt" % (args.qdo_quename,res))

    # Rerun tasks and delete those tasks' outputs
    if len(ids['running']) > 0:
        if args.running_to_pending:
            Q.change_task_state(ids['running'], to='pending',modify=args.modify,
                                rm_files=False)
        elif args.running_to_failed:
            Q.change_task_state(ids['running'], to='failed',modify=args.modify,
                                rm_files=False)
    if len(ids['failed']) > 0:
        if args.failed_to_pending:
            Q.change_task_state(ids['failed'], to='pending',modify=args.modify,
                                rm_files=False)

    # Failed logfile lists, group by error message
    R= RunStatus(tasks,logs)
    print('Counting number of failed,suceed,running tasks for ech failure mode')
    tally= R.get_tally()
    R.print_tally(tally)

    # Subset of failed to pending
    if args.failed_message_to_pending:
        hasMessage= np.where(tally['failed'] == args.failed_message_to_pending)[0]
        if hasMessage.size > 0:
            theIds= np.array(ids['failed'])[hasMessage]
            Q.change_task_state(theIds, to='pending', modify=args.modify,
                                rm_files=False)

    # logs,tasks for each type of failure
    if not args.no_write:
        print('Writing logs,tasks for each failure mode for failed tasks')
        for err_key in R.regex_errs + R.regex_errs_extra:
            err_logs= np.array(logs['failed'])[ tally['failed'] == err_key ]
            err_tasks= np.array(tasks['failed'])[ tally['failed'] == err_key ]
            err_string= (err_key[:12] + err_key[-8:])
            err_string= ((err_key[:10] + err_key[-10:])
                         .replace(" ","_")
                         .replace("/","")
                         .replace("*","")
                         .replace("?","")
                         .replace(":",""))
            writelist(err_logs,"logs_%s_%s.txt" % (args.qdo_quename,err_string))
            writelist(err_tasks,"tasks_%s_%s.txt" % (args.qdo_quename,err_string))

    print('done')


text:
source "$(dirname "$(realpath "$0")")"/source_me.sh

find . -name '.pytest_cache' -type d -delete
find . -name '__pycache__' -type d -delete
find . -name '*.pyc' -type f -delete
find . -name '*.DS_Store' -type f -delete
find . -name 'tmp' -maxdepth 1 -type d -delete
rm -rf build dist sklearn_porter.egg-info


text:
#pragma once
#include <aws/elasticmapreduce/EMR_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>

namespace Aws
{
namespace Utils
{
namespace Json
{
  class JsonValue;
  class JsonView;
} // namespace Json
} // namespace Utils
namespace EMR
{
namespace Model
{

  /**
   *
A CloudWatch dimension, which is specified using a Key (known as
   * a Name in CloudWatch), Value pair. By default, Amazon
   * EMR uses one dimension whose Key is JobFlowID and
   * Value is a variable representing the cluster ID, which is
   * ${emr.clusterId}. This enables the rule to bootstrap when the
   * cluster ID becomes available.

See Also:
   AWS
   * API Reference

   */
  class AWS_EMR_API MetricDimension
  {
  public:
    MetricDimension();
    MetricDimension(Aws::Utils::Json::JsonView jsonValue);
    MetricDimension& operator=(Aws::Utils::Json::JsonView jsonValue);
    Aws::Utils::Json::JsonValue Jsonize() const;

    /**
     *
The dimension name.

     */
    inline const Aws::String& GetKey() const{ return m_key; }

    /**
     *
The dimension name.

     */
    inline bool KeyHasBeenSet() const { return m_keyHasBeenSet; }

    /**
     *
The dimension name.

     */
    inline void SetKey(const Aws::String& value) { m_keyHasBeenSet = true; m_key = value; }

    /**
     *
The dimension name.

     */
    inline void SetKey(Aws::String&& value) { m_keyHasBeenSet = true; m_key = std::move(value); }

    /**
     *
The dimension name.

     */
    inline void SetKey(const char* value) { m_keyHasBeenSet = true; m_key.assign(value); }

    /**
     *
The dimension name.

     */
    inline MetricDimension& WithKey(const Aws::String& value) { SetKey(value); return *this;}

    /**
     *
The dimension name.

     */
    inline MetricDimension& WithKey(Aws::String&& value) { SetKey(std::move(value)); return *this;}

    /**
     *
The dimension name.

     */
    inline MetricDimension& WithKey(const char* value) { SetKey(value); return *this;}

    /**
     *
The dimension value.

     */
    inline const Aws::String& GetValue() const{ return m_value; }

    /**
     *
The dimension value.

     */
    inline bool ValueHasBeenSet() const { return m_valueHasBeenSet; }

    /**
     *
The dimension value.

     */
    inline void SetValue(const Aws::String& value) { m_valueHasBeenSet = true; m_value = value; }

    /**
     *
The dimension value.

     */
    inline void SetValue(Aws::String&& value) { m_valueHasBeenSet = true; m_value = std::move(value); }

    /**
     *
The dimension value.

     */
    inline void SetValue(const char* value) { m_valueHasBeenSet = true; m_value.assign(value); }

    /**
     *
The dimension value.

     */
    inline MetricDimension& WithValue(const Aws::String& value) { SetValue(value); return *this;}

    /**
     *
The dimension value.

     */
    inline MetricDimension& WithValue(Aws::String&& value) { SetValue(std::move(value)); return *this;}

    /**
     *
The dimension value.

     */
    inline MetricDimension& WithValue(const char* value) { SetValue(value); return *this;}

  private:

    Aws::String m_key;
    bool m_keyHasBeenSet;

    Aws::String m_value;
    bool m_valueHasBeenSet;
  };

} // namespace Model
} // namespace EMR
} // namespace Aws


text:
package org.hibernate.metamodel.source.annotations.global;

import javax.persistence.NamedNativeQuery;

import org.jboss.jandex.Index;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import org.hibernate.cfg.NotYetImplementedException;
import org.hibernate.engine.query.spi.sql.NativeSQLQueryReturn;
import org.hibernate.engine.query.spi.sql.NativeSQLQueryRootReturn;
import org.hibernate.engine.spi.NamedSQLQueryDefinition;
import org.hibernate.metamodel.MetadataSources;
import org.hibernate.metamodel.source.annotations.AnnotationBindingContextImpl;
import org.hibernate.metamodel.source.annotations.JandexHelper;
import org.hibernate.metamodel.source.internal.MetadataImpl;
import org.hibernate.service.ServiceRegistryBuilder;
import org.hibernate.service.classloading.spi.ClassLoaderService;
import org.hibernate.service.internal.StandardServiceRegistryImpl;
import org.hibernate.testing.junit4.BaseUnitTestCase;

import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertNotNull;
import static junit.framework.Assert.assertTrue;

/**
 * @author Hardy Ferentschik
 */
public class QueryBinderTest extends BaseUnitTestCase {

	private StandardServiceRegistryImpl serviceRegistry;
	private ClassLoaderService service;
	private MetadataImpl meta;

	@Before
	public void setUp() {
		serviceRegistry = (StandardServiceRegistryImpl) new ServiceRegistryBuilder().buildServiceRegistry();
		service = serviceRegistry.getService( ClassLoaderService.class );
		meta = (MetadataImpl) new MetadataSources( serviceRegistry ).buildMetadata();
	}

	@After
	public void tearDown() {
		serviceRegistry.destroy();
	}

	@Test(expected = NotYetImplementedException.class)
	public void testNoResultClass() {
		@NamedNativeQuery(name = "fubar", query = "SELECT * FROM FOO")
		class Foo {
		}
		Index index = JandexHelper.indexForClass( service, Foo.class );
		QueryBinder.bind( new AnnotationBindingContextImpl( meta, index ) );
	}

	@Test
	public void testResultClass() {
		@NamedNativeQuery(name = "fubar", query = "SELECT * FROM FOO", resultClass = Foo.class)
		class Foo {
		}
		Index index = JandexHelper.indexForClass( service, Foo.class );
		QueryBinder.bind( new AnnotationBindingContextImpl( meta, index ) );

		NamedSQLQueryDefinition namedQuery = meta.getNamedNativeQuery( "fubar" );
		assertNotNull( namedQuery );
		NativeSQLQueryReturn queryReturns[] = namedQuery.getQueryReturns();
		assertTrue( "Wrong number of returns", queryReturns.length == 1 );
		assertTrue( "Wrong query return type", queryReturns[0] instanceof NativeSQLQueryRootReturn );
		NativeSQLQueryRootReturn rootReturn = (NativeSQLQueryRootReturn) queryReturns[0];
		assertEquals( "Wrong result class", Foo.class.getName(), rootReturn.getReturnEntityName() );
	}
}


text:
from unittest import TestCase

from PySide.QtGui import QApplication, QPushButton, QVBoxLayout

from qtlayoutbuilder.lib.builder import Builder
from qtlayoutbuilder.lib.multiline_string_utils import MultilineString
from qtlayoutbuilder.lib_test.test_utils import \
    raises_layout_error_with_this_message, \
    raises_layout_error_with_this_approximately_this_message

class TestBuilder(TestCase):
    @classmethod
    def setUpClass(cls):
        # Needs QApplication context.
        super(TestBuilder, cls).setUpClass()
        try:
            QApplication([])
        except RuntimeError:
            pass  # Singleton already exists

    # -------------------------------------------------------------------------
    # Test utilities and helpers, bottom up first to make sure we can
    # rely on what they say when debugging problems from higher level tests.

    # -------------------------------------------------------------------------
    # Assertions and error reporting.

    def test_error_message_when_tabs_are_present(self):
        str_input = """
            page        \t QLabel
        """
        result = raises_layout_error_with_this_message("""
                This line contains a tab - which is not allowed.
                (This line: <page        \t QLabel>)
                (Line number: 1, from unit test provenance)
            """, Builder.build, str_input, 'unit test provenance')
        if not result:
            self.fail()

    def test_error_message_when_indent_is_not_multiple_of_two(self):
        str_input = """
            page        QLabel
             layout     QHBoxLayout
        """
        result = raises_layout_error_with_this_message("""
                A line is indented by 1 spaces.
                Indentation spaces must be a multiple of 2.
                (This line: < layout     QHBoxLayout>)
                (Line number: 2, from unit test provenance)
            """, Builder.build, str_input, 'unit test provenance')
        if not result:
            self.fail()

    def test_error_message_when_too_many_words_per_line(self):
        str_input = """
            page        QLabel  QLabel
        """
        result = raises_layout_error_with_this_message("""
            Cannot split this line, into exactly two words,
            (after comments and parenthesis have been removed.)
            (This line: <page        QLabel  QLabel>)
            (Line number: 1, from unit test provenance)
            """, Builder.build, str_input, 'unit test provenance')
        if not result:
            self.fail()

    def test_error_message_when_too_few_words_per_line(self):
        str_input = """
            page
        """
        result = raises_layout_error_with_this_message("""
            Cannot split this line, into exactly two words,
            (after comments and parenthesis have been removed.)
            (This line: <page>)
            (Line number: 1, from unit test provenance)
            """, Builder.build, str_input, 'unit test provenance')
        if not result:
            self.fail()

    def test_error_message_when_skip_indent_levels(self):
        str_input = """
            page        QWidget
                layout    QVBoxLayout
        """
        result = raises_layout_error_with_this_message("""
            This line is indented too much.
            It cannot be indented relative to the line
            above it by more than 2 spaces.
            (This line: <    layout    QVBoxLayout>)
            (Line number: 2, from unit test provenance)
            """, Builder.build, str_input, 'unit test provenance')
        if not result:
            self.fail()

    def test_error_message_when_no_meaningful_input_found(self):
        str_input = """
            # Hello
        """
        result = raises_layout_error_with_this_message("""
                This input provided (unit test provenance) contains nothing, or
                nothing except whitespace and comments.
            """, Builder.build, str_input, 'unit test provenance')
        if not result:
            self.fail()

    def test_error_message_when_set_text_fails(self):
        # You can't call setText('hello') on a QVBoxLayout.
        str_input = """
            layout      QVBoxLayout(hello)
        """
        result = raises_layout_error_with_this_message("""
            Cannot do anything with the text you specified
            in parenthesis because the object being created
            has neither of the following methods: setText(), or setTitle().
            (This line: <layout      QVBoxLayout(hello)>)
            (Line number: 1, from unit test provenance)
            """, Builder.build, str_input, 'unit test provenance')
        if not result:
            self.fail()

    def test_error_message_when_name_is_not_unique(self):
        # Names must be unique.
        str_input = """
            foo      QVBoxLayout
              bar    QGroupBox
              bar    QLabel
        """
        result = raises_layout_error_with_this_message("""
            The name you have given this item (<bar>), has already
            been used.
            (This line: <  bar    QLabel>)
            (Line number: 3, from unit test provenance)
            """, Builder.build, str_input, 'unit test provenance')
        if not result:
            self.fail()

    # -------------------------------------------------------------------------
    # API Level

    # -------------------------------------------------------------------------
    # Simplest possible input.

    def test_simplest_possible_runs_without_crashing(self):
        str_input = """
            page        QWidget
              layout    QVBoxLayout
        """
        Builder.build(str_input, 'unit test provenenance')

    def test_simplest_possible_dump_of_contents_is_correct(self):
        str_input = """
            page        QWidget
              layout    QVBoxLayout
        """
        layouts_created = Builder.build(str_input, 'unit test provenenance')
        dumped = MultilineString.normalise(layouts_created.dump())
        expected = MultilineString.normalise("""
            page           QWidget
            page.layout    QVBoxLayout
        """)
        self.assertEqual(dumped, expected)

    def test_querying_accessor_normal_working(self):
        str_input = """
            layout       QVBoxLayout
              foo_n1     QLabel
              foo_n2     QPushButton
              foo_n3     QTextEdit
        """
        layouts_created = Builder.build(str_input, 'unit test provenenance')
        found = layouts_created.at('foo_n2')
        self.assertTrue(isinstance(found, QPushButton))

    def test_querying_accessor_error_msg_for_none_found(self):
        str_input = """
            layout       QVBoxLayout
              foo        QLabel
              bar        QPushButton
              baz        QTextEdit
        """
        layouts_created = Builder.build(str_input, 'unit test provenance')
        result = raises_layout_error_with_this_message("""
            No path can be found that ends with <harry>.
            These are the paths that do exist:

            layout        QVBoxLayout
            layout.foo    QLabel
            layout.bar    QPushButton
            layout.baz    QTextEdit
        """, layouts_created.at, 'harry')
        if not result:
            self.fail()

    def test_simplest_possible_creates_parent_child_relations(self):
        str_input = """
            page        QWidget
              layout    QVBoxLayout
        """
        layouts_created = Builder.build(str_input, 'unit test provenenance')
        page = layouts_created.at('page')
        self.assertTrue(isinstance(page.layout(), QVBoxLayout))

    def test_sibling_child_additions_work(self):
        str_input = """
            layout      QVBoxLayout
              a         QLabel
              b         QLabel
              c         QLabel
        """
        layouts_created = Builder.build(str_input, 'unit test provenenance')
        MultilineString.normalise(layouts_created.dump())
        layout = layouts_created.at('layout')
        self.assertEqual(layout.count(), 3)

    def test_multi_level_descent_works(self):
        str_input = """
            page          QWidget
              layout      QVBoxLayout
                a         QLabel
                b         QLabel
                c         QLabel
        """
        layouts_created = Builder.build(str_input, 'unit test provenenance')
        dumped = MultilineString.normalise(layouts_created.dump())
        expected = MultilineString.normalise("""
            page             QWidget
            page.layout      QVBoxLayout
            page.layout.a    QLabel
            page.layout.b    QLabel
            page.layout.c    QLabel
        """)
        self.assertEqual(dumped, expected)

    def test_multi_level_descent_and_ascent_works(self):
        str_input = """
            page           QWidget
              vlayout      QVBoxLayout
                a          QLabel
                b          QLabel
                fred       QWidget
                  hlayout  QHBoxLayout
                    lbl    QLabel
                c          QLabel
        """
        layouts_created = Builder.build(str_input, 'unit test provenenance')
        dumped = MultilineString.normalise(layouts_created.dump())
        expected = MultilineString.normalise("""
            page                             QWidget
            page.vlayout                     QVBoxLayout
            page.vlayout.a                   QLabel
            page.vlayout.b                   QLabel
            page.vlayout.fred                QWidget
            page.vlayout.fred.hlayout        QHBoxLayout
            page.vlayout.fred.hlayout.lbl    QLabel
            page.vlayout.c                   QLabel
        """)
        self.assertEqual(dumped, expected)
        layout = layouts_created.at('vlayout')
        self.assertEqual(layout.count(), 4)

    def test_more_than_one_top_level_object_works(self):
        str_input = """
            page1          QWidget
              layout1      QVBoxLayout
            page2          QWidget
              layout2      QVBoxLayout
        """
        layouts_created = Builder.build(str_input, 'unit test provenenance')
        dumped = MultilineString.normalise(layouts_created.dump())
        expected = MultilineString.normalise("""
            page1            QWidget
            page1.layout1    QVBoxLayout
            page2            QWidget
            page2.layout2    QVBoxLayout
        """)
        self.assertEqual(dumped, expected)
        widget = layouts_created.at('page2')
        self.assertTrue(isinstance(widget.layout(), QVBoxLayout))

    def test_adding_text_unicode_decode_works(self):
        str_input = """
            page        QWidget
              layout    QHBoxLayout
                label       QLabel(\u25c0)
        """
        layouts_created = Builder.build(str_input, 'unit test provenenance')
        label = layouts_created.at('label')
        txt = label.text()
        self.assertEqual(txt, u'\u25c0')

    def test_adding_text_unicode_decode_error_reporting(self):
        # The \u encoded unicode code-point, has only 3 ascii characters
        # following. Well formed needs 4.
        str_input = """
            page        QWidget
              layout    QHBoxLayout
                label       QLabel(\u25c)
        """
        # Use the approx test, because the python exception is a long line
        # and gets messed up with auto reformat of the source.
        result = raises_layout_error_with_this_approximately_this_message("""
            Python raised an exception when the builder tried to
            deal with unicode encoded values in your text: <\u25c>. The
            underlying python error was:
            'rawunicodeescape' codec can't decode bytes in position
            0-4: truncated \uXXXX
            (This line: <    label       QLabel(\u25c) >)
            (Line number: 3, from unit test provenance)
            """, Builder.build, str_input, 'unit test provenance')
        if not result:
            self.fail()

    def test_adding_text_works_using_set_text_works(self):
        str_input = """
            label       QLabel(hello)
        """
        layouts_created = Builder.build(str_input, 'unit test provenenance')
        widget = layouts_created.at('label')
        self.assertEqual(widget.text(), 'hello')

    def test_adding_text_works_using_set_title(self):
        str_input = """
            group       QGroupBox(hello)
        """
        layouts_created = Builder.build(str_input, 'unit test provenenance')
        widget = layouts_created.at('group')
        self.assertEqual(widget.title(), 'hello')

_MOCK_LINE = 'mock line'


text:
Local<Function>::New(Isolate::GetCurrent(), pfn)
#else
#define BUFFER_TYPE Buffer*
#define BUFFER_TO_HANDLE(ARG) Local<Value>::New((ARG)->handle_)
#define RETURN_TYPE Handle<Value>
#define RETURN(v) return scope.Close(v)
#define ARGUMENTS Arguments
#define LOCAL_VALUE(h) Local<Value>(*h)
#define FUNCTION_TO_PERSIST(pfn, fn) pfn = Persistent<Function>::New(fn)
#define FUNCTION_TO_HANDLE(pfn) Local<Function>::New(pfn)
#endif


text:
layout: post
title: "The Swift Programming Language (Swift 2) -7 Generics"
description: ""
category: swift
tags: [swift]
---

###

{% highlight swift %}
//: ## Generics
//:
//: Write a name inside angle brackets to make a generic function or type.
//:
func repeatItem<Item>(item: Item, numberOfTimes: Int) -> [Item] {
    var result = [Item]()
    for _ in 0..<numberOfTimes {
         result.append(item)
    }
    return result
}
repeatItem("knock", numberOfTimes:4)

//: You can make generic forms of functions and methods, as well as classes, enumerations, and structures.
//:
// Reimplement the Swift standard library's optional type
enum OptionalValue<Wrapped> {
    case None
    case Some(Wrapped)
}
var possibleInteger: OptionalValue<Int> = .None
possibleInteger = .Some(100)

//: Use `where` after the type name to specify a list of requirements—for example, to require the type to implement a protocol, to require two types to be the same, or to require a class to have a particular superclass.
//:
func anyCommonElements <T: SequenceType, U: SequenceType where T.Generator.Element: Equatable, T.Generator.Element == U.Generator.Element> (lhs: T, _ rhs: U) -> Bool {
    for lhsItem in lhs {
        for rhsItem in rhs {
            if lhsItem == rhsItem {
                return true
            }
        }
    }
   return false
}
anyCommonElements([1, 2, 3], [3])

//: > **Experiment**:
//: > Modify the `anyCommonElements(_:_:)` function to make a function that returns an array of the elements that any two sequences have in common.
//:
//: Writing `<T: Equatable>` is the same as writing `<T where T: Equatable>`.
//:

//: [Previous](@previous)
{% endhighlight %}


text:
namespace Naru.Concurrency.Scheduler
{
    public interface INewThreadScheduler : IRXScheduler
    {
    }
}


text:
import functools
import os

import pytest

from limejudge import anscompare

def test_compare_no_extra_ws(tmpdir):
    outfile = tmpdir.join('outfile')
    ansfile = tmpdir.join('ansfile')
    outname = str(outfile)
    ansname = str(ansfile)
    nonexistent = os.path.join(str(tmpdir), 'nonexistent')

    cmp_noextraws = functools.partial(anscompare.compare, 'no-extra-ws')

    # Same content
    outfile.write('1234abcd\nefgh5678\n')
    ansfile.write('1234abcd\nefgh5678\n')
    assert cmp_noextraws(None, outname, ansname, 42) == 42
    assert cmp_noextraws('ignored', outname, ansname, 42) == 42

    # Different content
    outfile.write('1234abcd\nefgh5678\n')
    ansfile.write('1234abcd\nefgh5679\n')
    assert cmp_noextraws(None, outname, ansname, 42) == 0

    # Ignore trailing whitespace
    outfile.write('1234abcd  \t\r\nefgh')
    ansfile.write('1234abcd\nefgh\n\r\n')
    assert cmp_noextraws(None, outname, ansname, 42) == 42

    # Don't ignore leading whitespace
    outfile.write(' 1234abcd\n')
    ansfile.write('1234abcd\n')
    assert cmp_noextraws(None, outname, ansname, 42) == 0

    # Non-existent files
    assert cmp_noextraws(None, nonexistent, ansname, 42) == 0
    assert cmp_noextraws(None, outname, nonexistent, 42) == 0
    assert cmp_noextraws(None, '', '', 42) == 0

def test_compare_spj(tmpdir):
    infile = tmpdir.join('infile')
    outfile = tmpdir.join('outfile')
    ansfile = tmpdir.join('ansfile')
    inname = str(infile)
    outname = str(outfile)
    ansname = str(ansfile)
    spjpath = os.path.join(os.path.dirname(__file__), 'progs', 'spj.py')
    relspjpath = os.path.relpath(spjpath)

    cmp_spj = functools.partial(anscompare.compare,
                                'special-judge:' + spjpath)
    cmp_relspj = functools.partial(anscompare.compare,
                                   'special-judge:' + relspjpath)

    # Call special judge with absolute or relative path
    infile.write('input')
    ansfile.write('answer')
    outfile.write('score 5')
    assert cmp_spj(inname, outname, ansname, 42) == 5
    assert cmp_relspj(inname, outname, ansname, 42) == 5

    # Input is checked correctly
    infile.write('bad-input')
    ansfile.write('answer')
    outfile.write('score 5')
    assert cmp_spj(inname, outname, ansname, 42) == 0

    # Answer is checked correctly
    infile.write('input')
    ansfile.write('bad-answer')
    outfile.write('score 5')
    assert cmp_spj(inname, outname, ansname, 42) == 0

    # Output is checked correctly
    infile.write('input')
    ansfile.write('answer')
    outfile.write('bad-score 5')
    assert cmp_spj(inname, outname, ansname, 42) == 0

    # Scores out of bound is returned as-is
    infile.write('input')
    ansfile.write('answer')
    outfile.write('score -1')
    assert cmp_spj(inname, outname, ansname, 42) == -1

    infile.write('input')
    ansfile.write('answer')
    outfile.write('score 43')
    assert cmp_spj(inname, outname, ansname, 42) == 43

def test_compare_invalid():
    with pytest.raises(ValueError) as err:
        anscompare.compare('invalid-comp-type', None, None, None, 0)
    assert 'Unknown comparison type:' in str(err)


text:
class ProfileVariant(dict):
    """Represent a profile variant

    These variants will be used to profile samples, based on a samples genotype
    at these positions.
    """

    def __init__(self, variant_id, chrom, pos, ref, alt, maf, id_column=None):
        super(ProfileVariant, self).__init__(
            _id=variant_id, chrom=chrom, pos=pos, ref=ref, alt=alt, maf=maf, id_column=id_column
        )


text:
package com.nearinfinity.honeycomb.config;

import static java.lang.String.format;

import java.io.File;
import java.io.InputStream;
import java.util.List;
import java.util.Map;

import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.apache.log4j.Logger;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.common.io.Files;
import com.google.common.io.InputSupplier;
import com.nearinfinity.honeycomb.util.Verify;

/**
 * Provides capabilities for validation and parsing of the application configuration content
 */
public class ConfigurationParser {
    private static final Logger logger = Logger.getLogger(ConfigurationParser.class);

    /**
     * XPath query to find adapter names from document.
     */
    private static final String QUERY_ADAPTER_NAMES = "/options/adapters/adapter/@name";

    /**
     * XPath query to find adapter configuration options from document
     */
    private static final String QUERY_ADAPTER_CONFIG_NODES = "/options/adapters/adapter[@name='%s']/configuration/*";

    private static final String QUERY_DEFAULT_ADAPTER = "/options/defaultAdapter";

    private static final XPath xPath = XPathFactory.newInstance().newXPath();

    private ConfigurationParser() {}

    /**
     * Create a {@link HoneycombConfiguration} from a configuration file path and configuration
     * schema validator path.
     *
     * @param configPath Path to configuration file to be parsed
     * @param schemaPath Path to schema file to be validated against
     * @return ConfigurationParser object holding configuration options
     */
    public static HoneycombConfiguration parseConfiguration(String configPath,
                                                            String schemaPath) {
        Verify.isNotNullOrEmpty(configPath);
        Verify.isNotNullOrEmpty(schemaPath);

        final File configFile = new File(configPath);
        final File schemaFile = new File(schemaPath);

        checkFileAvailable(configFile);
        checkFileAvailable(schemaFile);

        final InputSupplier<? extends InputStream> configSupplier =
                Files.newInputStreamSupplier(configFile);
        final InputSupplier<? extends InputStream> schemaSupplier =
                Files.newInputStreamSupplier(schemaFile);

        checkValidConfig(configSupplier, schemaSupplier);
        Document doc = parseDocument(configSupplier);
        Map<String, Map<String, String>> adapters = parseAdapters(doc);
        String defaultAdapter = parseDefaultAdapter(doc);
        return new HoneycombConfiguration(adapters, defaultAdapter);
    }

    /**
     * Performs validation on the configuration content supplied by the
     * configuration supplier against the schema document provided by the
     * validation supplier.  Throws Runtime exception if validation fails.
     *
     * @param configSupplier The supplier that provides the configuration to inspect, not null
     * @param schemaSupplier The supplier that provides the schema used to inspect the configuration, not null
     */
    private static void checkValidConfig(final InputSupplier<? extends InputStream> configSupplier,
                                         final InputSupplier<? extends InputStream> schemaSupplier) {
        try {
            final SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
            final Schema schema = schemaFactory.newSchema(new StreamSource(schemaSupplier.getInput()));
            final Validator validator = schema.newValidator();
            validator.validate(new StreamSource(configSupplier.getInput()));
        } catch (Exception e) {
            logger.error("Unable to validate honeycomb configuration.", e);
            throw new RuntimeException("Exception while validating honeycomb configuration.", e);
        }
    }

    /**
     * Checks if the file is accessible and available for reading
     *
     * @param file The file to inspect
     * @return True if file is available, False otherwise
     */
    private static boolean checkFileAvailable(final File file) {
        if (!(file.exists() && file.canRead() && file.isFile())) {
            final String errorMsg = format("%s is not readable.", file.getAbsolutePath());
            logger.fatal(errorMsg);
            throw new RuntimeException(errorMsg);
        }

        return true;
    }

    /**
     * Parses the application configuration and returns the XML document.
     * @param configSupplier File supplier containing application configuration
     * @return XML Document
     */
    private static Document parseDocument(final InputSupplier<? extends InputStream> configSupplier) {
        try {
            return DocumentBuilderFactory
                    .newInstance()
                    .newDocumentBuilder()
                    .parse(configSupplier.getInput());

        } catch (Exception e) {
            logger.error("Unable to parse honeycomb configuration.", e);
            throw new RuntimeException("Exception while parsing honeycomb configuration.", e);
        }
    }

    /**
     * Determines if the option name is already namespaced (contains a '.').
     * @param optionName
     * @return
     */
    private static boolean isNamespaced(String optionName) {
        return optionName.contains(".");
    }

    /**
     * Namespaces the given option name by {@value Constants#HONEYCOMB_NAMESPACE} and the adapter type.
     * @param adapterName
     * @param optionName
     * @return
     */
    private static String prependNamespace(String adapterName, String optionName) {
        return Constants.HONEYCOMB_NAMESPACE + "." + adapterName + "." + optionName;
    }

    private static Map<String, String> parseOptions(String adapterName, Document doc) {
        String optionsQuery = String.format(QUERY_ADAPTER_CONFIG_NODES, adapterName);
        NodeList optionNodes;
        try {
            optionNodes = (NodeList) xPath.evaluate(optionsQuery, doc, XPathConstants.NODESET);
        } catch (XPathExpressionException e) {
            logger.error("Unable to parse options for " + adapterName + " adapter.", e);
            throw new RuntimeException("Exception while parsing options for " + adapterName + " adapter.", e);
        }
        ImmutableMap.Builder<String, String> options = ImmutableMap.builder();

        for (int i = 0; i < optionNodes.getLength(); i++) {
            Node optionNode = optionNodes.item(i);
            if (optionNode.getNodeType() == Node.ELEMENT_NODE) {
                String optionName = optionNode.getNodeName();
                String namespacedOptionName = isNamespaced(optionName)
                        ? optionName
                        : prependNamespace(adapterName, optionName);
                options.put(namespacedOptionName, optionNode.getTextContent());
            }
        }

        return options.build();
    }

    private static Map<String, Map<String, String>> parseAdapters(Document doc) {
        // Extract adapter names from document
        NodeList adapterNameNodes;
        try {
            adapterNameNodes = (NodeList) xPath.evaluate(QUERY_ADAPTER_NAMES, doc, XPathConstants.NODESET);
        } catch (XPathExpressionException e) {
            logger.error("Unable to parse adapter names from honeycomb configuration.", e);
            throw new RuntimeException("Exception while parsing adapter names from honeycomb configuration.", e);
        }
        List<String> adapterNames = Lists.newArrayList();
        for (int i = 0; i < adapterNameNodes.getLength(); i++) {
            Node adapterNameNode = adapterNameNodes.item(i);
            if (adapterNameNode.getNodeType() == Node.ATTRIBUTE_NODE) {
                adapterNames.add(adapterNameNode.getNodeValue());
            }
        }

        // Extract individual adapter options from the document
        ImmutableMap.Builder<String, Map<String, String>> adapters = ImmutableMap.builder();
        for (String adapterName : adapterNames) {
            adapters.put(adapterName, parseOptions(adapterName, doc));
        }

        return adapters.build();
    }

    private static String parseDefaultAdapter(Document doc) {
        try {
            Node defaultAdapterNode = (Node) xPath.evaluate(QUERY_DEFAULT_ADAPTER, doc, XPathConstants.NODE);
            return defaultAdapterNode.getTextContent();
        } catch (XPathExpressionException e) {
            logger.error("Unable to parse default adapter from honeycomb configuration.", e);
            throw new RuntimeException("Exception while parsing default adapter from honeycomb configuration.", e);        }
    }
}


text:
module.exports = function (routes, optionsFn) {
    optionsFn("/", function (req, res) {
        res.contentType("application/json");

        res.send(routes);
    });
};


text:
'use strict';

const path = require('path');
const mustacheExpress = require('mustache-express');

const {when} = require('jest-when');
const request = require('supertest');

const { google } = require('googleapis');
jest.mock('googleapis');

const auth = require('../../auth');
jest.mock('../../auth');

const userService = require('../../services/user-service');

const index = require('../../routes/index');
const express = require('express');

const OLD_ENV = process.env;
let app = express();

app.set('views', path.join(__dirname, '../../views'));
app.engine('mustache', mustacheExpress());
app.set('view engine', 'mustache');

app.use("/", index);

beforeEach(() => {
    jest.resetModules();

    process.env = {...OLD_ENV};
    delete process.env.NODE_ENV;

    process.env.GAE_APPLICATION = "true";
});

afterEach(() => {
    process.env = OLD_ENV;
});

describe('GET /', () => {
    test('unknown user redirects to OAuth2 auth URL', (done) => {
        const userEmail = 'unknown@domain.com';
        const url = 'https://oauth2-url'

        const generateAuthUrlFn = jest.fn();
        when(generateAuthUrlFn)
            .expectCalledWith({
                access_type: 'online',
                scope: ['https://www.googleapis.com/auth/userinfo.profile'],
                login_hint: userEmail,
            })
            .mockReturnValueOnce(url);

        auth.getOAuth2Client.mockResolvedValue({
            generateAuthUrl: generateAuthUrlFn
        });

        request(app)
            .get('/')
            .set('X-Goog-Authenticated-User-Email', `accounts.google.com:${userEmail}`)
            .expect(302)
            .expect('Location', url, done);
    });

    test('known user renders the index', (done) => {
        const henry = {email: 'henry@domain.com', displayName: 'Henry'};

        userService.saveUser(henry);

        request(app)
            .get('/')
            .set('X-Goog-Authenticated-User-Email', `accounts.google.com:${henry.email}`)
            .expect(200)
            .expect('Content-Type', /text\/html/)
            .end(function(err, res) {
                expect(res.text).toContain(henry.displayName);
                expect(res.text).toContain(henry.email);

                if (err) return done(err);
                done();
            });
    });
});

describe('/auth-callback', () => {
    test('user info retrieved and renders the index', async (done) => {
        const email = 'henry-callback@domain.com';
        const henryCallbackUser = {email: email, displayName: 'Henry Callback', photoUrl: 'https://henry-callback-photo-url'};
        const authCode = 'auth-code';
        const tokens = {access_token: 'token'};

        const getTokenFn = jest.fn();
        when(getTokenFn)
            .expectCalledWith(authCode)
            .mockReturnValue(tokens);

        const setCredentialsFn = jest.fn();
        when(setCredentialsFn)
            .expectCalledWith(tokens);

        const mockOAuth2Client = {
            getToken: getTokenFn,
            setCredentials: setCredentialsFn
        };
        auth.getOAuth2Client.mockResolvedValue(mockOAuth2Client);

        const peopleResponse = {
            data: {
                names: [{displayName: henryCallbackUser.displayName}],
                photos: [{url: henryCallbackUser.photoUrl}]
            }
        };

        const mockPeopleGetFn = jest.fn();
        when(mockPeopleGetFn)
            .expectCalledWith({
                resourceName: 'people/me',
                personFields: 'emailAddresses,names,photos',
            })
            .mockResolvedValue(peopleResponse);

        const mockPeopleApi = {
            people: {
                get: mockPeopleGetFn
            }
        }

        when(google.people)
            .calledWith({
                version: 'v1',
                auth: mockOAuth2Client
            })
            .mockReturnValue(mockPeopleApi);

        request(app)
            .get(`/auth-callback?code=${authCode}`)
            .set('X-Goog-Authenticated-User-Email', `accounts.google.com:${email}`)
            .expect(302)
            .expect('Location', '/')
            .end(async function(err, res) {
                const actualUser = await userService.getUserByEmail(email);
                expect(actualUser).toEqual(henryCallbackUser);

                if (err) return done(err);
                done();
            });
    });
});


text:
namespace document {
    class ByteBuffer;
}
namespace vespalib {
    class GrowableByteBuffer;
}

namespace documentapi {

class DocumentState {
    std::unique_ptr<document::DocumentId> _docId;
    document::GlobalId _gid;
    uint64_t _timestamp;
    bool _removeEntry;

public:
    DocumentState();
    DocumentState(const DocumentState&);
    DocumentState(const document::DocumentId&,
                  uint64_t timestamp, bool removeEntry);
    DocumentState(const document::GlobalId&,
                  uint64_t timestamp, bool removeEntry);
    DocumentState(document::ByteBuffer &buf);

    DocumentState& operator=(const DocumentState&);

    void serialize(vespalib::GrowableByteBuffer &buf) const;

    const document::GlobalId& getGlobalId() const { return _gid; }
    const document::DocumentId* getDocumentId() const { return _docId.get(); }
    uint64_t getTimestamp() const { return _timestamp; }
    bool isRemoveEntry() const { return _removeEntry; }
};

} // documentapi


text:
package ve.com.abicelis.chefbuddy.views;

import android.content.Context;
import android.content.res.TypedArray;
import android.support.annotation.DrawableRes;
import android.support.annotation.Nullable;
import android.support.annotation.StringRes;
import android.text.InputFilter;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;

import butterknife.BindView;
import butterknife.ButterKnife;
import ve.com.abicelis.chefbuddy.R;

/**
 * Created by abicelis on 14/7/2017.
 */

public class FancyEditText extends LinearLayout {

    @BindView(R.id.fancy_edit_text_view_icon)
    ImageView mIcon;

    @BindView(R.id.fancy_edit_text_view_edit_text)
    EditText mEditText;

    public FancyEditText(Context context) {
        super(context);
        init(context, null);
    }
    public FancyEditText(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs);
    }
    public FancyEditText(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs);
    }

    private void init(Context context, @Nullable AttributeSet attrs) {

        LayoutInflater inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        inflater.inflate(R.layout.fancy_edit_text, this);

        ButterKnife.bind(this);

        //Get/apply custom xml configs
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.fancy_edit_text);
        int iconId = a.getResourceId(R.styleable.fancy_edit_text_icon, -1);
        int textId = a.getResourceId(R.styleable.fancy_edit_text_text, -1);
        int hintId = a.getResourceId(R.styleable.fancy_edit_text_hint, -1);
        int maxLines = a.getInt(R.styleable.fancy_edit_text_maxLines, -1);

        setIcon(iconId);
        setText(textId);
        setHint(hintId);
        setMaxLines(maxLines);
        a.recycle();

        this.setBackgroundResource(R.drawable.white_round_edges_background);
        this.setGravity(Gravity.CENTER_VERTICAL);
    }

    public void setIcon(@DrawableRes int iconRes) {
        if (iconRes != -1) {
            mIcon.setVisibility(View.VISIBLE);
            mIcon.setImageResource(iconRes);
        } else {
            mIcon.setVisibility(View.GONE);
        }
    }

    public void setHint(String hint) {
        mEditText.setHint(hint);
    }
    public void setHint(@StringRes int hintId) {
        if (hintId != -1)
            mEditText.setHint(hintId);
    }

    public void setMaxLenght(int lenght) {
        mEditText.setFilters( new InputFilter[] { new InputFilter.LengthFilter(lenght) } );
    }

    public void setMaxLines(int maxLines) {
        if(maxLines != -1) {
            mEditText.setMaxLines(maxLines);
            if(maxLines == 1)
                mEditText.setSingleLine();
        }
    }

    public void setText(String text) {
        mEditText.setText(text);
    }
    public void setText(@StringRes int textId) {
        if (textId != -1)
            mEditText.setText(textId);
    }
    public String getText() {
        return mEditText.getText().toString();
    }

}


text:
const PlotCard = require('../../../plotcard.js');

class Summons extends PlotCard {
    setupCardAbilities() {
        this.whenRevealed({
            handler: () => {
                this.game.promptForDeckSearch(this.controller, {
                    numCards: 10,
                    activePromptTitle: 'Select a card to add to your hand',
                    cardType: 'character',
                    onSelect: (player, card) => this.cardSelected(player, card),
                    onCancel: player => this.doneSelecting(player),
                    source: this
                });
            }
        });
    }

    cardSelected(player, card) {
        player.moveCard(card, 'hand');
        this.game.addMessage('{0} uses {1} to reveal {2} and add it to their hand', player, this, card);
    }

    doneSelecting(player) {
        this.game.addMessage('{0} does not use {1} to add a card to their hand', player, this);
    }
}

Summons.code = '01022';

module.exports = Summons;


text:
package test

import "testing"

func TestNoticeWithNoParams(t *testing.T) {
	with(t, func(a *TestClient) {
		a.Authenticate()

		a.Send("NOTICE")
		assertResponse(t, a, ":test.irc 461 NOTICE :Not enough parameters")
	})
}

func TestNoticeWithNoMessage(t *testing.T) {
	with(t, func(a *TestClient) {
		a.Authenticate()

		a.Send("NOTICE missing")
		assertResponse(t, a, ":test.irc 461 NOTICE :Not enough parameters")
	})
}

func TestNoticeToUser(t *testing.T) {
	with2(t, func(a, b *TestClient) {
		a.Authenticate()
		b.Authenticate()

		const msg = "Hey I have a message"
		a.Send("NOTICE " + b.nickName + " :" + msg)
		assertResponse(t, b, a.Prefix() + " NOTICE " + b.nickName + " :" + msg)
	})
}

func TestNoticeToChannel(t *testing.T) {
	with2(t, func(a, b *TestClient) {
		a.Authenticate()
		b.Authenticate()

		a.Send("JOIN #test")
		getResponse(a)
		getResponse(a)
		b.Send("JOIN #test")
		getResponse(a)
		getResponse(b)
		getResponse(b)

		msg := "Hey I have a message"
		a.Send("NOTICE #test :" + msg)
		assertResponse(t, b, a.Prefix() + " NOTICE #test :" + msg)

		msg = "Ok"
		b.Send("NOTICE #test :" + msg)
		assertResponse(t, a, b.Prefix() + " NOTICE #test :" + msg)
	})
}


text:
#ifndef __TESTLIB_H__

void getRandomBytes(void *p_dest, unsigned p_size);
void vli_print(uint8_t *p_vli, unsigned int p_size);
int get_vli(char *buf, char *key, uint8_t vli[NUM_ECC_DIGITS]);
int test_key(uint8_t secret[NUM_ECC_DIGITS], EccPoint *pub);

#endif /* __TESTLIB_H__ */


text:
git branch -D gh-pages
git push origin --delete gh-pages
git checkout --orphan gh-pages

mv docs/source/index.rst docs/source/index.rst.bak
mv docs/source/maddux.rst docs/source/old_maddux.rst

rm docs/source/maddux* docs/source/modules*
sphinx-apidoc -o docs/source/ maddux/

mv docs/source/index.rst.bak docs/source/index.rst
mv docs/source/old_maddux.rst docs/source/maddux.rst

cd docs
make html
cd ..

touch .nojekyll
cp -r docs/build/html/* .

git add -A
git commit -m "Updating Github Pages"
git push origin gh-pages
git checkout master


text:
package sexy

type SxyObject struct {
    goValue   interface {}
    messages  map[*SxySymbol]SxyObj
    autos     map[*SxySymbol]bool
    resends   map[*SxySymbol]SxyObj
    defProc   SxyObj
}

var SxyObjBuiltIns map[string]bool{
    "answers?": true,
    "autos": true,
    "default": true,
    "messages": true,
    "resends": true,
    "to-bool": true,
    "to-text": true,
    "to-literal": true,
    "type": true,
    "view": true
}

func init () {

}

func CreateObject (msgs []SxyObject, ottos []SxyObject, rsends, dProc SxyObj) SxyObject {

}

func (obj SxyObject) Answers (msg SxySymbol) SxyBool {
    val, ok := messages[*msg]

    if ok {
        return ok
    }

    val, ok = resends[*msg]

    if ok {
        return ok
    }

    return false
}

func (obj SxyObject) Autos () SxyPair {
    for m, _a := range obj.autos {
        // make list of pairs and return
    }
}

func (obj SxyObject) Default () SxyProc {
    return obj.defProc
}

func (obj *SxyObject) Messages () (rv SxyPair) {
    // messages + resends
    for m, _ := range obj.messages {
        // make list of pairs
    }

    rs := obj.Resends()

    return ms + rs
}

func (obj SxyObject) Resends () (rv SxyPair) {
    for r, _ := range obj.resends {
        // make list of pairs
    }

    return rv
}

func (obj *SxyObject) Send (msg SxySymbol, ukont Sxyλ, ekont Sxyλ) SxyThing {
    val, ok := messages[*msg]

    if ok {
        _, isAuto = autos[*msg]

        if isAuto {
            // exec and return value
        }

        return val
    }

    val, ok = resends[*msg]

    if ok {
        return val
    }

    obj.defProc.apply(msg) // probably needs to be a list... we'll see
}

func (obj SxyObject) ToBool (rv SxyBool) {
    return true
}

func (obj SxyObject) ToText SxyText {
    return "object"
}

func (obj SxyObject) ToLiteral () SxyText {
    return "object"
}

func (obj SxyObject) Type () SxySymbol {
    return SxySymbolTable("object")
}

func (obj SxyObject) View () SxyText {
    return "object"
}


text:
from . import get_connection

def get_image_size():
    select_sql = 'SELECT count(*) FROM image'
    cursor = get_connection().cursor()
    cursor.execute(select_sql)
    result = cursor.fetchone()
    if result == None:
        return 0
    return result[0]

def get_image_list(page_index, page_start):
    select_sql = 'SELECT id, code, upload_time, type, small_url, original_url, file_type, genre FROM image ORDER BY upload_time DESC LIMIT ?, ?'
    cursor = get_connection().cursor()
    cursor.execute(select_sql, (page_index, page_start))
    result = list(map(lambda x: map_image_list(x), cursor))
    return result

def get_image_list_by_ids(id_list):
    id_in = ','.join(str(id) for id in id_list)
    select_sql = 'SELECT id, code, upload_time, type, small_url, original_url, file_type, genre FROM image WHERE id IN (%s)'
    cursor = get_connection().cursor()
    cursor.execute(select_sql % id_in)
    result = list(map(lambda x: map_image_list(x), cursor))
    return result

def map_image_list(row):
    item = {}
    item['id'] = row[0]
    item['code'] = row[1]
    item['upload_time'] = row[2]
    item['type'] = row[3]
    item['small_url'] = row[4]
    item['original_url'] = row[5]
    item['file_type'] = row[6]
    item['genre'] = row[7]
    return item

def get_image_item(image_id):
    select_sql = 'SELECT id, code, upload_time, type, small_url, original_url, file_type, genre, remark FROM image WHERE id = ?'
    cursor = get_connection().cursor()
    cursor.execute(select_sql, (image_id,))
    result = list(map(lambda x: map_image_item(x), cursor))
    if len(result) > 0:
        return result[0]
    return None

def map_image_item(row):
    item = {}
    item['id'] = row[0]
    item['code'] = row[1]
    item['upload_time'] = row[2]
    item['type'] = row[3]
    item['small_url'] = row[4]
    item['original_url'] = row[5]
    item['file_type'] = row[6]
    item['genre'] = row[7]
    item['remark'] = row[8]
    return item

# def post_image(image):
#     if not 'genre' in image:
#         image['genre'] = None
#     if not 'remark' in image:
#         image['remark'] = None
#     insert_sql = 'INSERT INTO image (code, upload_time, type, small_url, original_url, file_type, genre, remark) VALUES (?, ?, ?, ?, ?, ?, ?, ?)'
#     cursor = get_connection().cursor()
#     cursor.execute(insert_sql, (image['code'], image['upload_time'], image['type'], image['small_url'], image['original_url'], image['file_type'], image['genre'], image['remark']))
#     get_connection().commit()
#     return cursor.lastrowid

def post_image_list(image_list):
    insert_sql = 'INSERT INTO image (code, upload_time, type, small_url, original_url, file_type) VALUES (?, ?, ?, ?, ?, ?)'
    insert_list = list(map(lambda x: map_image_insert(x), image_list))
    cursor = get_connection().cursor()
    cursor.executemany(insert_sql, insert_list)
    row_count = cursor.rowcount
    cursor.close()
    get_connection().commit()
    return row_count

def map_image_insert(image):
    return (image['code'], image['upload_time'], image['type'], image['small_url'], image['original_url'], image['file_type'])

# def update_image(image):
#     update_sql = 'UPDATE image SET upload_time = ?, code = ?, type = ?, small_url = ?, original_url = ?, file_type = ?, genre = ?, remark = ? WHERE id = ?'
#     cursor = get_connection().cursor()
#     cursor.execute(update_sql, (image['upload_time'], image['code'], image['type'], image['small_url'], image['original_url'], image['file_type'], image['genre'], image['remark'], image['id']))
#     get_connection().commit()
#     return cursor.rowcount

def update_image_info(image):
    update_sql = 'UPDATE image SET genre = ?, remark = ? WHERE id = ?'
    cursor = get_connection().cursor()
    cursor.execute(update_sql, (image['genre'], image['remark'], image['id']))
    get_connection().commit()
    return cursor.rowcount

def delete_image(image_id):
    delete_sql = 'DELETE FROM image WHERE id = ?'
    cursor = get_connection().cursor()
    cursor.execute(delete_sql, (image_id,))
    get_connection().commit()
    return cursor.rowcount


text:
<?php namespace Arcanedev\LaravelTracker\Contracts\Models;

/**
 * Interface  Route
 *
 * @package   Arcanedev\LaravelTracker\Contracts\Models
 * @author    ARCANEDEV <arcanedev.maroc@gmail.com>
 *
 * @property  \Illuminate\Database\Eloquent\Collection  paths
 */
interface Route
{
    /* -----------------------------------------------------------------
     |  Relationships
     | -----------------------------------------------------------------
     */

    /**
     * Paths relationship.
     *
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function paths();
}


text:
.. Copyright (c) 2007-2019 UShareSoft, All rights reserved

.. _install-mac:

For Mac
=======

For Mac users, you need to have ``XCode`` installed (or any other C compiler).

You can download the latest version of Xcode from the Apple developer website or get it using the Mac App Store

Run the following command to install the latest version of Hammr:

.. code-block:: shell

	$ xcode-select --install
	$ sudo easy_install pip
	$ sudo easy_install readline
	$ sudo easy_install progressbar==2.3
	$ sudo pip install hammr

If you want to install a specific version of Hammr, see :ref:`install-compatibility` to find the compatible version of UForge, and in the code above replace the 'sudo pip install hammr' with:

.. code-block:: shell

	$ sudo pip install hammr==HAMMR-VERSION

If you already have hammr installed and want to upgrade to the latest version you can run:

.. code-block:: shell

	$ pip install --upgrade hammr


text:
package net.digitalid.utility.validation.annotations.file.existence;

import java.io.File;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import javax.annotation.Nonnull;
import javax.lang.model.element.AnnotationMirror;
import javax.lang.model.element.Element;

import net.digitalid.utility.annotations.method.Pure;
import net.digitalid.utility.annotations.ownership.NonCaptured;
import net.digitalid.utility.annotations.parameter.Modified;
import net.digitalid.utility.processing.utility.TypeImporter;
import net.digitalid.utility.validation.annotations.meta.ValueValidator;
import net.digitalid.utility.validation.annotations.type.Stateless;
import net.digitalid.utility.validation.contract.Contract;
import net.digitalid.utility.validation.validators.FileValidator;

/**
 * This annotation indicates that the {@link File#getParentFile() parent directory} of the annotated {@link File file} does not {@link File#exists() exist}.
 *
 * @see ExistentParent
 */
@Documented
@Target({ElementType.TYPE_USE, ElementType.PARAMETER, ElementType.METHOD, ElementType.FIELD, ElementType.LOCAL_VARIABLE})
@Retention(RetentionPolicy.RUNTIME)
@ValueValidator(NonExistentParent.Validator.class)
public @interface NonExistentParent {

    /* -------------------------------------------------- Validator -------------------------------------------------- */

    /**
     * This class checks the use of and generates the contract for the surrounding annotation.
     */
    @Stateless
    public static class Validator extends FileValidator {

        @Pure
        @Override
        public @Nonnull Contract generateContract(@Nonnull Element element, @Nonnull AnnotationMirror annotationMirror, @NonCaptured @Modified @Nonnull TypeImporter typeImporter) {
            return Contract.with("# == null || !#.getAbsoluteFile().getParentFile().exists()", "The parent directory of the # $ may not exist.", element);
        }

    }

}


text:
import argparse
import time
import math
import multiprocessing

import parsl

CORES = multiprocessing.cpu_count()
CORES_PER_WORKER = 1
EXPECTED_WORKERS = math.floor(CORES / CORES_PER_WORKER)

# from parsl.tests.configs.htex_local import config
from htex_local import config
config.executors[0].cores_per_worker = CORES_PER_WORKER
config.executors[0].provider.init_blocks = 1
parsl.set_stream_logger()

# from htex_midway import config
# from htex_swan import config

from parsl.app.app import python_app  # , bash_app
parsl.load(config)

@python_app
def slow_pid(sleep=1):
    import os
    import time
    time.sleep(sleep)
    return os.getppid(), os.getpid()

def test_worker(n=2, sleep=0):
    d = {}
    start = time.time()
    for i in range(0, n):
        d[i] = slow_pid(sleep=sleep)

    foo = [d[i].result() for i in d]
    manager_ids = set([f[0] for f in foo])
    worker_ids = set([f[1] for f in foo])

    print("Got workers : {}".format(worker_ids))
    assert len(manager_ids) == 1, "Expected only 1 manager id, got ids : {}".format(
        manager_ids)
    assert len(worker_ids) == EXPECTED_WORKERS, "Exptected {} workers, instead got {}".format(EXPECTED_WORKERS,
                                                                                len(worker_ids))

    print("Duration : {0}s".format(time.time() - start))
    print("[TEST STATUS] test_parallel_for [SUCCESS]")
    return d

if __name__ == '__main__':

    parser = argparse.ArgumentParser()
    parser.add_argument("-s", "--sleep", default="0")
    parser.add_argument("-c", "--count", default="10",
                        help="Count of apps to launch")
    parser.add_argument("-d", "--debug", action='store_true',
                        help="Count of apps to launch")
    args = parser.parse_args()

    if args.debug:
        parsl.set_stream_logger()

    x = test_worker(n=int(args.count), sleep=float(args.sleep))


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

	<title>Nested TabBars</title>
	<link rel="STYLESHEET" type="text/css" href="../../codebase/dhtmlxtabbar.css">

<link rel='STYLESHEET' type='text/css' href='../common/style.css'>

		Sample: dhtmlxTabbar

		Nested TabBars

		dhtmlxTabbar main page

You can nest tabbars within other tabbars  using setContent method</>
	Attach content to TabBar

<div id="a_tabbar" style="width:400;height:100"></div>
    <script>

        tabbar=new dhtmlXTabBar("a_tabbar","top");
        ...
        tabbar2=new dhtmlXTabBar("html_1","right");
        ...
        tabbar3=new dhtmlXTabBar("html_2","bottom");
        ...
        tabbar.setContent("a1","html_01");
        tabbar.setContent("a2","html_02");
        tabbar.setContentHTML("a3","<br/>The content can be set as <b>HTML</b> node or as <b>HTML</b> text.");

</script>

© DHTMLX LTD. All rights reserved


text:
import chromedriver from 'chromedriver';
import webdriver from 'selenium-webdriver';

export function delay(time) {
  return new Promise(resolve => setTimeout(resolve, time));
}

let crdvIsStarted = false;
export function startChromeDriver() {
  if (crdvIsStarted) return Promise.resolve();
  chromedriver.start();
  process.on('exit', chromedriver.stop);
  crdvIsStarted = true;
  return delay(1000);
}

export function buildWebDriver(extPath) {
  return new webdriver.Builder()
    .usingServer('http://localhost:9515')
    .withCapabilities({
      chromeOptions: {
        args: [`load-extension=${extPath}`]
      }
    })
    .forBrowser('chrome')
    .build();
}


text:
from __future__ import absolute_import

import raven

from raven.utils import six
from raven.utils.imports import import_string

def test_import_string():
    new_raven = import_string('raven')
    assert new_raven is raven

    # this will test unicode on python2
    new_raven = import_string(six.text_type('raven'))
    assert new_raven is raven

    new_client = import_string('raven.Client')
    assert new_client is raven.Client

    # this will test unicode on python2
    new_client = import_string(six.text_type('raven.Client'))
    assert new_client is raven.Client


text:
package com.codemany.txtreader;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.MotionEvent;

public class Splash extends Activity {
    private boolean active = true;
    private int splashTime = 5000; // time to display the splash screen in ms

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.splash);

        Thread splashTread = new Thread() {
            @Override
            public void run() {
                try {
                    int waited = 0;
                    while (active && (waited < splashTime)) {
                        sleep(100);
                        if (active) {
                            waited += 100;
                        }
                    }
                } catch(InterruptedException e) {
                } finally {
                    finish();
                    startActivity(new Intent(Splash.this, MainActivity.class));
                }
            }
        };
        splashTread.start();
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            active = false;
        }
        return true;
    }
}