text:
package fpgatidbits.streams

import Chisel._

// combinational join for two streams -> one stream
// join function can be customized

class StreamJoin[TiA <: Data, TiB <: Data, TO <: Data]
(genA: TiA, genB: TiB, genOut: TO, join: (TiA, TiB) => TO) extends Module {
  val io = new Bundle {
    val inA = Decoupled(genA).flip
    val inB = Decoupled(genB).flip
    val out = Decoupled(genOut)
  }

  io.out.valid := io.inA.valid & io.inB.valid
  io.out.bits := join(io.inA.bits, io.inB.bits)

  io.inA.ready := io.out.ready & io.inB.valid
  io.inB.ready := io.out.ready & io.inA.valid
}

object StreamJoin {
  def apply[TiA <: Data, TiB <: Data, TO <: Data]
  (inA: DecoupledIO[TiA], inB: DecoupledIO[TiB], genO: TO,
  join: (TiA, TiB) => TO): DecoupledIO[TO] = {
    val joiner = Module(new StreamJoin(inA.bits, inB.bits, genO, join)).io
    joiner.inA <> inA
    joiner.inB <> inB
    joiner.out
  }
}


text:
set -euv

### -------------------- Provisioning by user.
cd

exit

redpajama_set_name: RedPajamaGithub


text:
from __future__ import print_function
import sys
from datetime import datetime, timedelta
from time import time, sleep
from redis import Redis
import requests
redis = Redis()

URLS = (
        "www.spokesman.com",
        "www.google.com",
        "www.yahoo.com",
        "www.example.com",
        "www.gibberish.com",
        "www.a.com",
        "www.b.com",
        "www.c.com",
        "www.d.com",
        "www.forza.com",
        "www.bbc.co.uk",
        "www.canada.ca",
        "www.twitter.com",
        "www.amazon.com"
        )

def sharecount(url):
    """Get social share count for given url."""
    queue_url(url)
    process_urls()
    print(url, get_share_count(url))

def queue_url(url):
    """Add url to request queue and/or increase score."""
    return url, redis.zincrby("url_queue",1,url)

def push_to_requested_queue(url):
    """Flush request queue and """

    time_period = timedelta(seconds=30).seconds
    requests_per_period = 15  # Twitter API

    print("Processing: {}".format(url))
    timenow = time()
    requested_queue = redis.hgetall('requested_queue')

    for rurl, timestamp in requested_queue.items():
        time_diff = timenow - float(timestamp)
        if time_diff > time_period:
            # Flush old requests
            redis.hdel('requested_queue',rurl)
            requested_queue.pop(rurl, None)

    count = redis.hlen('requested_queue')

    if not url in requested_queue and count < requests_per_period:
        redis.hset('requested_queue',url,timenow)
        twitter(url)
        return True

def twitter(url):
    raise DeprecationWarning('This url has been removed by Twitter, '
                             'with no replacement available')
    r = requests.get('http://urls.api.twitter.com/1/urls/count.json?url={}&callback=?'.format(url))
    if r.status_code == 200:
        count = r.json().get('count',0)
        redis.hset(url,"twitter_count",count)
        return count

def process_urls():
    """Process url with highest score."""

    processing = redis.zrevrange("url_queue",0,0)
    if push_to_requested_queue(processing[0]):
        return redis.zrem("url_queue", processing[0])

def get_share_count(url):
    return redis.hgetall(url)

if __name__ == '__main__':

    for url in URLS:
        sharecount(url)
        sleep(10)


text:
from django.http import HttpResponse
from zabbixwechat.common import *
from django.shortcuts import render
from zabbix_wechat_db.models import ALARM_INFO
import time

def tempcloselist(request):
    now = int(time.time())
    code = request.GET['code']
    state = request.GET['state']
    comfirmuser = getusername(code)
    context = {}
    list = TEMP_CLOSED.objects.filter(
        # ENDTIME__gt=now,REMOVED=1).order_by("-id")
        REMOVED='', ENDTIME__gt=now).order_by("-id")
    for i in list:
        i.BEGINTIME = time.strftime(
            "%Y-%m-%d %H:%M:%S", time.localtime(int(i.BEGINTIME)))
        i.ENDTIME = time.strftime(
            "%Y-%m-%d %H:%M:%S", time.localtime(int(i.ENDTIME)))
    context['body'] = list
    context['username'] = comfirmuser
    return render(request, 'tempcloselist.html', context)


text:
package org.apache.ignite.internal.processors.query.h2;

import java.util.UUID;
import org.apache.ignite.internal.util.future.GridFutureAdapter;

/**
 * Kill Query run context.
 */
class KillQueryRun {
    /** Node id. */
    private final UUID nodeId;

    /** Node query id. */
    private final long nodeQryId;

    /** Cancellation query future. */
    private final GridFutureAdapter<String> cancelFut;

    /**
     * Constructor.
     *
     * @param nodeId Node id.
     * @param cancelFut Cancellation query future.
     */
    public KillQueryRun(UUID nodeId, long nodeQryId, GridFutureAdapter<String> cancelFut) {
        assert nodeId != null;

        this.nodeId = nodeId;
        this.nodeQryId = nodeQryId;
        this.cancelFut = cancelFut;
    }

    /**
     * @return Node id.
     */
    public UUID nodeId() {
        return nodeId;
    }

    /**
     * @return Node query id.
     */
    public long nodeQryId() {
        return nodeQryId;
    }

    /**
     * @return Cancellation query future.
     */
    public GridFutureAdapter<String> cancelFuture() {
        return cancelFut;
    }
}


text:
package com.oprisnik.semdroid.filter;

import com.oprisnik.semdroid.app.DexClass;

/**
 * Checks if the class name contains a given string.
 */
public class ContainsStringClassFilter extends ClassSizeClassFilter {

    private String mString;

    public ContainsStringClassFilter(String string) {
        mString = string.toLowerCase();
    }

    @Override
    public boolean use(DexClass data) {
        if (super.use(data)) {
            return data.getClassName().toLowerCase().contains(mString);
        }
        return false;
    }
}


text:
package com.example.etienne.chillapp.fragments;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import com.example.etienne.chillapp.R;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link Appointments.OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link Appointments#newInstance} factory method to
 * create an instance of this fragment.
 */
public class Appointments extends Fragment {

    ListView lv;

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private OnFragmentInteractionListener mListener;

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment Appointments.
     */
    // TODO: Rename and change types and number of parameters
    public static Appointments newInstance(String message) {
        Appointments fragment = new Appointments();
        Bundle bundle = new Bundle(1);
        bundle.putString("title", message);
        fragment.setArguments(bundle);
        return fragment;
    }

    public Appointments() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        lv = (ListView)getActivity().findViewById(R.id.lv_appointments);
        /*lv.setOnItemClickListener(new AdapterView.OnItemClickListener(){
            @Override
            public void onItemClick(AdapterView<?> arg0, View view, int position, long arg3) {

                Intent i = new Intent(view.getContext(), AppointmentDetail.class);
                startActivity(i);
            }
        });*/
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        String message = getArguments().getString(ARG_PARAM1);
        View v = inflater.inflate(R.layout.fragment_appointments, container, false);
        //TextView messageTextView = (TextView)v.findViewById(R.id.textView);
        //messageTextView.setText(message);

        return v;
    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            mListener = (OnFragmentInteractionListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     *

     * See the Android Training lesson Communicating with Other Fragments for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        public void onFragmentInteraction(Uri uri);
    }

}


text:
using Bridge.Test.NUnit;
using System;
using System.Text.RegularExpressions;

namespace Bridge.ClientTest.Text.RegularExpressions.Entities
{
    [Category(Constants.MODULE_REGEX)]
    [TestFixture(TestNameFormat = "RegexGroupCollection Entity - {0}")]
    public class RegexGroupCollectionTests : RegexTestBase
    {
        #region Test data

        private const string Pattern = @"((?:\w)+[\s\.])+";
        private const string Text = @"This is a sentance. This is another sentance.";

        private static Match GetTestDataMatch(int matchIndex = 1)
        {
            var rgx = new Regex(Pattern);
            var m = rgx.Match(Text);
            for (int i = 1; i < matchIndex; i++)
            {
                m = rgx.Match(Text, m.Index + m.Length);
            }

            return m;
        }

        [Test]
        public void CaseDataTest()
        {
            var m1 = GetTestDataMatch();

            ValidateMatch(m1, 0, 19, "This is a sentance.", 2, true);

            ValidateGroup(m1, 0, 0, 19, true, "This is a sentance.", 1);
            ValidateCapture(m1, 0, 0, 0, 19, "This is a sentance.");

            ValidateGroup(m1, 1, 10, 9, true, "sentance.", 4);
            ValidateCapture(m1, 1, 0, 0, 5, "This ");
            ValidateCapture(m1, 1, 1, 5, 3, "is ");
            ValidateCapture(m1, 1, 2, 8, 2, "a ");
            ValidateCapture(m1, 1, 3, 10, 9, "sentance.");

            var m2 = GetTestDataMatch(2);

            ValidateMatch(m2, 20, 25, "This is another sentance.", 2, true);

            ValidateGroup(m2, 0, 20, 25, true, "This is another sentance.", 1);
            ValidateCapture(m2, 0, 0, 20, 25, "This is another sentance.");

            ValidateGroup(m2, 1, 36, 9, true, "sentance.", 4);
            ValidateCapture(m2, 1, 0, 20, 5, "This ");
            ValidateCapture(m2, 1, 1, 25, 3, "is ");
            ValidateCapture(m2, 1, 2, 28, 8, "another ");
            ValidateCapture(m2, 1, 3, 36, 9, "sentance.");
        }

        #endregion Test data

        [Test]
        public void GroupCollectionFieldsTest()
        {
            var m = GetTestDataMatch();
            var groups = m.Groups;

            Assert.AreEqual(2, groups.Count, "Groups.Count");
            Assert.AreEqual(true, groups.IsReadOnly, "Groups.IsReadOnly");
            Assert.AreEqual(false, groups.IsSynchronized, "Groups.IsSynchronized");
            Assert.AreEqual(m, groups.SyncRoot, "Groups.SyncRoot");
        }

        [Test]
        public void GroupCollectionForeachTest()
        {
            var m = GetTestDataMatch();
            var groups = m.Groups;

            var i = 0;
            foreach (var groupObj in groups)
            {
                var group = groupObj as Group;
                GroupsAreEqual(groups[i], group, "Groups[" + i + "]");
                ++i;
            }
        }

        [Test]
        public void GroupCollectionEnumeratorTest()
        {
            var m = GetTestDataMatch();
            var groups = m.Groups;

            var en = groups.GetEnumerator();

            Assert.True(en.MoveNext(), "First call - MoveNext()");

            int i = 0;
            do
            {
                var group = en.Current as Group;
                GroupsAreEqual(groups[i], group, "Groups[" + i + "]");
                ++i;
            } while (en.MoveNext());

            Assert.AreEqual(groups.Count, i, "Groups.Count");
        }

        [Test]
        public void GroupCollectionCopyToTest()
        {
            var m = GetTestDataMatch();
            var groups = m.Groups;

            var dstArray = new Group[groups.Count];
            groups.CopyTo(dstArray, 0);

            for (int i = 0; i < groups.Count; i++)
            {
                GroupsAreEqual(groups[i], dstArray[i], "Groups[" + i + "]");
            }

            Assert.Throws(() => { groups.CopyTo(null, 0); },
                err => err.GetType().FullName == typeof(ArgumentNullException).FullName,
                "Exception: Array is not null.");
            Assert.Throws(() => { groups.CopyTo(dstArray, 1); },
                err => err.GetType().FullName == typeof(IndexOutOfRangeException).FullName,
                "Exception: Out of range.");
        }
    }
}


text:
Sintaxis para llamar a un método: `$('#table').bootstrapTable('method', parameter);`.

        Nombre
        Parámetro
        Descripción

        getOptions
        none
        Retorna el objeto options.

        getSelections
        none
        Retorna todas las filas seleccionadas, cuando no hay seleccionadas, se retorna un array vacío .

        getData
        useCurrentPage
        Retorna los datos cargados en la tabla. Si se setea useCurrentPage a true se devolverá los datos mostrados en la página
        actual

        load
        data
        Se cargan los datos en la tabla, las filas antiguas se removeran.

        append
        data
        Se anexan los datos a la tabla.

        prepend
        data
        Se antepone los datos a la tabla.

        remove
        params

        Se remueven los datos de la tabla, los parámetros contienen dos propiedades:

        field: el nombre del campo de las filas removidas.

        values: el array de valores de las filas que deberían ser removidas.

        Ejemplo: $('#myTable').bootstrapTable('remove', {field: 'id', values: ["73", "74"]})

        insertRow
        params

        Inserta una nueva fila, los paeámetros contienen las siguientes propiedades:

        index: el índice donde se insertara la nueva fila.

        row: los datos de la fila.

        updateRow
        params

        Actualiza la fila especificada, el parámetro contiene las siguientes propiedades:

        index: el índice de la fila para ser actualizada.

        row: los nuevos data de la fila.

        showRow
        params
        Muesta la fila especificada. El parámetro contiene los siguiente propiedades:

        index: el indice o idField de la fila.
        isIdField: Boolean que indica si el index es idField o la posición de la fila.

        hideRow
        params
        Oculta la fila especificada. El parámetro contiene los siguiente propiedades:

        index: el indice o idField de la fila.
        isIdField: Boolean que indica si el index es idField o la posición de la fila.

        getRowsHidden
        boolean
        Obitnene todas las filas ocultas si se pasa el parámetro show en true las filas serán mostradas, sino, el método solo
        devolvera las filas ocultas.

        mergeCells
        options

        Se unen algunas celdas en una, las opciones contienen las siguientes propiedades:

        index: el índice de la fila.

        field: el nombre del campo.

        rowspan: el rowspan para ser unidas.

        colspan: el colspan para ser unidas.

        refresh
        params
        Refresca los datos remotos del servidor, se puede setear {silent: true} para refrescar los datos silenciosamente, y setear {url: newUrl} para cambiar el URL. Para suministrar query params especificos para este request, setear {query: {foo: 'bar'}}

        showLoading
        none
        Mostrar el estado de la carga.

        hideLoading
        none
        Ocultar el estado de la carga.

        checkAll
        none
        Chequear todas las filas de la página actual de la tabla.

        uncheckAll
        none
        Des-chequear todas las filas de la página actual de la tabla.

        check
        index
        Chequea una fila, el índice de la fila inicia en 0.

        uncheck
        index
        Des-chequea una fila, el índice de la fila inicia en 0.

        checkBy
        params

        Chequea una fila por un array de valores los parámetros continen:

        field: nombre del campo a usar para encontrar los registros

        values: array de valores de las filas por chequear

        Ejemplo:

        $("#table").bootstrapTable("checkBy", {field:"field_name", values:["value1","value2","value3"]})

        uncheckBy
        params

        Deschequea una fila por un array de valores los parámetros continen:

        field: nombre del campo a usar para encontrar los registros

        values: array de valores de las filas por deschequear

        Ejemplo:

        $("#table").bootstrapTable("uncheckBy", {field:"field_name", values:["value1","value2","value3"]})

        resetView
        params
        Reinicia la vista de bootstrap table, por ejemplo reinicia el alto de la tabla.

        destroy
        none
        Destruye la bootstrap table.

        showColumn
        field
        Muestra la columna especificada.

        hideColumn
        field
        Oculta la columna especificada.

        scrollTo
        value
        Setea la posición del scroll, setear 'bottom' significa setear la posición del scroll al final de la tabla.

        getScrollPosition
        none
        Obtiene la posición actual del scroll.

        filterBy
        params
        (Solo se puede usar en client-side)Filtra los datos en la tabla, ejm. se puede filtrar {age: 10} para mostrar los daros solo con la edad igual a 10.

        selectPage
        page
        Ir a una página en especifico.

        prevPage
        none
        Ir a la página anterior.

        nextPage
        none
        Ir a la siguiente página.

        togglePagination
        none
        Habilita y deshabilita la paginación.

        toggleView
        none
        Alterna la vista entre tabla y tarjeta.

        deleteCookie
        cookie name
        Elimina una cookie creada. Debe usar: 'sortOrder', 'sortName', 'pageNumber' o 'pageList'.


text:
version = "$Revision: 910524 $"
progname = "hotshot2cachegrind"

import os, sys
from hotshot import stats,log
import os.path

file_limit=0

what2text = {
    log.WHAT_ADD_INFO    : "ADD_INFO",
    log.WHAT_DEFINE_FUNC : "DEFINE_FUNC",
    log.WHAT_DEFINE_FILE : "DEFINE_FILE",
    log.WHAT_LINENO      : "LINENO",
    log.WHAT_EXIT        : "EXIT",
    log.WHAT_ENTER       : "ENTER"}

# a pseudo caller on the caller stack. This represents
# the Python interpreter that executes the given python
# code.
root_caller = ("PythonInterpreter",0,"execute")

class CallStack:
    """A tiny Stack implementation, based on python lists"""
    def __init__(self):
       self.stack = []
       self.recursion_counter = {}
    def push(self, elem):
        """put something on the stack"""
        self.stack.append(elem)
        rc = self.recursion_counter.get(elem, 0)
        self.recursion_counter[elem] = rc + 1

    def pop(self):
        """get the head element of the stack and remove it from the stack"""
        elem = self.stack[-1:][0]
        rc = self.recursion_counter.get(elem) - 1
        if rc>0:
            self.recursion_counter[elem] = rc
        else:
            del self.recursion_counter[elem]
        return self.stack.pop()

    def top(self):
        """get the head element of the stack, stack is unchanged."""
        return self.stack[-1:][0]
    def handleLineCost(self, tdelta):
        p, c = self.stack.pop()
        self.stack.append( (p,c + tdelta) )
    def size(self):
        """ return how many elements the stack has"""
        return len(self.stack)

    def __str__(self):
        return "[stack: %s]" % self.stack

    def recursion(self, pos):
        return self.recursion_counter.get(pos, 0)
        #return self.recursion_dict.has_key((entry[0][0], entry[0][2]))

def return_from_call(caller_stack, call_dict, cost_now):
    """return from a function call
       remove the function from the caller stack,
       add the costs to the calling function.
    """
    called, cost_at_enter = caller_stack.pop()
    caller, caller_cost = caller_stack.top()

    #print "return_from_call: %s ruft %s" % (caller, called,)

    per_file_dict = call_dict.get(called[0], {})
    per_caller_dict = per_file_dict.get(called[2], {})
    cost_so_far, call_counter = per_caller_dict.get(caller, (0, 0))

    if caller_stack.recursion(called):
        per_caller_dict[caller] = (cost_so_far, call_counter + 1)
    else:
        per_caller_dict[caller] = (cost_so_far + cost_now - cost_at_enter, call_counter + 1)

    per_file_dict[called[2]] = per_caller_dict
    call_dict[called[0]] = per_file_dict

def updateStatus(filecount):
    sys.stdout.write("reading File #%d    \r" % filecount)
    sys.stdout.flush()
def convertProfFiles(output, inputfilenames):
    """convert all the given input files into one kcachegrind
       input file.
    """
    call_dict = {}
    cost_per_pos = {}
    cost_per_function = {}
    caller_stack = CallStack()
    caller_stack.push((root_caller, 0))

    total_cost = 0
    filecount = 1
    number_of_files = len(inputfilenames)
    for inputfilename in inputfilenames:
        updateStatus(filecount)
        cost, filecount = convertHandleFilename(inputfilename, caller_stack, call_dict, cost_per_pos, cost_per_function, filecount)
        total_cost += cost
        if (file_limit > 0) and (filecount > file_limit):
            break

    print
    print "total_cost: % d Ticks",total_cost
    dumpResults(output, call_dict, total_cost, cost_per_pos, cost_per_function)

def convertHandleFilename(inputfilename, caller_stack, call_dict, cost_per_pos, cost_per_function, filecount):
    updateStatus(filecount)
    if not ((file_limit > 0) and (filecount > file_limit)):
        if os.path.isdir(inputfilename):
            cost, filecount = convertProfDir(inputfilename, caller_stack, call_dict, cost_per_pos, cost_per_function, filecount)
        elif os.path.isfile(inputfilename):
            cost = convertProfFile(inputfilename, caller_stack, call_dict, cost_per_pos, cost_per_function)
            filecount += 1
        else:
            sys.stderr.write("warn: ignoring '%s', is no file and no directory\n" % inputfilename)
            cost = 0
    return (cost, filecount)

def convertProfDir(start, caller_stack, call_dict, cost_per_pos, cost_per_function, filecount):
    cost = 0
    filenames = os.listdir(start)
    for f in filenames:
        if (file_limit > 0) and (filecount > file_limit):
            break
        full = os.path.join(start, f)
        c, filecount = convertHandleFilename(full, caller_stack, call_dict, cost_per_pos, cost_per_function, filecount)
        cost += c;
    return (cost, filecount)

def handleCostPerPos(cost_per_pos, pos, current_cost):
    """
       the cost per source position are managed in a dict in a dict.

       the cost are handled per file and there per function.
       so, the per-file-dict contains some per-function-dicts
       which sum up the cost per line (in this function and in
       this file).
    """
    filename  = pos[0]
    lineno    = pos[1]
    funcname  = pos[2]
    file_dict = cost_per_pos.get(filename, {})
    func_dict = file_dict.get(funcname, {})
    func_dict.setdefault(lineno, 0)
    func_dict[lineno] += current_cost
    file_dict[funcname] = func_dict
    cost_per_pos[filename] = file_dict

def convertProfFile(inputfilename, caller_stack, call_dict, cost_per_pos, cost_per_function):
    """convert a single input file into one kcachegrind
       data.

       this is the most expensive function in this python source :-)
    """

    total_cost = 0
    try:
        logreader = log.LogReader(inputfilename)
        current_cost = 0
        hc = handleCostPerPos # shortcut
        for item in logreader:
            what, pos ,tdelta = item
            (file, lineno, func) = pos
            #line = "%s %s %d %s %d" % (what2text[what], file, lineno, func, tdelta)
            #print line
            # most common cases first
            if what == log.WHAT_LINENO:
                # add the current cost to the current function
                hc(cost_per_pos, pos, tdelta)
                total_cost += tdelta
            elif what == log.WHAT_ENTER:
                caller_stack.push((pos, total_cost))
                hc(cost_per_pos, pos, tdelta)
                total_cost += tdelta
            elif what == log.WHAT_EXIT:
                hc(cost_per_pos, pos, tdelta)
                total_cost += tdelta
                return_from_call(caller_stack, call_dict, total_cost)
            else:
                assert 0, "duh: %d" % what

        # I have no idea, why sometimes the stack is not empty - we
        # have to rewind the stack to get 100% for the root_caller
        while caller_stack.size() > 1:
            return_from_call(caller_stack, call_dict, total_cost)

    except IOError:
        print "could not open inputfile '%s', ignore this." % inputfilename
    except EOFError, m:
        print "EOF: %s" % (m,)
    return total_cost

def pretty_name(file, function):
    #pfile = os.path.splitext(os.path.basename(file)) [0]
    #return "%s_[%s]" % (function, file)
    return "%s" % function
    #return "%s::%s" % (file, function)
    #return "%s_%s" % (pfile, function)

class TagWriter:
    def __init__(self, output):
        self.output = output
        self.last_values = {}

    def clearTag(self, tag):
        if self.last_values.has_key(tag):
            del self.last_values[ tag ]
    def clear(self):
        self.last_values = {}

    def write(self, tag, value):
        self.output.write("%s=%s\n" % (tag, value))
        #if (not self.last_values.has_key(tag)) or self.last_values[tag] != value:
        #    self.last_values[ tag ] = value
        #    self.output.write("%s=%s\n" % (tag, value))

def dumpResults(output, call_dict, total_cost, cost_per_pos, cost_per_function):
    """write the collected results in the format kcachegrind
       could read.
    """
    # the intro
    output.write("events: Tick\n")
    output.write("summary: %d\n" % total_cost)
    output.write("cmd: your python script\n")
    output.write("\n")
    tagwriter = TagWriter(output)

    # now the costs per line
    for file in cost_per_pos.keys():
        func_dict = cost_per_pos[file]
        for func in func_dict.keys():
            line_dict = func_dict[func]
            tagwriter.write("ob", file)
            tagwriter.write("fn", func)# pretty_name(file, func)) ; output.write("# ^--- 2\n")
            tagwriter.write("fl", file)
            for line in line_dict:
                output.write("%d %d\n" %( line, line_dict[line] ))

    output.write("\n\n")
    # now the function calls. For each caller all the called
    # functions and their costs are written.
    for file in call_dict.keys():
        per_file_dict = call_dict[file]
        #print "file %s -> %s" % (file, per_file_dict)
        for called_x in per_file_dict.keys():
            #print "called_x:",called_x
            per_caller_dict = per_file_dict[called_x]
            #print "called_x %s wird gerufen von: %s" % (called_x, per_caller_dict)
            for caller_x in per_caller_dict.keys():
                tagwriter.write("ob", caller_x[0])
                tagwriter.write("fn", caller_x[2])# pretty_name(caller_x[2], caller_x[0])) ; output.write("# ^--- 1\n")
                tagwriter.write("fl", caller_x[0])
                tagwriter.write("cob", file)
                tagwriter.write("cfn", called_x) #pretty_name(file, called_x))
                tagwriter.write("cfl", file)
                cost, count = per_caller_dict[caller_x]
                #print "called_x:",called_x
                output.write("calls=%d\n%d %d\n" % (count, caller_x[1], cost))
                tagwriter.clear()
                #tagwriter.clearTag("cob")
                # is it a bug in kcachegrind, that the "cob=xxx" line has
                # to be rewritten after a calls entry with costline ?
                #assert cost <= total_cost, "caller_x: %s, per_caller_dict: %s " % (caller_x, per_caller_dict, )
                #output.write("calls=%d\n%d %d\n" % (count, caller_x[1], cost))
                output.write("\n")

def run_without_optparse():
    """parse the options without optparse, use sys.argv"""
    if  len(sys.argv) < 4 or sys.argv[1] != "-o" :
        print "usage: hotshot2cachegrind -o outputfile in1 [in2 [in3 [...]]]"
        return
    outputfilename = sys.argv[2]
    try:
        output = file(outputfilename, "w")
        args = sys.argv[3:]
        convertProfFiles(output, args)
        output.close()
    except IOError:
        print "could not open '%s' for writing." % outputfilename

def run_with_optparse():
    """parse the options with optparse"""

    global file_limit

    versiontext = "%s version: %s" % ( progname, version.split()[1], )
    parser = OptionParser(version=versiontext)
    parser.add_option("-o", "--output",
      action="store", type="string", dest="outputfilename",
      help="write output into FILE")
    parser.add_option("--file-limit",
      action="store", dest="file_limit", default=0,
      help="stop after given number of input files")
    output = sys.stdout
    close_output = 0
    (options, args) = parser.parse_args()
    file_limit = int(options.file_limit)
    try:
        if options.outputfilename and options.outputfilename != "-":
            output = file(options.outputfilename, "w")
            close_output = 1
    except IOError:
        print "could not open '%s' for writing." % options.outputfilename
    if output:
        convertProfFiles(output, args)
        if close_output:
            output.close()

def profile_myself():
    import hotshot
    filename = "self.prof"
    if not os.path.exists(filename):
        prof = hotshot.Profile(filename, lineevents=1)
        prof.runcall(run)
        prof.close()
    else:
        print "not profiling myself, since '%s' exists, running normal" % filename
        run()

# check if optparse is available.
try:
    from optparse import OptionParser
    run = run_with_optparse
except ImportError:
    run = run_without_optparse

if __name__ == "__main__":
    try:
        run()
        #profile_myself()
    except KeyboardInterrupt:
        sys.exit(1)


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
Sedum granatense Pau

### Remarks
null


text:
process.stdout.write("gunmetal v1.1.3\r");
process.env.GULP_PROJECTS_DIR = process.cwd();
process.chdir(require('gunmetal').dirname);
require('gulp-cli')();


text:
{% extends "base.html" %}
{% load i18n %}
{% load random_int %}

{% block shareimage %}http://schoolido.lu/static/screenshots/contest.png{% endblock %}
{% block shareimagetwitter %}http://schoolido.lu/static/screenshots/contest.png{% endblock %}

{% block title %}{% trans 'The ultimate battle between School Idols' %}{% endblock %}

{% block content %}

      School Idol Contest is temporarily disabled due to high traffic. Please try again tomorrow.

      Any help to get more powerful servers is greatly appreciated. Donate here!

{% endblock %}


text:
package com.devicehive.resource.converters;

import com.devicehive.configuration.Messages;
import com.devicehive.exceptions.HiveException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import static javax.ws.rs.core.Response.Status.BAD_REQUEST;

public class SortOrderQueryParamParser {

    private static final Logger logger = LoggerFactory.getLogger(SortOrderQueryParamParser.class);

    private final static String SORT_ORDER_ASC = "ASC";
    private final static String SORT_ORDER_DESC = "DESC";

    public static boolean parse(String value) {
        if (value == null || value.equalsIgnoreCase(SORT_ORDER_ASC)) {
            return true;
        } else if (value.equalsIgnoreCase(SORT_ORDER_DESC)) {
            return false;
        } else {
            throw new HiveException(String.format(Messages.UNPARSEABLE_SORT_ORDER, value),
                                    BAD_REQUEST.getStatusCode());
        }
    }

}


text:
@interface PodsDummy_Pods_PokedexGo : NSObject
@end
@implementation PodsDummy_Pods_PokedexGo
@end


text:
##
##  See COPYING file distributed along with the ncanda-data-integration package
##  for the copyright and license terms
##

import pandas
import string
import time
import datetime
import numpy

input_fields = { 'parentreport' : [ 'parentreport_sesp3', # highest grade you has completed
                                    'parentreport_sesp3b',# highest grade you has completed
                                    'parentreport_sesp14',# TOTAL COMBINED FAMILY INCOME categories
                                    'parent_report_complete', 'parentreport_missing' ] }

output_form = 'clinical'
outfield_list = [ 'ses_parent_score', 'ses_parent_faminc', 'ses_parent_yoe', 'ses_complete' ]

#
# Safe conversion of string to float
#
def safe_float( strng ):
    if strng == '' or str( strng ) == 'nan':
        return 0
    try:
        return float( strng )
    except:
        return 0

#
# Computation function
#
def compute( record ):
    # check parent report
    if (record['parent_report_complete'] > 0) and ( record['parentreport_missing'] != 1 ):
	edu_valid = False
	income_valid = False

        # Get max education and check if valid (many are missing)
        edu = max( [ safe_float( record['parentreport_sesp3'] ), safe_float( record['parentreport_sesp3b'] ) ] )
	if edu > 0:
            record['ses_parent_yoe'] = int( edu )
            edu_valid = True

        # Get family income and make sure it's not "don't know"
        income = safe_float( record['parentreport_sesp14'] )
	if (income > 0) and (income < 11): ## '11' is "Don't know!"
            record['ses_parent_faminc'] = int( income )
            income_valid = True

        # Score valid only if both education and income are known
        if edu_valid and income_valid:
	    record['ses_parent_score'] = int( edu*3+income*5 )

        # Only set "Complete" status if not "missing"
        record['ses_complete'] =  str( record['parent_report_complete'] )

    return record[ outfield_list ]

#
# Driver function - go through the steps of status determination
#
def compute_scores( data, demographics ):
    for f in outfield_list:
        data[f] = ''

    # Do computations, return result
    results = data.apply( compute, axis=1 )
    results.index = pandas.MultiIndex.from_tuples( results.index )
    return results


text:
from beritest_tools import BaseBERITestCase
from nose.plugins.attrib import attr

class test_raw_hilo(BaseBERITestCase):
    @attr('beriinitial')
    def test_init_hi(self):
        self.assertRegisterEqual(self.MIPS.a0, 0, "HI non-zero on reset")

    @attr('beriinitial')
    def test_init_lo(self):
        self.assertRegisterEqual(self.MIPS.a1, 0, "LO non-zero on reset")


text:
Joshfire.define(['joshfire/uielements/panel', 'joshfire/class', 'joshfire/vendor/underscore'], function(Panel, Class, _) {
  /**
  * Panel Manager shows one of its children panel at a time

  * The manager listens to a uiMaster, and change its active view depending of the select events fired by this master
  * @class Panel Manager base class
  * @name uielements_panel.manager
  * @augments uielements_panel
  */
  return Class(Panel,
      /**
      * @lends uielements_panel.manager.prototype
      */
      {
        /**
        * Initialize the panel manager

        * If uiMaster, subscribe to masters' select event
        * @function
        *
        **/
        init: function() {
          var self = this;

          self.__super();

          self.lastSequenceId = 0;

          self.subscribe('state', function(ev, data) {
            if (data[0] == 'route') {
              self.route(data[1]);
            }
          });

          self.currentId = false;

        },

        switchTo: function(finalPath) {
          var self = this;

          self.currentPanelId = finalPath;

          //Show panel.mgr item referenced by uimaster
          //Hide everybody else
          _.each(self.children, function(child) {
            if (child.path == self.path + '/' + finalPath) {
              self.app.ui.element(child.path).show();
            } else {
              self.app.ui.element(child.path).hide();
            }
          });
        },

        setup: function(callback) {
          var self = this;

          if (self.options.uiMaster) {
            self.app.ui.fetch(self.options.uiMaster, false, function(error, item) {
              var uiMaster = self.app.ui.element(self.options.uiMaster);

              uiMaster.subscribe('select', function(ev, data) {
                //Check target exists
                if (!data.length || self.app.ui.get(self.path + '/' + data[0][0]) === undefined) {
                  return false;
                }

                self.switchTo(data[0][0]);

                return true;
              });
            });
          }

          callback();
        },

        /**
        * Init view
        * @function
        * @param {string} view
        * @param {Function} callback, called after init.
        **/
        initView: function(view, callback) {
          var self = this;

          if (_.isString(view)) {
            //todo cache view classes
            Joshfire.require([this.options.requirePrefix + view], function(viewClass) {
              if (!viewClass) {
                return callback('no such view');
              }
              var elt = new viewClass(self.app, self.path + '/' + view, {
                sequenceId: self.lastSequenceId++
              });
              return callback(null, elt);
            });
          }
        }
      });
});


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

<title>Uses of Class thobe.widgets.multiFramePanel.AbstractMultiFrameLayout</title>
<meta name="date" content="2015-04-06">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Class
thobe.widgets.multiFramePanel.AbstractMultiFrameLayout

Packages that use AbstractMultiFrameLayout

Package
Description

thobe.widgets.multiFramePanel.layouts

Uses of AbstractMultiFrameLayout in thobe.widgets.multiFramePanel.layouts

Subclasses of AbstractMultiFrameLayout in thobe.widgets.multiFramePanel.layouts

Modifier and Type
Class and Description

class
Layout_1Single

class
Layout_2SideBySide

class
Layout_2Stacked

class
Layout_3SideBySide

class
Layout_3StackedLeft

class
Layout_3StackedRight

class
Layout_4SideBySide

class
Layout_4Stacked

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes


text:
layout: page
title: Price Tech Executive Retreat
date: 2016-05-24
author: Larry Burke
tags: weekly links, java
status: published
summary: Duis rutrum erat elit, ac.
banner: images/banner/leisure-03.jpg
booking:
  startDate: 07/15/2017
  endDate: 07/16/2017
  ctyhocn: BGMNYHX
  groupCode: PTER
published: true
---
Duis vitae sem diam. Nam diam enim, sodales sit amet nulla in, venenatis tincidunt lectus. Donec et suscipit nibh. Sed malesuada rhoncus vehicula. Aenean consequat nisl et pretium placerat. Sed orci neque, congue malesuada lorem ut, gravida dapibus ipsum. Suspendisse nec tincidunt lectus. Duis euismod dolor lorem, a tempus purus dignissim aliquam. In eu mattis augue. Sed ac scelerisque lorem. Proin blandit tortor ut augue ultrices, ut varius erat facilisis. Nam interdum vitae sapien eget sagittis. Pellentesque aliquam posuere turpis, sed vestibulum ligula aliquet id. Suspendisse feugiat elit eget ante semper, a cursus magna consequat. Fusce sollicitudin, arcu a consectetur malesuada, lectus ipsum eleifend lorem, ornare sollicitudin purus nunc ut quam. Phasellus non lorem orci.
In sodales tempor quam sit amet fringilla. Proin ut porttitor metus, non feugiat nisl. Integer venenatis nunc et eros vulputate, ac efficitur enim facilisis. Nunc pretium varius sollicitudin. Pellentesque id tellus vel est eleifend volutpat vel non felis. Donec ac maximus lorem, et consequat sapien. Vestibulum ut tortor facilisis risus congue consectetur. Nullam ultrices ornare mauris, non sollicitudin urna porta ut. Aenean aliquet iaculis ipsum eu dictum. Morbi lacinia laoreet malesuada. Pellentesque ac lacus facilisis, condimentum urna vel, aliquam nibh. In hac habitasse platea dictumst.

1 Nullam vulputate tellus commodo, suscipit mauris id, accumsan urna
1 Praesent vehicula tellus nec magna dictum, at ultricies massa mattis
1 Nam nec leo scelerisque lorem rhoncus iaculis ac ut mauris
1 Pellentesque non felis feugiat, mollis arcu eu, vulputate ipsum
1 In eget urna id turpis fermentum tempus at sed mauris
1 Etiam condimentum nibh quis sapien elementum venenatis.

Morbi maximus aliquet libero, vitae convallis nunc egestas vel. Maecenas pretium ultrices leo. Maecenas euismod sollicitudin posuere. Maecenas efficitur aliquam ornare. Curabitur malesuada consequat aliquet. Quisque sit amet facilisis ligula. Sed dapibus malesuada nunc, ut convallis ex hendrerit eget. Suspendisse accumsan mollis congue. Mauris iaculis ac justo quis pulvinar. Curabitur varius laoreet quam sagittis egestas. Nullam non fermentum ante, congue mollis erat. Etiam vehicula mauris in venenatis posuere.


text:
//
// Pythagoras - a collection of geometry classes
// http://github.com/samskivert/pythagoras

package pythagoras.f;

/**
 * Provides read-only access to a {@link RoundRectangle}.
 */
public interface IRoundRectangle extends IRectangularShape, Cloneable
{
    /** Returns the width of the corner arc. */
    float arcWidth ();

    /** Returns the height of the corner arc. */
    float arcHeight ();

    /** Returns a mutable copy of this round rectangle. */
    RoundRectangle clone ();
}


text:
long CVcFill::GetStyle()
{
	long result;
	InvokeHelper(0x1, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL);
	return result;
}

void CVcFill::SetStyle(long nNewValue)
{
	static BYTE parms[] =
		VTS_I4;
	InvokeHelper(0x1, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms,
		 nNewValue);
}

CVcBrush CVcFill::GetBrush()
{
	LPDISPATCH pDispatch;
	InvokeHelper(0x2, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&pDispatch, NULL);
	return CVcBrush(pDispatch);
}


text:
<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>Tag Without Class</title>
  <link rel="stylesheet" href="tag-without-class.css">

Tag Without Class

        icon should be blue

        icon should be blue

        span should be red


text:
import numbers
from abc import ABCMeta
from itertools import chain
from typing import Any, Optional, TypeVar, Union, TYPE_CHECKING

import numpy as np
import pandas as pd
from pandas.api.types import CategoricalDtype

from pyspark.sql import functions as F
from pyspark.sql.types import (
    ArrayType,
    BinaryType,
    BooleanType,
    DataType,
    DateType,
    DecimalType,
    FractionalType,
    IntegralType,
    MapType,
    NullType,
    NumericType,
    StringType,
    StructType,
    TimestampType,
    UserDefinedType,
)
from pyspark.pandas.typedef import Dtype, extension_dtypes
from pyspark.pandas.typedef.typehints import (
    extension_dtypes_available,
    extension_float_dtypes_available,
    extension_object_dtypes_available,
)

if extension_dtypes_available:
    from pandas import Int8Dtype, Int16Dtype, Int32Dtype, Int64Dtype

if extension_float_dtypes_available:
    from pandas import Float32Dtype, Float64Dtype

if extension_object_dtypes_available:
    from pandas import BooleanDtype, StringDtype

if TYPE_CHECKING:
    from pyspark.pandas.base import IndexOpsMixin  # noqa: F401 (SPARK-34943)
    from pyspark.pandas.indexes import Index  # noqa: F401 (SPARK-34943)
    from pyspark.pandas.series import Series  # noqa: F401 (SPARK-34943)

T_IndexOps = TypeVar("T_IndexOps", bound="IndexOpsMixin")

def is_valid_operand_for_numeric_arithmetic(operand: Any, *, allow_bool: bool = True) -> bool:
    """Check whether the `operand` is valid for arithmetic operations against numerics."""
    from pyspark.pandas.base import IndexOpsMixin

    if isinstance(operand, numbers.Number):
        return not isinstance(operand, bool) or allow_bool
    elif isinstance(operand, IndexOpsMixin):
        if isinstance(operand.dtype, CategoricalDtype):
            return False
        else:
            return isinstance(operand.spark.data_type, NumericType) or (
                allow_bool and isinstance(operand.spark.data_type, BooleanType)
            )
    else:
        return False

def transform_boolean_operand_to_numeric(
    operand: Any, spark_type: Optional[DataType] = None
) -> Any:
    """Transform boolean operand to numeric.

    If the `operand` is:
        - a boolean IndexOpsMixin, transform the `operand` to the `spark_type`.
        - a boolean literal, transform to the int value.
    Otherwise, return the operand as it is.
    """
    from pyspark.pandas.base import IndexOpsMixin

    if isinstance(operand, IndexOpsMixin) and isinstance(operand.spark.data_type, BooleanType):
        assert spark_type, "spark_type must be provided if the operand is a boolean IndexOpsMixin"
        return operand.spark.transform(lambda scol: scol.cast(spark_type))
    elif isinstance(operand, bool):
        return int(operand)
    else:
        return operand

def _as_categorical_type(
    index_ops: T_IndexOps, dtype: CategoricalDtype, spark_type: DataType
) -> T_IndexOps:
    """Cast `index_ops` to categorical dtype, given `dtype` and `spark_type`."""
    assert isinstance(dtype, CategoricalDtype)
    if dtype.categories is None:
        codes, uniques = index_ops.factorize()
        return codes._with_new_scol(
            codes.spark.column,
            field=codes._internal.data_fields[0].copy(dtype=CategoricalDtype(categories=uniques)),
        )
    else:
        categories = dtype.categories
        if len(categories) == 0:
            scol = F.lit(-1)
        else:
            kvs = chain(
                *[(F.lit(category), F.lit(code)) for code, category in enumerate(categories)]
            )
            map_scol = F.create_map(*kvs)

            scol = F.coalesce(map_scol.getItem(index_ops.spark.column), F.lit(-1))
        return index_ops._with_new_scol(
            scol.cast(spark_type).alias(index_ops._internal.data_fields[0].name),
            field=index_ops._internal.data_fields[0].copy(
                dtype=dtype, spark_type=spark_type, nullable=False
            ),
        )

def _as_bool_type(index_ops: T_IndexOps, dtype: Union[str, type, Dtype]) -> T_IndexOps:
    """Cast `index_ops` to BooleanType Spark type, given `dtype`."""
    from pyspark.pandas.internal import InternalField

    if isinstance(dtype, extension_dtypes):
        scol = index_ops.spark.column.cast(BooleanType())
    else:
        scol = F.when(index_ops.spark.column.isNull(), F.lit(False)).otherwise(
            index_ops.spark.column.cast(BooleanType())
        )
    return index_ops._with_new_scol(
        scol.alias(index_ops._internal.data_spark_column_names[0]),
        field=InternalField(dtype=dtype),
    )

def _as_string_type(
    index_ops: T_IndexOps, dtype: Union[str, type, Dtype], *, null_str: str = str(None)
) -> T_IndexOps:
    """Cast `index_ops` to StringType Spark type, given `dtype` and `null_str`,
    representing null Spark column.
    """
    from pyspark.pandas.internal import InternalField

    if isinstance(dtype, extension_dtypes):
        scol = index_ops.spark.column.cast(StringType())
    else:
        casted = index_ops.spark.column.cast(StringType())
        scol = F.when(index_ops.spark.column.isNull(), null_str).otherwise(casted)
    return index_ops._with_new_scol(
        scol.alias(index_ops._internal.data_spark_column_names[0]),
        field=InternalField(dtype=dtype),
    )

def _as_other_type(
    index_ops: T_IndexOps, dtype: Union[str, type, Dtype], spark_type: DataType
) -> T_IndexOps:
    """Cast `index_ops` to a `dtype` (`spark_type`) that needs no pre-processing.

    Destination types that need pre-processing: CategoricalDtype, BooleanType, and StringType.
    """
    from pyspark.pandas.internal import InternalField

    need_pre_process = (
        isinstance(dtype, CategoricalDtype)
        or isinstance(spark_type, BooleanType)
        or isinstance(spark_type, StringType)
    )
    assert not need_pre_process, "Pre-processing is needed before the type casting."

    scol = index_ops.spark.column.cast(spark_type)
    return index_ops._with_new_scol(
        scol.alias(index_ops._internal.data_spark_column_names[0]),
        field=InternalField(dtype=dtype),
    )

class DataTypeOps(object, metaclass=ABCMeta):
    """The base class for binary operations of pandas-on-Spark objects (of different data types)."""

    def __new__(cls, dtype: Dtype, spark_type: DataType):
        from pyspark.pandas.data_type_ops.binary_ops import BinaryOps
        from pyspark.pandas.data_type_ops.boolean_ops import BooleanOps, BooleanExtensionOps
        from pyspark.pandas.data_type_ops.categorical_ops import CategoricalOps
        from pyspark.pandas.data_type_ops.complex_ops import ArrayOps, MapOps, StructOps
        from pyspark.pandas.data_type_ops.date_ops import DateOps
        from pyspark.pandas.data_type_ops.datetime_ops import DatetimeOps
        from pyspark.pandas.data_type_ops.null_ops import NullOps
        from pyspark.pandas.data_type_ops.num_ops import (
            DecimalOps,
            FractionalExtensionOps,
            FractionalOps,
            IntegralExtensionOps,
            IntegralOps,
        )
        from pyspark.pandas.data_type_ops.string_ops import StringOps, StringExtensionOps
        from pyspark.pandas.data_type_ops.udt_ops import UDTOps

        if isinstance(dtype, CategoricalDtype):
            return object.__new__(CategoricalOps)
        elif isinstance(spark_type, DecimalType):
            return object.__new__(DecimalOps)
        elif isinstance(spark_type, FractionalType):
            if extension_float_dtypes_available and type(dtype) in [Float32Dtype, Float64Dtype]:
                return object.__new__(FractionalExtensionOps)
            else:
                return object.__new__(FractionalOps)
        elif isinstance(spark_type, IntegralType):
            if extension_dtypes_available and type(dtype) in [
                Int8Dtype,
                Int16Dtype,
                Int32Dtype,
                Int64Dtype,
            ]:
                return object.__new__(IntegralExtensionOps)
            else:
                return object.__new__(IntegralOps)
        elif isinstance(spark_type, StringType):
            if extension_object_dtypes_available and isinstance(dtype, StringDtype):
                return object.__new__(StringExtensionOps)
            else:
                return object.__new__(StringOps)
        elif isinstance(spark_type, BooleanType):
            if extension_object_dtypes_available and isinstance(dtype, BooleanDtype):
                return object.__new__(BooleanExtensionOps)
            else:
                return object.__new__(BooleanOps)
        elif isinstance(spark_type, TimestampType):
            return object.__new__(DatetimeOps)
        elif isinstance(spark_type, DateType):
            return object.__new__(DateOps)
        elif isinstance(spark_type, BinaryType):
            return object.__new__(BinaryOps)
        elif isinstance(spark_type, ArrayType):
            return object.__new__(ArrayOps)
        elif isinstance(spark_type, MapType):
            return object.__new__(MapOps)
        elif isinstance(spark_type, StructType):
            return object.__new__(StructOps)
        elif isinstance(spark_type, NullType):
            return object.__new__(NullOps)
        elif isinstance(spark_type, UserDefinedType):
            return object.__new__(UDTOps)
        else:
            raise TypeError("Type %s was not understood." % dtype)

    def __init__(self, dtype: Dtype, spark_type: DataType):
        self.dtype = dtype
        self.spark_type = spark_type

    @property
    def pretty_name(self) -> str:
        raise NotImplementedError()

    def add(self, left, right) -> Union["Series", "Index"]:
        raise TypeError("Addition can not be applied to %s." % self.pretty_name)

    def sub(self, left, right) -> Union["Series", "Index"]:
        raise TypeError("Subtraction can not be applied to %s." % self.pretty_name)

    def mul(self, left, right) -> Union["Series", "Index"]:
        raise TypeError("Multiplication can not be applied to %s." % self.pretty_name)

    def truediv(self, left, right) -> Union["Series", "Index"]:
        raise TypeError("True division can not be applied to %s." % self.pretty_name)

    def floordiv(self, left, right) -> Union["Series", "Index"]:
        raise TypeError("Floor division can not be applied to %s." % self.pretty_name)

    def mod(self, left, right) -> Union["Series", "Index"]:
        raise TypeError("Modulo can not be applied to %s." % self.pretty_name)

    def pow(self, left, right) -> Union["Series", "Index"]:
        raise TypeError("Exponentiation can not be applied to %s." % self.pretty_name)

    def radd(self, left, right) -> Union["Series", "Index"]:
        raise TypeError("Addition can not be applied to %s." % self.pretty_name)

    def rsub(self, left, right) -> Union["Series", "Index"]:
        raise TypeError("Subtraction can not be applied to %s." % self.pretty_name)

    def rmul(self, left, right) -> Union["Series", "Index"]:
        raise TypeError("Multiplication can not be applied to %s." % self.pretty_name)

    def rtruediv(self, left, right) -> Union["Series", "Index"]:
        raise TypeError("True division can not be applied to %s." % self.pretty_name)

    def rfloordiv(self, left, right) -> Union["Series", "Index"]:
        raise TypeError("Floor division can not be applied to %s." % self.pretty_name)

    def rmod(self, left, right) -> Union["Series", "Index"]:
        raise TypeError("Modulo can not be applied to %s." % self.pretty_name)

    def rpow(self, left, right) -> Union["Series", "Index"]:
        raise TypeError("Exponentiation can not be applied to %s." % self.pretty_name)

    def __and__(self, left, right) -> Union["Series", "Index"]:
        raise TypeError("Bitwise and can not be applied to %s." % self.pretty_name)

    def __or__(self, left, right) -> Union["Series", "Index"]:
        raise TypeError("Bitwise or can not be applied to %s." % self.pretty_name)

    def rand(self, left, right) -> Union["Series", "Index"]:
        return left.__and__(right)

    def ror(self, left, right) -> Union["Series", "Index"]:
        return left.__or__(right)

    def restore(self, col: pd.Series) -> pd.Series:
        """Restore column when to_pandas."""
        return col

    def prepare(self, col: pd.Series) -> pd.Series:
        """Prepare column when from_pandas."""
        return col.replace({np.nan: None})

    def isnull(self, index_ops: T_IndexOps) -> T_IndexOps:
        return index_ops._with_new_scol(index_ops.spark.column.isNull())

    def astype(self, index_ops: T_IndexOps, dtype: Union[str, type, Dtype]) -> T_IndexOps:
        raise TypeError("astype can not be applied to %s." % self.pretty_name)


text:
package es.ucm.fdi.tp;

import static org.junit.Assert.assertEquals;

import java.util.List;

import org.junit.Test;

import es.ucm.fdi.tp.was.WolfAndSheepAction;
import es.ucm.fdi.tp.was.WolfAndSheepState;

public class WolfAndSheepStateTest {

	@Test
	public void trappedWolf(){ //si los movimientos del lobo son 0 tienen que ganar las ovejas
		WolfAndSheepState was = new WolfAndSheepState(8);
		//colocamos a las ovejas al rededor del lobo para atraparle.

		was = new WolfAndSheepState(was, was.getBoard(), was.isFinished(), was.getWinner());
		WolfAndSheepAction ac = new WolfAndSheepAction(1, 6, 1, 0, 1); //colocamos una oveja en la posición 6,1 y el lobo ya no se puede mover
		was = ac.applyTo(was);

		assertEquals("The winner once the wolf is trapped should be the sheeps!", 1, was.getWinner());
	}

	@Test
	public void WolfWon(){
		WolfAndSheepState was = new WolfAndSheepState(8);
		WolfAndSheepAction ac = new WolfAndSheepAction(0, 0, 0, 7, 0); //colocamos al lobo en la primera celda

		was = ac.applyTo(was);
		assertEquals("The winner once the wolf is in the row 0 should be the wolf!", 0, was.getWinner());
	}

	@Test
	public void ChechValidAcctions(){
		WolfAndSheepState was = new WolfAndSheepState(8);

		List<WolfAndSheepAction> valid = was.validActions(0);
		assertEquals("The valid actions should be just 1" , 1, valid.size());

		WolfAndSheepAction ac = new WolfAndSheepAction(0, 6, 1, 7, 0); //we place the wolf in the position 6, 1
		was = ac.applyTo(was);
		valid = was.validActions(0);
		assertEquals("The valid actions should be 4" , 4, valid.size());
	}
	@Test
	public void CheckSheepActions(){
		WolfAndSheepState was = new WolfAndSheepState(8);

		//we leave only the first sheep (placed in 0,1 and erease the other ones)

		int i = 2;
		int[][] b = was.getBoard();
		while(i < was.getDim()){
			b[0][i] = -1;
			i++;
		}
		was = new WolfAndSheepState(was, b, was.isFinished(), was.getWinner());

		List<WolfAndSheepAction> valid = was.validActions(1);
		assertEquals("The valid actions should be 2" , 2, valid.size());

		WolfAndSheepAction ac = new WolfAndSheepAction(1, 0, 7, 0, 1); //we place the wolf in the position 6, 1
		was = ac.applyTo(was);

		valid = was.validActions(1);
		assertEquals("The valid actions should be just 1" , 1, valid.size());
	}
}


text:
"""* Core modules.
@package jscribe.core
"""


text:
import os
import sys
import distutils.unixccompiler
import distutils.ccompiler
import distutils.sysconfig
import distutils.command.build_ext as build_ext
import distutils.dist as dist

from distutils \
    import \
        errors
from distutils \
    import \
        sysconfig

DEFAULT_COMPILERS = {
        "win32": [None, "mingw32"],
        "default": [None]
}

def _mingw32_cc():
    compiler_type = "mingw32"
    compiler = distutils.ccompiler.new_compiler(compiler=compiler_type)
    return compiler.compiler_so

def detect_distutils_cc(ctx):
    if not sys.platform in DEFAULT_COMPILERS:
        plat = "default"
    else:
        plat = sys.platform

    sys.stderr.write("Detecting distutils C compiler... ")
    compiler_type = \
            distutils.ccompiler.get_default_compiler()
    if sys.platform == "win32":
        if compiler_type == "msvc":
            try:
                compiler = distutils.ccompiler.new_compiler(
                        compiler="msvc")
                compiler.initialize()
                cc = [compiler.cc]
            except errors.DistutilsPlatformError:
                cc = _mingw32_cc()
        else:
            cc = _mingw32_cc()
    else:
        cc = distutils.sysconfig.get_config_var("CC")
        # FIXME: use shlex for proper escaping handling
        cc = cc.split()
    sys.stderr.write("%s\n" % compiler_type)
    return cc

# XXX: unixccompiler instances are the only classes where we can hope
# to get semi-sensical data. Reusing them also makes transition easier
# for packagers, as their compilation options will be reused.
# OTOH, having a sane tooling system will make customization much
# easier.
def get_configuration(compiler_type=None):
    plat = os.name
    if compiler_type is None:
        compiler_type = distutils.ccompiler.get_default_compiler(plat)

    if not compiler_type in distutils.ccompiler.compiler_class:
        raise ValueError("compiler type %s is not recognized" %
                         compiler_type)

    env = {"CC": [],
        "CPPPATH": [],
        "BASE_CFLAGS": [],
        "OPT": [],
        "SHARED": [],
        "CFLAGS": [],
        "SHLINK": [],
        "LDFLAGS": [],
        "LIBDIR": [],
        "LIBS": [],
        "SO": ""}

    env["CPPPATH"].append(sysconfig.get_python_inc())
    if compiler_type == "unix":
        env["CC"].extend(sysconfig.get_config_var("CC").split(" "))
        env["BASE_CFLAGS"].extend(sysconfig.get_config_var("BASECFLAGS").split(" "))
        env["OPT"].extend(sysconfig.get_config_var("OPT").split(" "))
        env["SHARED"].extend(sysconfig.get_config_var("CCSHARED").split(" "))

        env["SHLINK"] = sysconfig.get_config_var("LDSHARED").split(" ")
        env["SO"] = sysconfig.get_config_var("SO")
        env["LDFLAGS"] = sysconfig.get_config_var("LDFLAGS").split()
        if "-pthread" in sysconfig.get_config_var("LDFLAGS"):
            env["LDFLAGS"].insert(0, "-pthread")
        env["CFLAGS"].extend(sysconfig.get_config_var("CFLAGS").split(" "))
        env["FRAMEWORKS"] = []
        setup_unix(env)
    elif compiler_type == "msvc":
        setup_msvc(env)
    elif compiler_type == "mingw32":
        setup_mingw32(env)
    else:
        raise ValueError("Gne ?")

    return env

def _get_ext_library_dirs():
    binst = build_ext.build_ext(dist.Distribution())
    binst.initialize_options()
    binst.finalize_options()
    return binst.library_dirs

def _get_ext_libraries(compiler):
    binst = build_ext.build_ext(dist.Distribution())
    binst.compiler = compiler
    binst.initialize_options()
    binst.finalize_options()
    class _FakeExt(object):
        def __init__(self):
            self.libraries = []
    return binst.get_libraries(_FakeExt())

def setup_unix(env):
    if sys.platform == "darwin":
        env["LDFLAGS"].extend(["-bundle", "-undefined", "dynamic_lookup"])

        def _strip_arch(flag):
            value = env[flag]
            while "-arch" in value:
                id = value.index("-arch")
                value.pop(id)
                value.pop(id)
            return value
        for flag in ["BASE_CFLAGS", "LDFLAGS"]:
            env[flag] = _strip_arch(flag)

def setup_msvc(env):
    compiler = distutils.ccompiler.new_compiler(
            compiler="msvc")
    compiler.initialize()

    env["CC"] = compiler.cc
    env["BASE_CFLAGS"].extend(compiler.compile_options)

    env["SHLINK"] = compiler.linker
    env["SO"] = ".pyd"
    env["LDFLAGS"] = compiler.ldflags_shared
    env["LIBDIR"].extend( _get_ext_library_dirs())

def setup_mingw32(env):
    compiler = distutils.ccompiler.new_compiler(
            compiler="mingw32")

    env["CC"] = ["gcc"]
    env["BASE_CFLAGS"].extend(["-mno-cygwin"])

    env["SHLINK"] = ["gcc", "-mno-cygwin", "-shared"]
    env["SO"] = ".pyd"
    #env["LDFLAGS"] = compiler.ldflags_shared
    env["LIBDIR"].extend( _get_ext_library_dirs())

    libs = _get_ext_libraries(compiler)
    libs += compiler.dll_libraries
    env["LIBS"].extend(libs)


text:
namespace Yuki.Api.TimeEntries.GetRunningTimeEntry
{
    public class Request
    {
        public Request(int userId)
        {
            this.UserId = userId;
        }

        public int UserId
        {
            get;
            private set;
        }
    }
}


text:
import React from 'react';
import PropTypes from 'prop-types';
import { graphql } from 'gatsby';
import { Row, Col } from 'react-flexbox-grid';

import IndexLayout from '../components/layouts/Index';
import Header from '../components/blog/Header';
import BioEntry from '../components/blog/BioEntry';
import MetaTags from '../components/blog/MetaTags';
import AboutSection from '../components/blog/AboutSection';

export default function About({ data }) {
  return (
    <IndexLayout>
      <Row>
        <Col
          lg={8}
          lgOffset={2}
          style={{
            'text-align': 'left',
          }}
        >
          <MetaTags
            title={`About`}
            path={`/about`}
            description={'Hey, I am Kostas. Nice having you here.'}
          />

            Hey, I am Kostas. Nice having you here.

            <AboutSection title={'Intro'}>

                I design software architectures, APIs and databases to serve the rest of an
                application. I am a full stack engineer but I love taking a specific field in my
                hands and getting the juice out of it. I am always interested in being a part of a
                team that builds great software and getting things done.

                I like things like Node.js, Express.js, React.js, Webpack, Gulp, MySQL, MongoDB,
                Mocha, Jest, AWS, Ansible, Git and a whole lot more.

                I like speaking to meetups and
                conferences about things that tried and also talking with others on my{' '}
                podcast. I created{' '}
                Janitr and{' '}
                GitYeller You can find more code samples and my
                contributions on Github. Along with some
                folks, we are organizing the local{' '}
                Nodejs meetup and{' '}

                  DEVit Conf

                , the biggest web development conference in northern Greece. We are also known as{' '}

                  SKGtech

                .

                This site is being generated using Gatsby.js and you can find the source on{' '}
                 GitHub.

                I am currently living in Thessaloniki, Greece. Have you ever been? Take a look, I am
                sure you will fall in love with the amazing beaches of Chalkidiki.

            </AboutSection>
            <AboutSection title={'Bio'}>
              <BioEntry year={'2019'}>
                Started working with Bulb, hopefully I will get to
                help on world{"'"}s most serious issue at the moment.
              </BioEntry>
              <BioEntry year={'2018'}>
                Started working with Trouva, a curated marketplace
                with unique products that you wont find on high streets.
              </BioEntry>
              <BioEntry year={'2018'}>
                Worked with Geekbot, a fully remote company with a
                mission to change the way we do standup meetings.
              </BioEntry>
              <BioEntry year={'2017'}>
                Worked with Quotelier. A amazing product on the
                hospitality industry.
              </BioEntry>
              <BioEntry year={'2017'}>
                Released Janitr.net
              </BioEntry>
              <BioEntry year={'2016'}>
                Started the first ever{' '}
                Podcast for greek developers
              </BioEntry>
              <BioEntry year={'2015'}>
                Started working with Goodvidio
              </BioEntry>
              <BioEntry year={'2014'}>
                Won the first place at{' '}

                  Thessaloniki Startup Live
                {' '}
                with the Tunedeck Team
              </BioEntry>
              <BioEntry year={'2014'}>
                Stargento is on the air
              </BioEntry>
              <BioEntry year={'2014'}>
                Started working with a local web design agency. Lots of E-Commerce, Magento based,
                projects
              </BioEntry>
              <BioEntry year={'2013'}>2013 This blog is born</BioEntry>
              <BioEntry year={'2013'}>
                Started working with DTek. A lot of nice projects born
                from there like Carfinder.gr and{' '}
                Viral Contest App
              </BioEntry>
              <BioEntry year={'2013'}>
                Fulfilled my military service as defined by the Greek Constitution (nine months)
              </BioEntry>
              <BioEntry year={'2012'}>
                Graduated from{' '}

                  A.T.E.I. Thessalonikis with the BsC of Computer Science

              </BioEntry>
              <BioEntry year={'2005'}>Started Web Development using raw HTML, CSS, JS</BioEntry>
              <BioEntry year={'2002'}>
                Started Web Development using Flash, Dreamweaver and MS Web Publisher
              </BioEntry>
              <BioEntry year={'2001'}>Wrote my first app (Lucky Seven) using Visual Basic</BioEntry>
              <BioEntry year={'2000'}>
                Bought my first computer. Since then I have formatted every hard disk of my close
                friends
              </BioEntry>
              <BioEntry year={'1988'}>
                Bing Bang happens somewhere in Thessaloniki, Greece.
                Generation Y got upgraded
              </BioEntry>
            </AboutSection>
            <AboutSection title={'Projects'}>
              <Row>
                <Col md={4}>

                    Janitr

                </Col>
                <Col md={8} className="text-right">
                  A Slack bot that welcomes news members on your team
                </Col>
              </Row>
              <Row>
                <Col md={4}>

                    GitYeller (Dead)

                </Col>
                <Col md={8} className="text-right">
                  Subscribe to your favorite GitHub repository and get notified by email for new
                  issues with specific labels.
                </Col>
              </Row>
              <Row>
                <Col md={4}>

                    Stargento (Dead)

                </Col>
                <Col md={8} className="text-right">
                  PHP sandbox powered up with the latest Magento installation to test your Magento
                  skills
                </Col>
              </Row>
            </AboutSection>

            <AboutSection title={'Talks'}>
              <Row>
                <Col md={4}>

                    JavaScript 101

                </Col>
                <Col md={8} className="text-right">
                  A JavaScript journey for beginners
                </Col>
              </Row>
              <Row>
                <Col md={4}>

                    Micro Services Architecture

                </Col>
                <Col md={8} className="text-right">
                  How do I scale my codebase
                </Col>
              </Row>
              <Row>
                <Col md={4} />
                <Col md={8} className="text-right">
                  Find all my presentation slides at{' '}

                    Slides.com

                </Col>
              </Row>
            </AboutSection>

        </Col>
      </Row>
    </IndexLayout>
  );
}

About.propTypes = {
  data: PropTypes.object,
};

export const aboutPageQuery = graphql`
  query AboutPageSiteMetadata {
    file(relativePath: { eq: "avatar.jpg" }) {
      childImageSharp {
        fluid(maxWidth: 750) {
          ...GatsbyImageSharpFluid_withWebp
        }
      }
    }
  }
`;


text:
TestedInterface = "Navigation"
Tested_resultCode = "IN_USE"
Tested_wrongJSON = false

Test = require('user_modules/IsReady_Template/ATF_Interface_IsReady_missing_SplitRPC_Template')

return Test


text:
String theory is an Atom UI theme based on `Nucleus-Dark`. Similarly to Nucleus,
it bases most of the coloring on the syntax theme you use within Atom, and works
best with a dark syntax theme. My personal recommendations for syntax themes are
`seti` or `Base16 Tomorrow Dark`.

![String-theory](http://fred.d.pr/19qGh.png)

## Why ST versus Nucleus?

Nucleus, while a great theme, is quite opinionated. As such, I felt more at ease
forking rather than submitting a pull request. String-theory includes changes to
several sections of the Atom UI, including a slightly cleaner status bar,
tighter font and tab sizing, as well as some better control over gutter display.

## Installing

Installing String-theory is as simple as installing another atom package. You
can either find it via the settings page, or by using `apm`:

```apm install string-theory```

## Contributing

Feel free to submit pull requests to further string-theory development. Thanks
in advance for your help.


text:
package org.jboss.weld.tests.assignability;

import jakarta.enterprise.inject.Vetoed;

@Vetoed
public class Animal<A, B, C> {

}


text:
///////////////////////////////////////////////////////////////////////////////////////////////////////
// Tencent is pleased to support the open source community by making Appecker available.
//
// Copyright (C) 2015 THL A29 Limited, a Tencent company. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in
// compliance with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under the License is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
// either express or implied. See the License for the specific language governing permissions and
// limitations under the License.
///////////////////////////////////////////////////////////////////////////////////////////////////////

#import "ATFCompleteDemoAppDelegate.h"

@implementation ATFCompleteDemoAppDelegate

@synthesize window;
@synthesize navController;

#pragma mark -
#pragma mark Application lifecycle

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    // Override point for customization after application launch.

    [self.window makeKeyAndVisible];

	[window addSubview:navController.view];

    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application {
    /*
     Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
     Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
     */
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    /*
     Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
     If your application supports background execution, called instead of applicationWillTerminate: when the user quits.
     */
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    /*
     Called as part of  transition from the background to the inactive state: here you can undo many of the changes made on entering the background.
     */
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    /*
     Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
     */
}

- (void)applicationWillTerminate:(UIApplication *)application {
    /*
     Called when the application is about to terminate.
     See also applicationDidEnterBackground:.
     */
}

#pragma mark -
#pragma mark Memory management

- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application {
    /*
     Free up as much memory as possible by purging cached data objects that can be recreated (or reloaded from disk) later.
     */
}

- (void)dealloc {
    [window release];
	[navController release];
    [super dealloc];
}

@end


text:
package com.connexta.arbitro.cond;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import com.connexta.arbitro.attr.AttributeValue;
import com.connexta.arbitro.attr.BagAttribute;
import com.connexta.arbitro.attr.BooleanAttribute;
import com.connexta.arbitro.ctx.EvaluationCtx;

/**
 * Represents all of the higher order bag functions, except map, which has its own class due to the
 * issues with its return type. Unlike the other functions that are designed to work over any types
 * (the type-* functions) these functions don't use specific names to describe what type they
 * operate over, so you don't need to install new instances for any new datatypes you define.
 *
 * @since 1.0
 * @author Seth Proctor
 */
public class HigherOrderFunction implements Function {

	/**
	 * Standard identifier for the any-of function.
	 */
	public static final String NAME_ANY_OF = FunctionBase.FUNCTION_NS + "any-of";

	/**
	 * Standard identifier for the all-of function.
	 */
	public static final String NAME_ALL_OF = FunctionBase.FUNCTION_NS + "all-of";

	/**
	 * Standard identifier for the any-of-any function.
	 */
	public static final String NAME_ANY_OF_ANY = FunctionBase.FUNCTION_NS + "any-of-any";

	/**
	 * Standard identifier for the all-of-any function.
	 */
	public static final String NAME_ALL_OF_ANY = FunctionBase.FUNCTION_NS + "all-of-any";

	/**
	 * Standard identifier for the any-of-all function.
	 */
	public static final String NAME_ANY_OF_ALL = FunctionBase.FUNCTION_NS + "any-of-all";

	/**
	 * Standard identifier for the all-of-all function.
	 */
	public static final String NAME_ALL_OF_ALL = FunctionBase.FUNCTION_NS + "all-of-all";

	// internal identifiers for each of the supported functions
	private static final int ID_ANY_OF = 0;
	private static final int ID_ALL_OF = 1;
	private static final int ID_ANY_OF_ANY = 2;
	private static final int ID_ALL_OF_ANY = 3;
	private static final int ID_ANY_OF_ALL = 4;
	private static final int ID_ALL_OF_ALL = 5;

	// internal mapping of names to ids
	private static HashMap<String, Integer> idMap;

	// the internal identifier for each function
	private int functionId;

	// the real identifier for each function
	private URI identifier;

	// should the second argument (the first arg passed to the sub-function)
	// be a bag
	private boolean secondIsBag;

	// the stuff used to make sure that we have a valid return type or a
	// known error, just like in the attribute classes
	private static URI returnTypeURI;
	private static RuntimeException earlyException;

	// try to create the return type URI, and also setup the id map
	static {
		try {
			returnTypeURI = new URI(BooleanAttribute.identifier);
		} catch (Exception e) {
			earlyException = new IllegalArgumentException();
			earlyException.initCause(e);
		}

		idMap = new HashMap<String, Integer>();

		idMap.put(NAME_ANY_OF, Integer.valueOf(ID_ANY_OF));
		idMap.put(NAME_ALL_OF, Integer.valueOf(ID_ALL_OF));
		idMap.put(NAME_ANY_OF_ANY, Integer.valueOf(ID_ANY_OF_ANY));
		idMap.put(NAME_ALL_OF_ANY, Integer.valueOf(ID_ALL_OF_ANY));
		idMap.put(NAME_ANY_OF_ALL, Integer.valueOf(ID_ANY_OF_ALL));
		idMap.put(NAME_ALL_OF_ALL, Integer.valueOf(ID_ALL_OF_ALL));
	};

	/**
	 * Creates a new instance of the given function.
	 *
	 * @param functionName the function to create
	 *
	 * @throws IllegalArgumentException if the function is unknown
	 */
	public HigherOrderFunction(String functionName) {
		// try to get the function's identifier
		Integer i = (Integer) (idMap.get(functionName));
		if (i == null)
			throw new IllegalArgumentException("unknown function: " + functionName);
		functionId = i.intValue();

		// setup the URI form of this function's idenitity
		try {
			identifier = new URI(functionName);
		} catch (URISyntaxException use) {
			throw new IllegalArgumentException("invalid URI");
		}

		// see if the second arg is a bag
		if ((functionId != ID_ANY_OF) && (functionId != ID_ALL_OF))
			secondIsBag = true;
		else
			secondIsBag = false;
	}

	/**
	 * Returns a Set containing all the function identifiers supported by this class.
	 *
	 * @return a Set of Strings
	 */
	public static Set getSupportedIdentifiers() {
		return Collections.unmodifiableSet(idMap.keySet());
	}

	/**
	 * Returns the full identifier of this function, as known by the factories.
	 *
	 * @return the function's identifier
	 */
	public URI getIdentifier() {
		return identifier;
	}

	/**
	 * Returns the same value as getReturnType. This is here to support the
	 * Expression interface.
	 *
	 * @return the return type
	 */
	public URI getType() {
		return getReturnType();
	}

	/**
	 * Returns the type of attribute value that will be returned by this function.
	 *
	 * @return the return type
	 */
	public URI getReturnType() {
		if (earlyException != null)
			throw earlyException;

		return returnTypeURI;
	}

	/**
	 * Returns whether or not this function will actually return a bag of values.
	 *
	 * @return true if the function returns a bag of values, otherwise false
	 */
	public boolean returnsBag() {
		return false;
	}

	/**
	 * Evaluates the function, using the specified parameters.
	 *
	 * @param inputs a List of Evaluatable objects representing the
	 *            arguments passed to the function
	 * @param context an EvaluationCtx so that the Evaluatable objects can
	 *            be evaluated
	 * @return an EvaluationResult representing the function's result
	 */
	public EvaluationResult evaluate(List inputs, EvaluationCtx context) {

		Iterator iterator = inputs.iterator();

		// get the first arg, which is the function
		Expression xpr = (Expression) (iterator.next());
		Function function = null;

		if (xpr instanceof Function) {
			function = (Function) xpr;
		} else {
			function = (Function) (((VariableReference) xpr).getReferencedDefinition()
					.getExpression());
		}

		// get the two inputs, and if anything is INDETERMINATE, then we
		// stop right away
		AttributeValue[] args = new AttributeValue[2];

		Evaluatable eval = (Evaluatable) (iterator.next());
		EvaluationResult result = eval.evaluate(context);
		if (result.indeterminate())
			return result;
		args[0] = (AttributeValue) (result.getAttributeValue());

		eval = (Evaluatable) (iterator.next());
		result = eval.evaluate(context);
		if (result.indeterminate())
			return result;
		args[1] = (AttributeValue) (result.getAttributeValue());

		// now we're ready to do the evaluation
		result = null;

		switch (functionId) {

		case ID_ANY_OF: {

			// param: boolean-function, single value, bag of same type
			// return: boolean
			// using the function, iterate through the bag, and if one
			// of the bag elements matches the single value, return
			// true, otherwise return false

			result = any(args[0], (BagAttribute) (args[1]), function, context, false);
			break;
		}

		case ID_ALL_OF: {

			// param: boolean-function, single value, bag of same type
			// return: boolean
			// using the function, iterate through the bag, and if all
			// of the bag elements match the single value, return
			// true, otherwise return false

			result = all(args[0], (BagAttribute) (args[1]), function, context);
			break;
		}

		case ID_ANY_OF_ANY: {

			// param: boolean-function, bag, bag of same type
			// return: boolean
			// apply the function to every combination of a single value from
			// the first bag and a single value from the second bag, and if
			// any evaluation is true return true, otherwise return false

			result = new EvaluationResult(BooleanAttribute.getInstance(false));
			Iterator it = ((BagAttribute) args[0]).iterator();
			BagAttribute bag = (BagAttribute) (args[1]);

			while (it.hasNext()) {
				AttributeValue value = (AttributeValue) (it.next());
				result = any(value, bag, function, context, false);

				if (result.indeterminate())
					return result;

				if (((BooleanAttribute) (result.getAttributeValue())).getValue())
					break;
			}
			break;
		}

		case ID_ALL_OF_ANY: {

			// param: boolean-function, bag, bag of same type
			// return: boolean
			// iterate through the first bag, and if for each of those values
			// one of the values in the second bag matches then return true,
			// otherwise return false

			result = allOfAny((BagAttribute) (args[1]), (BagAttribute) (args[0]), function, context);
			break;
		}

		case ID_ANY_OF_ALL: {

			// param: boolean-function, bag, bag of same type
			// return: boolean
			// iterate through the second bag, and if for each of those values
			// one of the values in the first bag matches then return true,
			// otherwise return false

			result = anyOfAll((BagAttribute) (args[0]), (BagAttribute) (args[1]), function, context);
			break;
		}

		case ID_ALL_OF_ALL: {

			// param: boolean-function, bag, bag of same type
			// return: boolean
			// iterate through the first bag, and for each of those values
			// if every value in the second bag matches using the given
			// function, then return true, otherwise return false

			result = new EvaluationResult(BooleanAttribute.getInstance(true));
			Iterator it = ((BagAttribute) args[0]).iterator();
			BagAttribute bag = (BagAttribute) (args[1]);

			while (it.hasNext()) {
				AttributeValue value = (AttributeValue) (it.next());
				result = all(value, bag, function, context);

				if (result.indeterminate())
					return result;

				if (!((BooleanAttribute) (result.getAttributeValue())).getValue())
					break;
			}
			break;
		}

		}

		return result;
	}

	/**
	 * Checks that the given inputs are valid for this function.
	 *
	 * @param inputs a List of Evaluatables
	 *
	 * @throws IllegalArgumentException if the inputs are invalid
	 */
	public void checkInputs(List inputs) throws IllegalArgumentException {
		Object[] list = inputs.toArray();

		// first off, check that we got the right number of paramaters
		if (list.length != 3)
			throw new IllegalArgumentException("requires three inputs");

		// now, try to cast the first element into a function
		Function function = null;

		if (list[0] instanceof Function) {
			function = (Function) (list[0]);
		} else if (list[0] instanceof VariableReference) {
			Expression xpr = ((VariableReference) (list[0])).getReferencedDefinition()
					.getExpression();
			if (xpr instanceof Function)
				function = (Function) xpr;
		}

		if (function == null)
			throw new IllegalArgumentException("first arg to higher-order "
					+ " function must be a function");

		// check that the function returns a boolean
		if (!function.getReturnType().toString().equals(BooleanAttribute.identifier))
			throw new IllegalArgumentException("higher-order function must "
					+ "use a boolean function");

		// get the two inputs
		Evaluatable eval1 = (Evaluatable) (list[1]);
		Evaluatable eval2 = (Evaluatable) (list[2]);

		// the first arg might be a bag
		if (secondIsBag && (!eval1.returnsBag()))
			throw new IllegalArgumentException("first arg has to be a bag");

		// the second arg must be a bag
		if (!eval2.returnsBag())
			throw new IllegalArgumentException("second arg has to be a bag");

		// finally, we need to make sure that the given type will work on
		// the given function
		List args = new ArrayList();
		args.add(eval1);
		args.add(eval2);
		function.checkInputsNoBag(args);
	}

	/**
	 * Checks that the given inputs are valid for this function if all inputs are considered to not
	 * be bags. This always throws an exception, since this function by definition must work on
	 * bags.
	 *
	 * @param inputs a List of Evaluatables
	 *
	 * @throws IllegalArgumentException always
	 */
	public void checkInputsNoBag(List inputs) throws IllegalArgumentException {
		throw new IllegalArgumentException("higher-order functions require " + "use of bags");
	}

	/**
	 * Private helper function that performs the any function, but lets you swap the argument order
	 * (so it can be used by any-of-all)
	 */
	private EvaluationResult any(AttributeValue value, BagAttribute bag, Function function,
			EvaluationCtx context, boolean argumentsAreSwapped) {
		return anyAndAllHelper(value, bag, function, context, false, argumentsAreSwapped);
	}

	/**
	 * Private helper function that performs the all function
	 */
	private EvaluationResult all(AttributeValue value, BagAttribute bag, Function function,
			EvaluationCtx context) {
		return anyAndAllHelper(value, bag, function, context, true, false);
	}

	/**
	 * Private helper for any & all functions
	 */
	private EvaluationResult anyAndAllHelper(AttributeValue value, BagAttribute bag,
			Function function, EvaluationCtx context, boolean allFunction,
			boolean argumentsAreSwapped) {
		BooleanAttribute attr = BooleanAttribute.getInstance(allFunction);
		Iterator it = bag.iterator();

		while (it.hasNext()) {
			List<Evaluatable> params = new ArrayList<Evaluatable>();

			if (!argumentsAreSwapped) {
				params.add(value);
				params.add((AttributeValue) (it.next()));
			} else {
				params.add((AttributeValue) (it.next()));
				params.add(value);
			}

			EvaluationResult result = function.evaluate(params, context);

			if (result.indeterminate())
				return result;

			BooleanAttribute bool = (BooleanAttribute) (result.getAttributeValue());
			if (bool.getValue() != allFunction) {
				attr = bool;
				break;
			}
		}

		return new EvaluationResult(attr);
	}

	/**
	 * any-of-all
	 */
	private EvaluationResult anyOfAll(BagAttribute anyBag, BagAttribute allBag, Function function,
			EvaluationCtx context) {
		return allAnyHelper(anyBag, allBag, function, context, true);
	}

	/**
	 * all-of-any
	 */
	private EvaluationResult allOfAny(BagAttribute anyBag, BagAttribute allBag, Function function,
			EvaluationCtx context) {
		return allAnyHelper(anyBag, allBag, function, context, false);
	}

	/**
	 * Private helper for the all-of-any and any-of-all functions
	 */
	private EvaluationResult allAnyHelper(BagAttribute anyBag, BagAttribute allBag,
			Function function, EvaluationCtx context, boolean argumentsAreSwapped) {
		Iterator it = allBag.iterator();

		while (it.hasNext()) {
			AttributeValue value = (AttributeValue) (it.next());
			EvaluationResult result = any(value, anyBag, function, context, argumentsAreSwapped);

			if (result.indeterminate())
				return result;

			if (!((BooleanAttribute) (result.getAttributeValue())).getValue())
				return result;
		}

		return new EvaluationResult(BooleanAttribute.getTrueInstance());
	}

    /**
     * Encodes this HigherOrderFunction into its XML form
     *
     * @return String
     */
    public String encode() {
        StringBuilder builder = new StringBuilder();
        encode(builder);
        return builder.toString();
    }

    /**
     * Encodes this HigherOrderFunction into its XML form and writes this out to the provided
     * StringBuilder
     *
     * @param builder string stream into which the XML-encoded data is written
     */
    public void encode(StringBuilder builder) {
        builder.append("<Function FunctionId=\"").append(getIdentifier().toString()).append("\"/>\n");
    }
}


text:
defaults write /Library/Preferences/com.apple.SoftwareUpdate CriticalUpdateInstall -bool yes
defaults write /Library/Preferences/com.apple.SoftwareUpdate ConfigDataInstall -bool yes
schedule=$(softwareupdate --schedule on)
run_config=$(softwareupdate --background-critical)

exit 0


text:
package org.apache.drill.exec.store.sys;

import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import net.hydromatic.optiq.SchemaPlus;

import org.apache.drill.common.JSONOptions;
import org.apache.drill.common.expression.SchemaPath;
import org.apache.drill.common.logical.StoragePluginConfig;
import org.apache.drill.exec.ops.FragmentContext;
import org.apache.drill.exec.physical.base.AbstractGroupScan;
import org.apache.drill.exec.planner.logical.DrillTable;
import org.apache.drill.exec.rpc.user.UserSession;
import org.apache.drill.exec.server.DrillbitContext;
import org.apache.drill.exec.server.options.DrillConfigIterator;
import org.apache.drill.exec.store.AbstractSchema;
import org.apache.drill.exec.store.AbstractStoragePlugin;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.google.common.collect.Sets;

public class SystemTablePlugin extends AbstractStoragePlugin{
  static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(SystemTablePlugin.class);

  private final DrillbitContext context;
  private final String name;

  public SystemTablePlugin(SystemTablePluginConfig configuration, DrillbitContext context, String name){
    this.context = context;
    this.name = name;
  }

  private SystemSchema schema = new SystemSchema();

  @Override
  public StoragePluginConfig getConfig() {
    return SystemTablePluginConfig.INSTANCE;
  }

  @Override
  public void registerSchemas(UserSession session, SchemaPlus parent) {
    parent.add(schema.getName(), schema);
  }

  public Iterator<Object> getRecordIterator(FragmentContext context, SystemTable table){
    switch(table){
    case VERSION:
      return new VersionIterator();
    case DRILLBITS:
      return new DrillbitIterator(context);
    case OPTION:
      return Iterables.concat((Iterable<Object>)(Object) new DrillConfigIterator(context.getConfig()), //
          context.getOptions()).iterator();
    default:
      throw new UnsupportedOperationException("Unable to create record iterator for table: " + table.getTableName());
    }
  }

  @Override
  public AbstractGroupScan getPhysicalScan(JSONOptions selection, List<SchemaPath> columns) throws IOException {
    SystemTable table = selection.getWith(context.getConfig(), SystemTable.class);
    return new SystemTableScan(table, this);
  }

  private class SystemSchema extends AbstractSchema{

    private Set<String> tableNames;

    public SystemSchema() {
      super(ImmutableList.<String>of(), "sys");
      Set<String> names = Sets.newHashSet();
      for(SystemTable t : SystemTable.values()){
        names.add(t.getTableName());
      }
      this.tableNames = ImmutableSet.copyOf(names);
    }

    @Override
    public Set<String> getTableNames() {
      return tableNames;
    }

    @Override
    public DrillTable getTable(String name) {
      for(SystemTable table : SystemTable.values()){
        if(table.getTableName().equalsIgnoreCase(name)){
          return new StaticDrillTable(table.getType(), SystemTablePlugin.this.name, SystemTablePlugin.this, table);
        }
      }
      return null;

    }

    @Override
    public String getTypeName() {
      return SystemTablePluginConfig.NAME;
    }

  }
}


text:
ofSoundPlayer_::ofSoundPlayer_ (){
	player		= NULL;
}

//---------------------------------------------------------------------------
ofSoundPlayer_::~ofSoundPlayer_(){
	if( player != NULL ){
		delete player;
		player = NULL;
	}
}

//---------------------------------------------------------------------------
bool ofSoundPlayer_::setPlayer(ofBaseSoundPlayer * newPlayer){
	if( player == NULL ){
		player = newPlayer;
		return true;
	}else{
		//TODO: should we delete newPlayer? This is why we need smart pointers.
		ofLog(OF_LOG_ERROR, "ofSoundPlayer::setPlayer - player already set!");
	}
	return false;
}

//--------------------------------------------------------------------
ofBaseSoundPlayer * ofSoundPlayer_::getPlayer(){
	return player;
}

//--------------------------------------------------------------------
void ofSoundPlayer_::loadSound(string fileName, bool stream){

	if( player == NULL ){
		setPlayer( new OF_SOUND_PLAYER_TYPE );
	}

	if( player != NULL ){
		player->loadSound(fileName, stream);
	}
}

//--------------------------------------------------------------------
void ofSoundPlayer_::unloadSound(){
	if( player != NULL ){
		player->unloadSound();
	}
}

//--------------------------------------------------------------------
void ofSoundPlayer_::play(){
	if( player != NULL ){
		player->play();
	}
}

//--------------------------------------------------------------------
void ofSoundPlayer_::stop(){
	if( player != NULL ){
		player->stop();
	}
}

//--------------------------------------------------------------------
void ofSoundPlayer_::setVolume(float vol){
	if( player != NULL ){
		player->setVolume(vol);
	}
}

//--------------------------------------------------------------------
void ofSoundPlayer_::setPan(float pan){
	if( player != NULL ){
		player->setPan(pan);
	}
}

//--------------------------------------------------------------------
void ofSoundPlayer_::setSpeed(float spd){
	if( player != NULL ){
		player->setSpeed(spd);
	}
}

//--------------------------------------------------------------------
void ofSoundPlayer_::setPaused(bool bP){
	if( player != NULL ){
		player->setPaused(bP);
	}
}

//--------------------------------------------------------------------
void ofSoundPlayer_::setLoop(bool bLp){
	if( player != NULL ){
		player->setLoop(bLp);
	}
}

//--------------------------------------------------------------------
void ofSoundPlayer_::setMultiPlay(bool bMp){
	if( player != NULL ){
		player->setMultiPlay(bMp);
	}
}

//--------------------------------------------------------------------
void ofSoundPlayer_::setPosition(float pct){
	if( player != NULL ){
		player->setPosition(pct);
	}
}

//--------------------------------------------------------------------
float ofSoundPlayer_::getPosition(){
	if( player != NULL ){
		return player->getPosition();
	} else {
		return 0;
	}
}

//--------------------------------------------------------------------
bool ofSoundPlayer_::getIsPlaying(){
	if( player != NULL ){
		return player->getIsPlaying();
	} else {
		return false;
	}
}

//--------------------------------------------------------------------
float ofSoundPlayer_::getSpeed(){
	if( player != NULL ){
		return player->getSpeed();
	} else {
		return 0;
	}
}

//--------------------------------------------------------------------
float ofSoundPlayer_::getPan(){
	if( player != NULL ){
		return player->getPan();
	} else {
		return 0;
	}
}