text:
/*	$NetBSD: dtfs_vfsops.c,v 1.3 2012/11/04 23:37:02 christos Exp $	*/

/*
 * Copyright (c) 2006  Antti Kantee.  All Rights Reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
 * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

#include <sys/types.h>
#include <sys/resource.h>

#include <stdio.h>
#include <assert.h>
#include <err.h>
#include <errno.h>
#include <puffs.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <util.h>

#include "dtfs.h"

static int
rtstr(struct puffs_usermount *pu, const char *str, enum vtype vt)
{
	struct puffs_node *pn = puffs_getroot(pu);
	struct vattr *va = &pn->pn_va;
	struct dtfs_file *df = DTFS_PTOF(pn);
	char ltarg[256+1];

	if (sscanf(str, "%*s %256s", ltarg) != 1)
		return 1;

	dtfs_baseattrs(va, vt, 2);
	df->df_linktarget = estrdup(ltarg);

	va->va_nlink = 1;
	va->va_size = strlen(df->df_linktarget);

	puffs_setrootinfo(pu, vt, 0, 0);

	return 0;
}

static int
rtdev(struct puffs_usermount *pu, const char *str, enum vtype vt)
{
	struct puffs_node *pn = puffs_getroot(pu);
	struct vattr *va = &pn->pn_va;
	int major, minor;

	if (sscanf(str, "%*s %d %d", &major, &minor) != 2)
		return 1;

	dtfs_baseattrs(va, vt, 2);
	va->va_nlink = 1;
	va->va_rdev = makedev(major, minor);

	if (vt == VBLK)
		va->va_mode |= S_IFBLK;
	else
		va->va_mode |= S_IFCHR;

	puffs_setrootinfo(pu, vt, 0, va->va_rdev);

	return 0;
}

static int
rtnorm(struct puffs_usermount *pu, const char *str, enum vtype vt)
{
	struct puffs_node *pn = puffs_getroot(pu);
	struct vattr *va = &pn->pn_va;

	dtfs_baseattrs(va, vt, 2);
	if (vt == VDIR)
		va->va_nlink = 2;
	else
		va->va_nlink = 1;

	puffs_setrootinfo(pu, vt, 0, 0);

	return 0;
}

struct rtype {
	char *tstr;
	enum vtype vt;
	int (*pfunc)(struct puffs_usermount *, const char *, enum vtype);
} rtypes[] = {
	{ "reg", VREG, rtnorm },
	{ "dir", VDIR, rtnorm },
	{ "blk", VBLK, rtdev },
	{ "chr", VCHR, rtdev },
	{ "lnk", VLNK, rtstr },
	{ "sock", VSOCK, rtnorm },
	{ "fifo", VFIFO, rtnorm }
};
#define NTYPES (sizeof(rtypes) / sizeof(rtypes[0]))

int
dtfs_domount(struct puffs_usermount *pu, const char *typestr)
{
	struct dtfs_mount *dtm;
	struct dtfs_file *dff;
	struct puffs_node *pn;
	int i;

	/* create mount-local thingie */
	dtm = puffs_getspecific(pu);
	dtm->dtm_nextfileid = 3;
	dtm->dtm_nfiles = 1;
	dtm->dtm_fsizes = 0;
	LIST_INIT(&dtm->dtm_pollent);

	/*
	 * create root directory, do it "by hand" to avoid special-casing
	 * dtfs_genfile()
	 */
	dff = dtfs_newdir();
	dff->df_dotdot = NULL;
	pn = puffs_pn_new(pu, dff);
	if (!pn)
		errx(1, "puffs_newpnode");
	puffs_setroot(pu, pn);

	if (!typestr) {
		rtnorm(pu, NULL, VDIR);
	} else {
		for (i = 0; i < NTYPES; i++) {
			if (strncmp(rtypes[i].tstr, typestr,
			    strlen(rtypes[i].tstr)) == 0) {
				if (rtypes[i].pfunc(pu, typestr,
				    rtypes[i].vt) != 0) {
					fprintf(stderr, "failed to parse "
					    "\"%s\"\n", typestr);
					return 1;
				}
				break;
			}
		}
		if (i == NTYPES) {
			fprintf(stderr, "no maching type for %s\n", typestr);
			return 1;
		}
	}

	return 0;
}

/*
 * statvfs() should fill in the following members of struct statvfs:
 *
 * unsigned long   f_bsize;         file system block size
 * unsigned long   f_frsize;        fundamental file system block size
 * unsigned long   f_iosize;        optimal file system block size
 * fsblkcnt_t      f_blocks;        number of blocks in file system,
 *                                            (in units of f_frsize)
 *
 * fsblkcnt_t      f_bfree;         free blocks avail in file system
 * fsblkcnt_t      f_bavail;        free blocks avail to non-root
 * fsblkcnt_t      f_bresvd;        blocks reserved for root
 *
 * fsfilcnt_t      f_files;         total file nodes in file system
 * fsfilcnt_t      f_ffree;         free file nodes in file system
 * fsfilcnt_t      f_favail;        free file nodes avail to non-root
 * fsfilcnt_t      f_fresvd;        file nodes reserved for root
 *
 *
 * The rest are filled in by the kernel.
 */
#define ROUND(a,b) (((a) + ((b)-1)) & ~((b)-1))
#define NFILES 1024*1024
int
dtfs_fs_statvfs(struct puffs_usermount *pu, struct statvfs *sbp)
{
	struct rlimit rlim;
	struct dtfs_mount *dtm;
	off_t btot, bfree;
	int pgsize;

	dtm = puffs_getspecific(pu);
	pgsize = getpagesize();
	memset(sbp, 0, sizeof(struct statvfs));

	/*
	 * Use datasize rlimit as an _approximation_ for free size.
	 * This, of course, is not accurate due to overhead and not
	 * accounting for metadata.
	 */
	if (getrlimit(RLIMIT_DATA, &rlim) == 0)
		btot = rlim.rlim_cur;
	else
		btot = 16*1024*1024;
	bfree = btot - dtm->dtm_fsizes;

	sbp->f_blocks = ROUND(btot, pgsize) / pgsize;
	sbp->f_files = NFILES;

	sbp->f_bsize = sbp->f_frsize = sbp->f_iosize = pgsize;
	sbp->f_bfree = sbp->f_bavail = ROUND(bfree, pgsize) / pgsize;
	sbp->f_ffree = sbp->f_favail = NFILES - dtm->dtm_nfiles;

	sbp->f_bresvd = sbp->f_fresvd = 0;

	return 0;
}
#undef ROUND

static void *
addrcmp(struct puffs_usermount *pu, struct puffs_node *pn, void *arg)
{

	if (pn == arg)
		return pn;

	return NULL;
}

int
dtfs_fs_fhtonode(struct puffs_usermount *pu, void *fid, size_t fidsize,
	struct puffs_newinfo *pni)
{
	struct dtfs_fid *dfid;
	struct puffs_node *pn;

	assert(fidsize == sizeof(struct dtfs_fid));
	dfid = fid;

	pn = puffs_pn_nodewalk(pu, addrcmp, dfid->dfid_addr);
	if (pn == NULL)
		return ESTALE;

	if (pn->pn_va.va_fileid != dfid->dfid_fileid
	    || pn->pn_va.va_gen != dfid->dfid_gen)
		return ESTALE;

	puffs_newinfo_setcookie(pni, pn);
	puffs_newinfo_setvtype(pni, pn->pn_va.va_type);
	puffs_newinfo_setsize(pni, pn->pn_va.va_size);
	puffs_newinfo_setrdev(pni, pn->pn_va.va_rdev);

	return 0;
}

int
dtfs_fs_nodetofh(struct puffs_usermount *pu, void *cookie,
	void *fid, size_t *fidsize)
{
	struct puffs_node *pn = cookie;
	struct dtfs_fid *dfid;
	extern int dynamicfh;

	if (dynamicfh == 0) {
		assert(*fidsize >= sizeof(struct dtfs_fid));
	} else {
		if (*fidsize < sizeof(struct dtfs_fid)) {
			*fidsize = sizeof(struct dtfs_fid);
			return E2BIG;
		}
		*fidsize = sizeof(struct dtfs_fid);
	}

	dfid = fid;

	dfid->dfid_addr = pn;
	dfid->dfid_fileid = pn->pn_va.va_fileid;
	dfid->dfid_gen = pn->pn_va.va_gen;

	return 0;
}

int
dtfs_fs_unmount(struct puffs_usermount *pu, int flags)
{

	return 0;
}


text:
package com.sfl.pms.core.api.internal.model.order;

import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.sfl.pms.core.api.internal.model.common.AbstractApiModel;
import com.sfl.pms.core.api.internal.model.common.request.ValidatableRequest;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;

/**
 * User: Ruben Dilanyan
 * Company: SFL LLC
 * Date: 1/19/16
 * Time: 2:15 PM
 */
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.EXISTING_PROPERTY, property = "type")
@JsonSubTypes({
        @JsonSubTypes.Type(value = OrderRequestRedirectPaymentMethodModel.class, name = "REDIRECT_PAYMENT_METHOD")
})
public abstract class OrderRequestPaymentMethodModel extends AbstractApiModel implements ValidatableRequest {

    private static final long serialVersionUID = 5455781958616770L;

    /* Properties */
    private final OrderRequestPaymentMethodClientType type;

    /* Constructors */
    public OrderRequestPaymentMethodModel(final OrderRequestPaymentMethodClientType type) {
        this.type = type;
    }

    /* Properties getters and setters */
    public OrderRequestPaymentMethodClientType getType() {
        return type;
    }

    /* Equals, HashCode and ToString */
    @Override
    public boolean equals(final Object o) {
        if (this == o) {
            return true;
        }
        if (!(o instanceof OrderRequestPaymentMethodModel)) {
            return false;
        }
        final OrderRequestPaymentMethodModel that = (OrderRequestPaymentMethodModel) o;
        final EqualsBuilder builder = new EqualsBuilder();
        builder.appendSuper(super.equals(o));
        builder.append(getType(), that.getType());
        return builder.build();
    }

    @Override
    public int hashCode() {
        final HashCodeBuilder builder = new HashCodeBuilder();
        builder.appendSuper(super.hashCode());
        builder.append(getType());
        return builder.build();
    }

    @Override
    public String toString() {
        final ToStringBuilder builder = new ToStringBuilder(this);
        builder.appendSuper(super.toString());
        builder.append("type", getType());
        return builder.build();
    }
}

redpajama_set_name: RedPajamaGithub


text:
ANSIBLE_METADATA = {
    'metadata_version': '1.1',
    'status': ['preview'],
    'supported_by': 'community'
}

DOCUMENTATION = '''
---
module: f5bigip_cm_failover_status
short_description: BIG-IP cm failover status module
description:
    - Display the failover status of the local device.
version_added: "2.4"
author:
    - "Eric Jacob (@erjac77)"
options:
requirements:
    - BIG-IP >= 12.0
    - ansible-common-f5
    - f5-sdk
'''

EXAMPLES = '''
- name: Gets the failover status of the device
  f5bigip_cm_failover_status:
    f5_hostname: 172.16.227.35
    f5_username: admin
    f5_password: admin
    f5_port: 443
  delegate_to: localhost
  register: result

- name: Displays the failover status of the device
  debug:
    msg: "Failover Status: {{ result.status }}"
'''

RETURN = '''
color:
    description: The color representing the failover status of the device
    returned: success
    type: string
    sample:
        - green
status:
    description: The failover status of the device
    returned: success
    type: string
    sample:
        - ACTIVE
        - STANDBY
summary:
    description: A summary message explaining the failover status of the device
    returned: success
    type: string
    sample:
        - 1/1 active
'''

from ansible.module_utils.basic import AnsibleModule
from ansible_common_f5.base import AnsibleF5Error
from ansible_common_f5.base import F5_PROVIDER_ARGS
from ansible_common_f5.bigip import F5BigIpUnnamedObject

class ModuleParams(object):
    @property
    def argument_spec(self):
        argument_spec = dict()
        argument_spec.update(F5_PROVIDER_ARGS)
        return argument_spec

    @property
    def supports_check_mode(self):
        return True

class F5BigIpCmFailoverStatus(F5BigIpUnnamedObject):
    def _set_crud_methods(self):
        self._methods = {
            'read': self._api.tm.cm.failover_status
        }

    def flush(self):
        result = dict(changed=False)

        try:
            failover_status = self._methods['read']
            failover_status.refresh()
            failover_status_stats = \
                failover_status.entries['https://localhost/mgmt/tm/cm/failover-status/0']['nestedStats']['entries']
        except Exception:
            raise AnsibleF5Error("Unable to retrieve the failover status of the device.")

        result.update(
            color=failover_status_stats['color']['description'],
            status=failover_status_stats['status']['description'],
            summary=failover_status_stats['summary']['description']
        )

        return result

def main():
    params = ModuleParams()
    module = AnsibleModule(argument_spec=params.argument_spec, supports_check_mode=params.supports_check_mode)

    try:
        obj = F5BigIpCmFailoverStatus(check_mode=module.check_mode, **module.params)
        result = obj.flush()
        module.exit_json(**result)
    except Exception as exc:
        module.fail_json(msg=str(exc))

if __name__ == '__main__':
    main()


text:
/**
 *
 *
 * @mixins Ext.device.purchases.Sencha
 *
 * @aside guide native_apis
 */
Ext.define('Ext.device.Purchases', {
    singleton: true,

    requires: [
        'Ext.device.purchases.Sencha'
    ],

    constructor: function() {
        return Ext.create('Ext.device.purchases.Sencha');
    }
});


text:
<?php

namespace RavelryApi\Tests\Functional;

class AppDataTest extends TestCase
{
    public function testBasicCrud()
    {
        $now = date('c');

        $result = $this->client->app->data->set([
            'test/sync/favorites' => $now,
        ]);

        $this->assertArrayHasKey('data', $result);

        $this->assertArrayHasKey('test/sync/favorites', $result['data']);
        $this->assertEquals($now, $result['data']['test/sync/favorites']);

        $result = $this->client->app->data->get([
            'keys' => [
                'test/sync/favorites',
            ],
        ]);

        $this->assertArrayHasKey('data', $result);

        $this->assertArrayHasKey('test/sync/favorites', $result['data']);
        $this->assertEquals($now, $result['data']['test/sync/favorites']);

        // @todo
        $this->markTestIncomplete('The app/data/delete call seems to be breaking with a 500 Internal Server Error');

        $result = $this->client->app->data->delete([
            'keys' => [
                'test/sync/favorites',
            ],
        ]);

        $this->assertArrayHasKey('data', $result);

        $this->assertArrayHasKey('test/sync/favorites', $result['data']);
        $this->assertEquals($now, $result['data']['test/sync/favorites']);

        $result = $this->client->app->data->get([
            'keys' => [
                'test/sync/favorites',
            ],
        ]);

        $this->assertArrayHasKey('data', $result);

        $this->assertArrayNotHasKey('test/sync/favorites', $result['data']);
    }
}


text:
/*
 * Sample/test code for running a user program.  You can use this for
 * reference when implementing the execv() system call. Remember though
 * that execv() needs to do more than this function does.
 */

#include <types.h>
#include <kern/errno.h>
#include <kern/fcntl.h>
#include <lib.h>
#include <proc.h>
#include <current.h>
#include <addrspace.h>
#include <vm.h>
#include <vfs.h>
#include <syscall.h>
#include <test.h>

/*
 * Load program "progname" and start running it in usermode.
 * Does not return except on error.
 *
 * Calls vfs_open on progname and thus may destroy it.
 */
int
runprogram(char *progname)
{
	struct addrspace *as;
	struct vnode *v;
	vaddr_t entrypoint, stackptr;
	int result;

	/* Open the file. */
	result = vfs_open(progname, O_RDONLY, 0, &v);
	if (result) {
		return result;
	}

	/* We should be a new process. */
	KASSERT(proc_getas() == NULL);

	/* Create a new address space. */
	as = as_create();
	if (as == NULL) {
		vfs_close(v);
		return ENOMEM;
	}

	/* Switch to it and activate it. */
	proc_setas(as);
	as_activate();

	/* Load the executable. */
	result = load_elf(v, &entrypoint);
	if (result) {
		/* p_addrspace will go away when curproc is destroyed */
		vfs_close(v);
		return result;
	}

	/* Done with the file now. */
	vfs_close(v);

	/* Define the user stack in the address space */
	result = as_define_stack(as, &stackptr);
	if (result) {
		/* p_addrspace will go away when curproc is destroyed */
		return result;
	}

	/* Warp to user mode. */
	enter_new_process(0 /*argc*/, NULL /*userspace addr of argv*/,
			  NULL /*userspace addr of environment*/,
			  stackptr, entrypoint);

	/* enter_new_process does not return. */
	panic("enter_new_process returned\n");
	return EINVAL;
}


text:
from django.conf import settings

from djczech.reconciliation.data.models import Cheque

from djzbar.settings import INFORMIX_EARL_TEST as INFORMIX_EARL
from djzbar.utils.informix import do_sql as do_esql

from sqlalchemy.orm import sessionmaker
from sqlalchemy import create_engine
from sqlalchemy import text

"""
engine = create_engine(
    'ibm_db_sa://{}:{}@{}:{}/{}:INFORMIXSERVER=wilson'.format(
        settings.INFORMIX_USERNAME,
        settings.INFORMIX_PASSWORD,
        settings.INFORMIX_HOST,
        settings.INFORMIX_PORT,
        settings.INFORMIX_DATABASE
    )
)

engine = create_engine('ibm_db_sa://{}:{}@/pyinformix'.format(
        settings.INFORMIX_USERNAME,
        settings.INFORMIX_PASSWORD,
    )
)
"""

sql = """
    SELECT
        *
    FROM
        ccreconjb_rec
    ORDER BY
        jbissue_date
"""

#Session = sessionmaker(bind=engine)
#session = Session()
# query
#objs = session.query(Cheque).all()

#objs = engine.execute(sql)

objs = do_esql(sql)
for o in objs:
    print o.jbchkno, o.jbimprt_date
    #print o

#session.close()

#session.query(Cheque).delete()
#session.commit()

#cid = 172207
#cheque = session.query(Cheque).filter_by(jbchkno=cid).first()

#print cheque

'''
sql = """
    SELECT
        jbaction, jbchkno, jbissue_date, jbstatus
    FROM
        ccreconjb_rec where jbaction=:jbaction
    """

objs = session.query("jbaction", "jbchkno", "jbissue_date", "jbstatus").\
        from_statement(text(sql)).\
        params(jbaction='X').all()
for o in objs:
    print o.jbaction, o.jbchkno, o.jbissue_date, o.jbstatus
    #print o
'''

"""
# does the same as do_sql() function
objs = session.execute(sql)
for o in objs:
    print o
"""

"""
seq = 1
for instance in session.query(Cheque):
    print seq, instance.jbchkno
    seq += 1
"""
#session.close()


text:
<?php
namespace Encuesta\DashboardBundle\Controller;

use Encuesta\ModeloBundle\Entity\Evento;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Security\Core\SecurityContext;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use Symfony\Component\HttpFoundation\Response;

class EventoController extends Controller
{
    public function listAction()
    {
        $em = $this->getDoctrine()->getManager();
        $list = $em->getRepository('ModeloBundle:Evento')->findAll();

        return $this->render('DashboardBundle:Evento:list.html.twig', array(
            'list' => $list,
            'idiomas' => $this->container->getParameter('idiomas'),
            'service_entity' => $this->get('dashboard.entity')
        ));
    }

    public function deleteAction()
    {
        $response = $this->get('dashboard.ajaxresponse');
        $em = $this->getDoctrine()->getManager();
        $translator = $this->get('translator');

        try {
            $obj = $em->getRepository('ModeloBundle:Evento')->find($this->getRequest()->get('id'));

            if(!$obj) {
                $response->setHttpCode(500);
                $response->setMessage($translator->trans('El evento que intenta eliminar no existe'));
            }
            else {
                $em->remove($obj);
                $em->flush();

                $response->setMessage($translator->trans('El evento se ha eliminado satisfactoriamente'));
                $response->setDataHolder(array('route' => $this->get('router')->generate('dashboard_evento')));
            }
        }
        catch(\Exception $e) {
            $response->setHttpCode(500);
            $response->setMessage($translator->trans('Lo sentimos, ha ocurrido un error'));
        }

        return new Response(json_encode($response->response()));
    }

    public function viewAction()
    {
        $request = $this->getRequest();
        $em = $this->getDoctrine()->getManager();

        $obj = $em->getRepository('ModeloBundle:Evento')->find($request->get('id'));
        if(!$obj)
            $this->createNotFoundException('No existe el evento que está intentando ver');

        return $this->render('DashboardBundle:Evento:view.html.twig', array(
            'idiomas' => $this->container->getParameter('idiomas'),
            'obj' => $obj,
            'i18n' => $em->getRepository('Gedmo\Translatable\Entity\Translation')->findTranslations($obj),
            'service_entity' => $this->get('dashboard.entity')
        ));
    }

    public function changeStateAction()
    {
        $translator = $this->get('translator');
        $em = $this->getDoctrine()->getManager();
        $peticion = $this->getRequest();

        $response = $this->get('dashboard.ajaxresponse');
        try {
            $obj = $em->getRepository('ModeloBundle:Evento')->find($peticion->get('id'));

            if(!$obj) {
                $response->setHttpCode(500);
                $response->setMessage($translator->trans('Está intentando modificar un evento que no existe'));
            }
            else {
                $obj->setActivo(!$obj->getActivo());
                $em->persist($obj);
                $em->flush();

                $response->setMessage($translator->trans('Se ha modificado el estado del evento correctamente'));
            }
        }
        catch(\Exception $e) {
            $response->setHttpCode(500);
            $response->setMessage($translator->trans('Lo sentimos, hubo un error'));
        }

        $sResponse = new Response(json_encode($response->response()));
        $sResponse->headers->set('Content-Type', 'application/json; charset=utf-8');

        return $sResponse;
    }
}


text:
package com.none.tom.simplerssreader.fragment;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.design.widget.TextInputEditText;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.ImageButton;

import com.none.tom.simplerssreader.R;
import com.none.tom.simplerssreader.activity.MainActivity;
import com.none.tom.simplerssreader.fragment.base.NonCancelableDialogFragment;
import com.none.tom.simplerssreader.utils.DialogFragmentUtils;
import com.none.tom.simplerssreader.utils.SoftInputUtils;
import com.none.tom.simplerssreader.utils.ThemeUtils;

public class FeedSubscriptionEditFragment extends NonCancelableDialogFragment {
    public static final String TAG = FeedSubscriptionEditFragment.class.getSimpleName();

    private int mPosition;
    private int mTitleLenght;
    private int mCategoryLength;

    private static FeedSubscriptionEditFragment sFeedSubscriptionEditFragment;

    @Override
    public int getType() {
        return NonCancelableDialogFragment.ALERT_DIALOG;
    }

    @Override
    public void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mPosition = getArguments().getInt(getGenericKey());
    }

    @SuppressLint("InflateParams")
    @Override
    public Dialog onCreateDialog(final Bundle savedInstanceState) {
        final Activity activity = getActivity();

        final View view = View.inflate(activity, R.layout.fragment_feed_subscription_edit, null);

        final TextInputEditText titleEditText =
                view.findViewById(R.id.FeedSubscriptionEditEditText);
        final TextInputEditText categoryEditText =
                view.findViewById(R.id.FeedSubscriptionEditCategoryEditText);

        final ImageButton categoryButton =
                view.findViewById(R.id.FeedSubscriptionEditCategoryImageButton);

        if (ThemeUtils.isDarkThemeSelected(activity)) {
            categoryButton.setImageResource(R.drawable.ic_arrow_drop_down_circle_white_24dp);
        }

        titleEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(final CharSequence text, final int i, final int i1,
                                          final int i2) {}

            @Override
            public void onTextChanged(final CharSequence text, final int i, final int i1,
                                      final int i2) {
                mTitleLenght = text.length();

                if (mTitleLenght > 0 && mCategoryLength > 0) {
                    DialogFragmentUtils.togglePositiveButtonVisibility(getDialog(), true);
                } else {
                    DialogFragmentUtils.togglePositiveButtonVisibility(getDialog(), false);
                }
            }

            @Override
            public void afterTextChanged(final Editable editable) {}
        });

        categoryEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(final CharSequence text, final int i, final int i1,
                                          final int i2) {}

            @Override
            public void onTextChanged(final CharSequence text, final int i, final int i1,
                                      final int i2) {
                mCategoryLength = text.length();

                if (mTitleLenght > 0 && mCategoryLength > 0) {
                    DialogFragmentUtils.togglePositiveButtonVisibility(getDialog(), true);
                } else {
                    DialogFragmentUtils.togglePositiveButtonVisibility(getDialog(), false);
                }
            }

            @Override
            public void afterTextChanged(final Editable editable) {}
        });

        categoryButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(final View view) {
                DialogFragmentUtils.showCategoriesPopupMenu(activity, categoryEditText, view);
            }
        });

        return new AlertDialog.Builder(activity)
                .setView(view)
                .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(final DialogInterface dialogInterface, final int i) {
                        SoftInputUtils.dismissSoftInput(getActivity(), titleEditText);

                        ((MainActivity) activity).editSubscription(
                                categoryEditText.getText().toString().trim(),
                                titleEditText.getText().toString().trim(), mPosition);
                    }
                })
                .setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(final DialogInterface dialogInterface, final int i) {
                        SoftInputUtils.dismissSoftInput(getActivity(), titleEditText);
                    }
                })
                .create();
    }

    @Override
    public void onStart() {
        super.onStart();

        DialogFragmentUtils.togglePositiveButtonVisibility(getDialog(), false);

        SoftInputUtils.forceShowSoftInput(getActivity(),
                getDialog().findViewById(R.id.FeedSubscriptionEditEditText));
    }

    public static FeedSubscriptionEditFragment getInstance(final int position) {
        if (sFeedSubscriptionEditFragment == null) {
            sFeedSubscriptionEditFragment = new FeedSubscriptionEditFragment();

            final Bundle args = new Bundle();
            args.putInt(getGenericKey(), position);

            sFeedSubscriptionEditFragment.setArguments(args);
        } else {
            final Bundle args = sFeedSubscriptionEditFragment.getArguments();

            args.clear();
            args.putInt(getGenericKey(), position);
        }

        return sFeedSubscriptionEditFragment;
    }
}


text:
.class final Landroid/net/wifi/aware/WifiAwareNetworkSpecifier$1;
.super Ljava/lang/Object;
.source "WifiAwareNetworkSpecifier.java"

# interfaces
.implements Landroid/os/Parcelable$Creator;

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Landroid/net/wifi/aware/WifiAwareNetworkSpecifier;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x8
    name = null
.end annotation

.annotation system Ldalvik/annotation/Signature;
    value = {
        "Ljava/lang/Object;",
        "Landroid/os/Parcelable$Creator",
        "<",
        "Landroid/net/wifi/aware/WifiAwareNetworkSpecifier;",
        ">;"
    }
.end annotation

# direct methods
.method constructor <init>()V
    .locals 0

    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    return-void
.end method

# virtual methods
.method public createFromParcel(Landroid/os/Parcel;)Landroid/net/wifi/aware/WifiAwareNetworkSpecifier;
    .locals 9

    new-instance v0, Landroid/net/wifi/aware/WifiAwareNetworkSpecifier;

    invoke-virtual {p1}, Landroid/os/Parcel;->readInt()I

    move-result v1

    invoke-virtual {p1}, Landroid/os/Parcel;->readInt()I

    move-result v2

    invoke-virtual {p1}, Landroid/os/Parcel;->readInt()I

    move-result v3

    invoke-virtual {p1}, Landroid/os/Parcel;->readInt()I

    move-result v4

    invoke-virtual {p1}, Landroid/os/Parcel;->readInt()I

    move-result v5

    invoke-virtual {p1}, Landroid/os/Parcel;->createByteArray()[B

    move-result-object v6

    invoke-virtual {p1}, Landroid/os/Parcel;->createByteArray()[B

    move-result-object v7

    invoke-virtual {p1}, Landroid/os/Parcel;->readString()Ljava/lang/String;

    move-result-object v8

    invoke-direct/range {v0 .. v8}, Landroid/net/wifi/aware/WifiAwareNetworkSpecifier;-><init>(IIIII[B[BLjava/lang/String;)V

    return-object v0
.end method

.method public bridge synthetic createFromParcel(Landroid/os/Parcel;)Ljava/lang/Object;
    .locals 1

    invoke-virtual {p0, p1}, Landroid/net/wifi/aware/WifiAwareNetworkSpecifier$1;->createFromParcel(Landroid/os/Parcel;)Landroid/net/wifi/aware/WifiAwareNetworkSpecifier;

    move-result-object v0

    return-object v0
.end method

.method public newArray(I)[Landroid/net/wifi/aware/WifiAwareNetworkSpecifier;
    .locals 1

    new-array v0, p1, [Landroid/net/wifi/aware/WifiAwareNetworkSpecifier;

    return-object v0
.end method

.method public bridge synthetic newArray(I)[Ljava/lang/Object;
    .locals 1

    invoke-virtual {p0, p1}, Landroid/net/wifi/aware/WifiAwareNetworkSpecifier$1;->newArray(I)[Landroid/net/wifi/aware/WifiAwareNetworkSpecifier;

    move-result-object v0

    return-object v0
.end method


text:
[![license][license-img]][github] [![web][web-img]][web] [![github][github-img]][github]

A modern HTTP web server index for Apache httpd, lighttpd, nginx and Cherokee.

## Important

* Do **not** install any files from the `src` folder, they need to be
  preprocessed to work correctly!
* Find a preprocessed package and detailed install instructions on the
  [project page][web].
* For bug reports and feature requests please use [issues][github-issues].

## Build

There are installation ready packages for the latest [releases][release] and
[dev builds][develop]. But to build **h5ai** yourself either `git clone` or
download the repository. From within the root folder run the following
commands to find a fresh zipball in folder `build` (tested on linux only,
requires [`node 6.0+`][node] to be installed).

~~~sh
> npm install
> npm run build
~~~

## License

The MIT License (MIT)

Copyright (c) 2016 Lars Jung (https://larsjung.de)

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

## References

**h5ai** profits from other projects, all of them licensed under the MIT license
too. Exceptions are some [Material Design icons][material-design-icons] (CC BY 4.0).

[web]: https://larsjung.de/h5ai/
[github]: https://github.com/lrsjng/h5ai
[github-issues]: https://github.com/lrsjng/h5ai/issues
[release]: https://release.larsjung.de/h5ai/
[develop]: https://release.larsjung.de/h5ai/develop/
[node]: https://nodejs.org
[material-design-icons]: https://github.com/google/material-design-icons

[license-img]: https://img.shields.io/badge/license-MIT-a0a060.svg?style=flat-square
[web-img]: https://img.shields.io/badge/web-larsjung.de/h5ai-a0a060.svg?style=flat-square
[github-img]: https://img.shields.io/badge/github-lrsjng/h5ai-a0a060.svg?style=flat-square


text:
{-# LANGUAGE OverloadedStrings, LambdaCase #-}

module Main where

import qualified Prelude as P
import Prelude hiding (readFile, putStrLn)

import qualified Data.Text as T
import Data.Attoparsec.Text (parseOnly)
import Data.Either.Utils (eitherToMonadError)
import Data.List.Split (splitOn)
import Data.Text.IO
import Text.PrettyPrint (render)

import qualified Control.Monad.Error as E
import qualified Control.Monad.Reader as R
import Control.Monad.Error (Error, ErrorT, liftIO)
import Control.Monad.Reader (Reader, ReaderT)
import Control.Monad

import Scheme.IR
import Scheme.PrettyPrint (simpleDoc)
import Scheme.Parser (programParser)
import Scheme.LLVM.Runtime (runtime)
import Scheme.LLVM.Compile
import Scheme.Simplify

import LLVM.ShowLLVM (showLLVM)
import Options.Applicative

import Tool.Repl
import Tool.Args

optionHandler = info (helper <*> options)
  (fullDesc <> header "Scheme.LLVM - a llvm based compiler for scheme")

main :: IO ()
main = do
  options <- execParser optionHandler
  result  <- runapp options application
  -- on success do nothing, otherwise
  -- print the error that occured.
  case result of
    Left error -> P.putStrLn error
    Right _    -> return ()

type App a = ReaderT Opts (ErrorT String IO) a

runapp :: Opts -> App a -> IO (Either String a)
runapp env app = E.runErrorT $ R.runReaderT app env

application :: App ()
application = R.asks _mode >>= \case
  ShowRuntime -> liftIO $ showLLVM runtime
  ASTRepl     -> liftIO startAstRepl
  SimpleRepl  -> liftIO startSimplerRepl
  SimpleRead  ->
    withFiles $ \fname -> do
      program <- getProgram fname
      let simple = simplify program
          simDoc = render $ simpleDoc simple
      liftIO $ P.putStrLn simDoc
  CompileRead ->
    withFiles $ \fname -> do
      program <- getProgram fname
      let simple  = simplify program
          mname   = T.pack . last . init $ splitOn "." fname
          lModule = compile mname simple
      liftIO $ showLLVM lModule

getProgram :: FilePath -> App Program
getProgram fname = do
  contents <- liftIO $ readFile fname
  eitherToMonadError $ parseOnly programParser contents

withFiles :: (FilePath -> App ()) -> App ()
withFiles action = do
  files <- R.asks _files
  forM_ files action


text:
package org.mifos.test.acceptance.framework.savings;

import org.mifos.test.acceptance.framework.AbstractPage;
import org.testng.Assert;

import com.thoughtworks.selenium.Selenium;

@SuppressWarnings("PMD.SystemPrintln")
public class TransactionHistoryPage extends AbstractPage {

    public final static String TABLE_ID = "trxnhistoryList";
    public final static String VOLUNTARY = "Voluntary";

    public TransactionHistoryPage(Selenium selenium) {
        super(selenium);
        verifyPage("viewsavingstrxnhistory");
    }

    public void verifyTableTypeAfterDeposit(int rowCount) {
        for (int i = 1; i <= rowCount; ++i) {
            String[] type = getType(i).split(" ");
            Assert.assertEquals(type[0], VOLUNTARY);
        }
    }

    public String getType(int row) {
        return selenium.getTable(TABLE_ID + "." + row + ".3");
    }
}


text:
"use strict";

const webpack = require("../../../../");

module.exports = {
	plugins: [
		new webpack.DefinePlugin({
			DEFINE_PATH: JSON.stringify("./a")
		})
	]
};


text:
package org.gradle.tooling.internal.protocol.events;

/**
 * DO NOT CHANGE THIS INTERFACE. It is part of the cross-version protocol.
 *
 * @since 2.5
 */
public interface InternalSuccessResult extends InternalOperationResult {
}


text:
namespace AngleSharp.Dom.Css
{
    using AngleSharp.Css;
    using AngleSharp.Parser.Css;
    using System;

    /// <summary>
    /// Represents a CSS rule.
    /// </summary>
    abstract class CssRule : ICssRule
    {
        #region Fields

        readonly CssRuleType _type;
        readonly CssParser _parser;

        ICssStyleSheet _ownerSheet;
        ICssRule _parentRule;

        #endregion

        #region ctor

        /// <summary>
        /// Creates a new CSS rule.
        /// </summary>
        internal CssRule(CssRuleType type, CssParser parser)
        {
            _type = type;
            _parser = parser;
        }

        #endregion

        #region Properties

        /// <summary>
        /// Gets the textual representation of the rule.
        /// </summary>
        public String CssText
        {
            get { return ToCss(); }
            set
            {
                var rule = _parser.ParseRule(value);

                if (rule == null)
                    throw new DomException(DomError.Syntax);
                else if (rule.Type != _type)
                    throw new DomException(DomError.InvalidModification);

                ReplaceWith(rule);
            }
        }

        /// <summary>
        /// Gets the containing rule, otherwise null.
        /// </summary>
        public ICssRule Parent
        {
            get { return _parentRule; }
            internal set { _parentRule = value; }
        }

        /// <summary>
        /// Gets the CSSStyleSheet object for the style sheet that contains this rule.
        /// </summary>
        public ICssStyleSheet Owner
        {
            get { return _ownerSheet; }
            internal set { _ownerSheet = value; }
        }

        /// <summary>
        /// Gets the type constant indicating the type of CSS rule.
        /// </summary>
        public CssRuleType Type
        {
            get { return _type; }
        }

        #endregion

        #region Internal Properties

        internal CssParser Parser
        {
            get { return _parser; }
        }

        #endregion

        #region Methods

        public String ToCss()
        {
            return ToCss(CssStyleFormatter.Instance);
        }

        public abstract String ToCss(IStyleFormatter formatter);

        #endregion

        #region Internal Methods

        /// <summary>
        /// Replaces the current object with the given rule.
        /// The types are equal.
        /// </summary>
        /// <param name="rule">The new rule.</param>
        protected abstract void ReplaceWith(ICssRule rule);

        #endregion
    }
}


text:
@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION

SET "NETFXTAG=-beta05"
IF "%ProgramFiles(x86)%" NEQ "" (
	SET "REFERENCEASSEMBLYROOT=%ProgramFiles(x86)%\Reference Assemblies"
) ELSE (
	SET "REFERENCEASSEMBLYROOT=%ProgramFiles%\Reference Assemblies"
)

CALL :Net35

FOR %%A IN (4.0.0,4.5.0,4.5.1,4.5.2,4.6.0,4.6.1,4.6.2) DO (
	SET DisplayName=net%%A
	SET DisplayName=!DisplayName:.=!
	IF "!DisplayName:~5,1!" EQU "0" (
		SET DisplayName=!DisplayName:~0,5!
	)
	SET DisplayVersion=v%%A
	IF "!DisplayVersion:~5,1!" EQU "0" (
		SET DisplayVersion=!DisplayVersion:~0,4!
	)

	SET "ROOT=%REFERENCEASSEMBLYROOT%\Microsoft\Framework\.NETFramework\!DisplayVersion!"

	IF NOT EXIST "!ROOT!" (
		ECHO .NET Framework reference assemblies were not found at !ROOT!.  Ensure the .NET Framework SDK is installed for this version and try again.
	) ELSE (
		ECHO Version %%A%NETFXTAG% - !DisplayName! - !DisplayVersion! - "!ROOT!"
		NuGet PACK "%~dp0CBT.DotNetFx.nuspec" -Properties "Version=%%A%NETFXTAG%;DisplayName=!DisplayName!;DisplayVersion=!DisplayVersion!;Root=!ROOT!" -NoPackageAnalysis -NoDefaultExcludes -O "%~dp0.."
	)
)

GOTO :EOF

:Net35
SET "ROOT=%REFERENCEASSEMBLYROOT%\Microsoft\Framework"
NuGet PACK "%~dp0CBT.DotNetFx.3.5.nuspec" -Properties "Version=3.5.0%NETFXTAG%;DisplayName=net35;DisplayVersion=v3.5;Root=%ROOT%" -NoPackageAnalysis -NoDefaultExcludes -O "%~dp0.."
IF ERRORLEVEL 1 EXIT /B 1


text:
console.log('Loading function kinesis-dumper.js');

exports.handler = function(event, context) {
    console.log(event);
    context.succeed(event);
};


text:
from cadnano.proxies.cnproxy import UndoCommand
from cadnano.strand import Strand
from cadnano.cntypes import (
    NucleicAcidPartT
)

class RefreshOligosCommand(UndoCommand):
    """RefreshOligosCommand is a post-processing step for AutoStaple.

    Normally when an xover is created, all strands in the 3' direction are
    assigned the oligo of the 5' strand. This becomes very expensive
    during autoStaple, because the Nth xover requires updating up to N-1
    strands.

    Hence, we disable oligo assignment during the xover creation step,
    and then do it all in one pass at the end with this command.

    This command is meant for non-undoable steps, like file-io.
    """

    def __init__(self, part: NucleicAcidPartT):
        super(RefreshOligosCommand, self).__init__("refresh oligos")
        self._part = part
    # end def

    def redo(self):
        visited = {}
        part = self._part
        for id_num in part.getIdNums():
            fwd_ss, rev_ss = part.getStrandSets(id_num)
            for strand in rev_ss:
                visited[strand] = False
            for strand in fwd_ss:
                visited[strand] = False

        fSetOligo = Strand.setOligo
        for strand in list(visited.keys()):
            if visited[strand]:
                continue
            visited[strand] = True
            start_oligo = strand.oligo()

            strand5gen = strand.generator5pStrand()
            # this gets the oligo and burns a strand in the generator
            strand5 = next(strand5gen)
            for strand5 in strand5gen:
                oligo5 = strand5.oligo()
                if oligo5 != start_oligo:
                    oligo5.removeFromPart(emit_signals=True)
                    fSetOligo(strand5, start_oligo, emit_signals=True)  # emits strandHasNewOligoSignal
                visited[strand5] = True
            # end for
            start_oligo.setStrand5p(strand5)
            # is it a loop?
            if strand.connection3p() == strand5:
                start_oligo._setLoop(True)
            else:
                strand3gen = strand.generator3pStrand()
                strand3 = next(strand3gen)   # burn one
                for strand3 in strand3gen:
                    oligo3 = strand3.oligo()
                    if oligo3 != start_oligo:
                        oligo3.removeFromPart(emit_signals=True)
                        fSetOligo(strand3, start_oligo, emit_signals=True)  # emits strandHasNewOligoSignal
                    visited[strand3] = True
                # end for
            start_oligo.refreshLength(emit_signals=True)
        # end for

        for strand in visited.keys():
            strand.strandConnectionChangedSignal.emit(strand)
    # end def

    def undo(self):
        """Doesn't reassign """
    # end def
# end class


text: LAST_STATUS=0 # Initialize status code by 0


text:
namespace NSass
{
	typedef void (__stdcall *FileAccessDelegate)(const char* path);

	class CallbackManager
	{
		private:
			FileAccessDelegate _fileAccessDelegate;

			CallbackManager();

			CallbackManager(CallbackManager const&);
			void operator=(CallbackManager const&);

		public:
			static CallbackManager& getInstance();

			void set_file_access_callback(FileAccessDelegate callBack);
			void unset_file_access_callback();
			void trigger_file_access_callback(const char* path);
	};
}


text:
"""
Classes to represent single and multiple shifts.
"""
import time, datetime

from result import *
from workgroup import Workgroups, Workgroup
from account import Accounts, Account
from shift import Shift

TIMEFMT = '%l:%M%P'

class Timeclock(Result):
    """Represents a single timeclock entry"""

    name = 'timeclock'
    name_plural = 'timeclocks'

    def __init__(self, session, seed=None, id=None):
        self.session = session
        self.loaded = False

        if seed:
            self.update(seed)

        if id:
            self['id'] = id
            self.load()

        if (not 'id' in self):
            self['id'] = self['account']

    def getData(self):
        result = self.session.apicall('timeclock.status',
            account = self['id']
            )
        return result['result']

    def time(self, show_end_time=False, timefmt=TIMEFMT):
        """Human-readable time display"""
        start_time = self.startTime()
        if 'clocked_out' in self and show_end_time:
            return '%s - %s' % (
                start_time.strftime(timefmt),
                self.endTime().strftime(timefmt),
                )
        if start_time.date() != datetime.date.today():
            return '%s' % (self.startTime().strftime(timefmt+" (%B %d, %Y)"),)

        return '%s' % (self.startTime().strftime(timefmt),)

    def startTime(self):
        """parse clock in time into standard python structure"""
        if 'clocked_in_local' in self:
            timeobj = datetime.datetime.strptime(
                self['clocked_in_local'], '%Y-%m-%dT%H:%M:%S')
        else:
            # Standard clockin specified in UTC time
            clockin_str = self['clocked_in']
            clockin_str = clockin_str.rstrip("Z")
            clockin_time = datetime.datetime.strptime(
                clockin_str, '%Y-%m-%dT%H:%M:%S')
            utctzdiff = datetime.datetime.utcnow() - datetime.datetime.now()
            timeobj = clockin_time - utctzdiff
        return timeobj

    def endTime(self):
        """parse clock out time into standard python structure"""
        if 'clocked_out_local' in self:
            timeobj = datetime.datetime.strptime(
                self['clocked_out_local'], '%Y-%m-%dT%H:%M:%S')
        else:
            # Standard clockin specified in UTC time
            clockout_str = self['clocked_out']
            clockout_str = clockin_str.rstrip("Z")
            clockout_time = datetime.datetime.strptime(
                clockout_str, '%Y-%m-%dT%H:%M:%S')
            utctzdiff = datetime.datetime.utcnow() - datetime.datetime.now()
            timeobj = clockout_time - utctzdiff
        return timeobj

    def clockedin(self):
        """Boolean test for checked in status"""
        if self.get('clocked_in', False) and not self.get('clocked_out', False):
            return True

        return False

    def clockIn(self, account=None, workgroup=None, shift=None):
        """Clock in the current timeclock object"""
        if (not account and 'account' in self):
            account = self['account']
        if (not workgroup and 'workgroup' in self):
            workgroup = self['workgroup']
        if (not shift and 'shift' in self):
            shift = self['shift']

        arglist = { 'account': account }

        if (workgroup):
            arglist['workgroup'] = workgroup

        if (shift):
            arglist['shift'] = shift

        result = self.session.apicall('timeclock.clockIn', **arglist)
        return result['result']

    def clockOut(self, account=None, workgroup=None, approve=True):
        """Clock out of the current timeclock object"""
        if (not workgroup and 'workgroup' in self):
            workgroup = self['workgroup']
        if (not account and 'account' in self):
            account = self['account']

        arglist = { 'account': account }

        if (workgroup):
            arglist['workgroup'] = workgroup

        result = self.session.apicall('timeclock.clockOut',
            account = account,
            workgroup = workgroup,
            approve = approve,
            )
        return result['result']

    def __cmp__(self, other):
        # use string comparison to optimize..
        delta = cmp(self.get('id',''), other.get('id',''))
        if delta:
            return delta

        delta = cmp(self.get('clocked_in',''), other.get('clocked_in',''))
        if delta:
            return delta

        delta = cmp(self.get('clocked_out',''), other.get('clocked_out',''))
        if delta:
            return delta

        delta = cmp(self.get('account',''), other.get('account', ''))
        if delta:
            return delta

        delta = cmp(self.get('workgroup',''), other.get('workgroup', ''))
        if delta:
            return delta

        delta = cmp(self.get('shift',''), other.get('shift', ''))
        if delta:
            return delta

        return delta

    def __ne__(self, other):
        return not (self == other)

    def __eq__(self, other):
        return (self['id'] == other['id'] and
                self['clocked_in'] == other['clocked_in'] and
                self.get('clocked_out') == other.get('clocked_out') and
                self['workgroup']['id'] == other['workgroup']['id'] and
                self['account']['id'] == other['account']['id'] and
                self['shift']['id'] == other['shift']['id'])

    def denormalizeReferenced(self, objects):
        """Denormalize, building lightweight versions of referenced data"""
        self.denormalizeBatch(objects, 'timezone')
        self.denormalizeBatch(objects, 'account', cls=Account)
        self.denormalizeBatch(objects, 'workgroup', cls=Workgroup)

    def denormalizeBatch(self, objects, key, obj_name=None, cls=None):
        if not obj_name:
            obj_name = key
        if not obj_name in objects:
            return

        if key in self and self[key]:
            obj = objects[obj_name][self[key]]
            if cls:
                # higher level object
                self[key] = cls(self.session, seed=obj)
            else:
                # simple dict
                self[key] = obj

class WhosOnTimeclocks(Results):
    """Represents a list of timeclocks"""
    child = Timeclock

    def getData(self, page={}):
        page['batch'] = self.batch
        result = self.session.apicall('timeclock.whosOn',
            extended=True, select=self.select, page=page)
        return result

    def storeBatch(self, obj):
        Results.storeBatch(self, obj)
        if 'referenced_objects' in obj and int(obj['count']) > 0:
            referenced_objs = obj['referenced_objects']

            # index objects by most likely unique key
            objidx = dict()
            for referenced_name, referenced_list in referenced_objs.iteritems():
                for referenced_obj in referenced_list:
                    if 'id' in referenced_obj:
                        objidx.setdefault(referenced_name, dict())[referenced_obj['id']] = referenced_obj
                    elif 'name' in referenced_obj:
                        objidx.setdefault(referenced_name, dict())[referenced_obj['name']] = referenced_obj
            start = obj['page']['this']['start'] - 1
            for idx in range(start, start + len(obj[self.child.name_plural])):
                self.storage[idx].denormalizeReferenced(objidx)


text:
package io.gatling.core

import scala.annotation.tailrec

import io.gatling.commons.validation._
import io.gatling.core.session.el._

package object session {
  type Expression[T] = Session => Validation[T]

  val TrueExpressionSuccess: Expression[Boolean] = true.expressionSuccess
  val EmptyStringExpressionSuccess: Expression[String] = "".expressionSuccess

  final case class StaticValueExpression[T](value: T) extends Expression[T] {
    private val valueV = value.success

    override def apply(session: Session): Validation[T] = valueV
  }

  implicit class ExpressionSuccessWrapper[T](val value: T) extends AnyVal {
    def expressionSuccess: Expression[T] = StaticValueExpression(value)
  }

  implicit class ExpressionFailureWrapper(val message: String) extends AnyVal {
    def expressionFailure: Expression[Nothing] = {
      val valueS = message.failure
      _ => valueS
    }
  }

  implicit class RichExpression[T](val expression: Expression[T]) extends AnyVal {
    def map[U](f: T => U): Expression[U] = expression(_).map(f)
    def safe: Expression[T] = session => safely()(expression(session))
  }

  def resolveOptionalExpression[T](expression: Option[Expression[T]], session: Session): Validation[Option[T]] = expression match {
    case Some(exp) => exp(session).map(Some.apply)
    case _         => Validation.NoneSuccess
  }

  def expressionSeq2SeqExpression[X](iterable: Iterable[(Expression[X], Expression[X])]): Expression[Seq[(String, X)]] = {
    @tailrec
    def resolveRec(session: Session, entries: Iterator[(Expression[X], Expression[X])], acc: List[(String, X)]): Validation[Seq[(String, X)]] =
      if (entries.isEmpty) {
        acc.reverse.success
      } else {
        val (elKey, elValue) = entries.next()

        elKey(session) match {
          case Success(key) =>
            elValue(session) match {
              case Success(value)   => resolveRec(session, entries, key.toString -> value :: acc)
              case failure: Failure => failure
            }
          case failure: Failure => failure
        }
      }

    resolveRec(_, iterable.iterator, Nil)
  }

  def tupleSeq2SeqExpression(seq: Seq[(String, Any)]): Expression[Seq[(String, Any)]] = {
    val expressionSequence: Seq[(Expression[String], Expression[Any])] = seq.map { case (key, value) =>
      val keyExpression = key.el[String]
      val valueExpression = value match {
        case s: String => s.el[Any]
        case v         => v.expressionSuccess
      }

      keyExpression -> valueExpression
    }

    expressionSeq2SeqExpression(expressionSequence)
  }
}


text:
using System;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using Azure;
using Azure.Analytics.Synapse.Artifacts.Models;
using Azure.Core;
using Azure.Core.Pipeline;

namespace Azure.Analytics.Synapse.Artifacts
{
    internal partial class SqlPoolsRestClient
    {
        private Uri endpoint;
        private ClientDiagnostics _clientDiagnostics;
        private HttpPipeline _pipeline;

        /// <summary> Initializes a new instance of SqlPoolsRestClient. </summary>
        /// <param name="clientDiagnostics"> The handler for diagnostic messaging in the client. </param>
        /// <param name="pipeline"> The HTTP pipeline for sending and receiving REST requests and responses. </param>
        /// <param name="endpoint"> The workspace development endpoint, for example https://myworkspace.dev.azuresynapse.net. </param>
        /// <exception cref="ArgumentNullException"> <paramref name="endpoint"/> is null. </exception>
        public SqlPoolsRestClient(ClientDiagnostics clientDiagnostics, HttpPipeline pipeline, Uri endpoint)
        {
            this.endpoint = endpoint ?? throw new ArgumentNullException(nameof(endpoint));
            _clientDiagnostics = clientDiagnostics;
            _pipeline = pipeline;
        }

        internal HttpMessage CreateListRequest()
        {
            var message = _pipeline.CreateMessage();
            var request = message.Request;
            request.Method = RequestMethod.Get;
            var uri = new RawRequestUriBuilder();
            uri.Reset(endpoint);
            uri.AppendPath("/sqlPools", false);
            uri.AppendQuery("api-version", "2020-12-01", true);
            request.Uri = uri;
            request.Headers.Add("Accept", "application/json");
            return message;
        }

        /// <summary> List Sql Pools. </summary>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        public async Task<Response<SqlPoolInfoListResult>> ListAsync(CancellationToken cancellationToken = default)
        {
            using var message = CreateListRequest();
            await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);
            switch (message.Response.Status)
            {
                case 200:
                    {
                        SqlPoolInfoListResult value = default;
                        using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false);
                        value = SqlPoolInfoListResult.DeserializeSqlPoolInfoListResult(document.RootElement);
                        return Response.FromValue(value, message.Response);
                    }
                default:
                    throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false);
            }
        }

        /// <summary> List Sql Pools. </summary>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        public Response<SqlPoolInfoListResult> List(CancellationToken cancellationToken = default)
        {
            using var message = CreateListRequest();
            _pipeline.Send(message, cancellationToken);
            switch (message.Response.Status)
            {
                case 200:
                    {
                        SqlPoolInfoListResult value = default;
                        using var document = JsonDocument.Parse(message.Response.ContentStream);
                        value = SqlPoolInfoListResult.DeserializeSqlPoolInfoListResult(document.RootElement);
                        return Response.FromValue(value, message.Response);
                    }
                default:
                    throw _clientDiagnostics.CreateRequestFailedException(message.Response);
            }
        }

        internal HttpMessage CreateGetRequest(string sqlPoolName)
        {
            var message = _pipeline.CreateMessage();
            var request = message.Request;
            request.Method = RequestMethod.Get;
            var uri = new RawRequestUriBuilder();
            uri.Reset(endpoint);
            uri.AppendPath("/sqlPools/", false);
            uri.AppendPath(sqlPoolName, true);
            uri.AppendQuery("api-version", "2020-12-01", true);
            request.Uri = uri;
            request.Headers.Add("Accept", "application/json");
            return message;
        }

        /// <summary> Get Sql Pool. </summary>
        /// <param name="sqlPoolName"> The Sql Pool name. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        /// <exception cref="ArgumentNullException"> <paramref name="sqlPoolName"/> is null. </exception>
        public async Task<Response<SqlPool>> GetAsync(string sqlPoolName, CancellationToken cancellationToken = default)
        {
            if (sqlPoolName == null)
            {
                throw new ArgumentNullException(nameof(sqlPoolName));
            }

            using var message = CreateGetRequest(sqlPoolName);
            await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);
            switch (message.Response.Status)
            {
                case 200:
                    {
                        SqlPool value = default;
                        using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false);
                        value = SqlPool.DeserializeSqlPool(document.RootElement);
                        return Response.FromValue(value, message.Response);
                    }
                default:
                    throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false);
            }
        }

        /// <summary> Get Sql Pool. </summary>
        /// <param name="sqlPoolName"> The Sql Pool name. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        /// <exception cref="ArgumentNullException"> <paramref name="sqlPoolName"/> is null. </exception>
        public Response<SqlPool> Get(string sqlPoolName, CancellationToken cancellationToken = default)
        {
            if (sqlPoolName == null)
            {
                throw new ArgumentNullException(nameof(sqlPoolName));
            }

            using var message = CreateGetRequest(sqlPoolName);
            _pipeline.Send(message, cancellationToken);
            switch (message.Response.Status)
            {
                case 200:
                    {
                        SqlPool value = default;
                        using var document = JsonDocument.Parse(message.Response.ContentStream);
                        value = SqlPool.DeserializeSqlPool(document.RootElement);
                        return Response.FromValue(value, message.Response);
                    }
                default:
                    throw _clientDiagnostics.CreateRequestFailedException(message.Response);
            }
        }
    }
}


text:
require 'rubygems'
gem 'minitest', '>= 2.5.1', '< 5.0.0'
require 'minitest/autorun'

require File.expand_path('../test_nxapi', __FILE__)
require File.expand_path('../test_logger', __FILE__)


text:
require_relative '../tests/image/image_spec.rb'
require_relative '../tests/networkcontroller/networkcontroller_spec.rb'
require_relative '../tests/orchestrationapi/orchestrationapi_spec.rb'
require_relative '../tests/telemetryserver/telemetryserver_spec.rb'
require_relative '../tests/volumecontroller/volumecontroller_spec.rb'
require_relative '../tests/controller/controller_spec.rb'


text:
package markov_clustering.blockmultiplication;

import java.io.IOException;

import org.apache.hadoop.io.DoubleWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;

public class MatrixMultiplicationReducer extends Reducer<Text, Text, Text, DoubleWritable> {
	@Override
	public void reduce(Text key, Iterable<Text> values, Context context) throws IOException, InterruptedException {
		int totSize = context.getConfiguration().getInt("size", 10000);
		int splits = context.getConfiguration().getInt("splits", 10);
		int matrixSize = totSize/splits;
		double[][] matrix_A = new double[matrixSize][matrixSize];
		double[][] matrix_B = new double[matrixSize][matrixSize];
		//Memorize all values...
		for(Text v: values) {
			String[] fields = v.toString().split(",");
			int x = Integer.parseInt(fields[1]);
			int y = Integer.parseInt(fields[2]);
			double value = Double.parseDouble(fields[3]);
			if (fields[0].equals("A"))
				matrix_A[x][y] = value;
			else //Matrix B is memorized by column since it is accessed this way, in order to minimize cache faults
				matrix_B[y][x] = value;
		}

		for (int i = 0; i < matrixSize; i++) {
			for(int j = 0; j < matrixSize; j++) {
				double sum = 0;
				for (int k = 0; k < matrixSize; k++) {
					sum += matrix_A[i][k]*matrix_B[j][k];
				}
				if(sum > 0) context.write(new Text(i+","+j), new DoubleWritable(sum));
			}
		}

	}

}


text:
package org.openfact.events.admin;

import java.util.Date;
import java.util.List;

public interface AdminEventQuery {

    /**
     * Search by resource organization
     *
     * @param organizationId organization id
     * @return Associated AdminEventQuery for method chaining
     */
    AdminEventQuery organization(String organizationId);

    /**
     * Search by authentication organization
     *
     * @param organizationId organization name
     * @return Associated AdminEventQuery for method chaining
     */
    AdminEventQuery authOrganization(String organizationId);

    /**
     * Search by authenticated user
     *
     * @param userId user email
     * @return Associated AdminEventQuery for method chaining
     */
    AdminEventQuery authUser(String userId);

    /**
     * Search by request ip address
     *
     * @param ipAddress
     * @return Associated AdminEventQuery for method chaining
     */
    AdminEventQuery authIpAddress(String ipAddress);

    /**
     * Search by operation type
     *
     * @param operations
     * @return this for method chaining
     */
    AdminEventQuery operation(OperationType... operations);

    /**
     * Search by {@link ResourceType}.
     *
     * @param resourceTypes
     * @return this for method chaining
     */
    AdminEventQuery resourceType(String... resourceTypes);

    /**
     * Search by resource path. Supports wildcards * and **. For example:
     *

     *
*/master - matches 'organizations/master'

     *
**/00d4b16f - matches 'organizations/master/clients/00d4b16f'

     *
organizations/master/** - matches anything under 'organizations/master'

     *

     *
     * @param resourcePath
     * @return this for method chaining
     */
    AdminEventQuery resourcePath(String resourcePath);

    /**
     * Search by events after the specified time
     *
     * @param fromTime from date
     * @return this for method chaining
     */
    AdminEventQuery fromTime(Date fromTime);

    /**
     * Search by events before the specified time
     *
     * @param toTime to date
     * @return this for method chaining
     */
    AdminEventQuery toTime(Date toTime);

    /**
     * Used for pagination
     *
     * @param first first result to return
     * @return this for method chaining
     */
    AdminEventQuery firstResult(int first);

    /**
     * Use for pagination
     *
     * @param max the maximum results to return
     * @return this for method chaining
     */
    AdminEventQuery maxResults(int max);

    /**
     * Executes the createQuery and returns the results
     *
     * @return
     */
    List<AdminEvent> getResultList();
}


text:
package com.net2plan.gui.plugins.networkDesign;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

import com.net2plan.interfaces.networkDesign.Demand;
import com.net2plan.interfaces.networkDesign.Link;
import com.net2plan.interfaces.networkDesign.NetPlan;
import com.net2plan.interfaces.networkDesign.NetworkElement;
import com.net2plan.internal.Constants.NetworkElementType;
import com.net2plan.utils.Pair;

/**
 * @author Jorge San Emeterio Villalain
 * @date 28/03/17
 */
public class ElementSelection
{
    private NetworkElementType elementType;

    private final List<NetworkElement> networkElementList;
    private final List<Pair<Demand, Link>> forwardingRuleList;

    public ElementSelection()
    {
        this.elementType = null;
        this.networkElementList = Collections.unmodifiableList(Collections.emptyList());
        this.forwardingRuleList = Collections.unmodifiableList(Collections.emptyList());
    }

    public ElementSelection (final NetworkElementType elementType, final Collection<?> networkElementsOrForwRules)
    {
    	assert elementType != null;
    	this.elementType = elementType;
        this.networkElementList = new ArrayList<> ();
        this.forwardingRuleList = new ArrayList<> ();
    	for (Object ne : networkElementsOrForwRules)
    	{
    		if (ne instanceof NetworkElement)
    		{
    			final NetworkElement e = (NetworkElement) ne;
    			if (e.getNeType() == elementType) this.networkElementList.add(e);
    		}
    		else if (ne instanceof Pair)
    		{
    			if (elementType != NetworkElementType.FORWARDING_RULE) continue;
    			final Pair e = (Pair) ne;
    			if (e.getFirst() instanceof Demand && e.getSecond() instanceof Link)
    				this.forwardingRuleList.add(e);
    			else throw new RuntimeException ();
    		}
    		else throw new RuntimeException ();
    	}
    }

    public boolean isEmpty()
    {
        return (networkElementList.isEmpty() && forwardingRuleList.isEmpty()) || elementType == null;
    }

    public List<? extends NetworkElement> getNetworkElements()
    {
        return Collections.unmodifiableList(networkElementList);
    }

    public List<Pair<Demand, Link>> getForwardingRules()
    {
        return Collections.unmodifiableList(forwardingRuleList);
    }

    public NetworkElementType getElementType()
    {
        return elementType;
    }

    public ElementSelection invertSelection()
    {
        final ElementSelection elementSelection;
        // Check all elements belong to the same NetPlan
        NetPlan netPlan = null;
        for (NetworkElement networkElement : networkElementList)
        {
            if (netPlan == null) netPlan = networkElement.getNetPlan();
            else if (netPlan != networkElement.getNetPlan()) return null;
        }
        if (netPlan == null) return null;

        final List<NetworkElement> invertedElements;
        switch (elementType)
        {
            case NODE:
                invertedElements = new ArrayList<>(netPlan.getNodes());
                invertedElements.removeAll(getNetworkElements());
                elementSelection = new ElementSelection(elementType, invertedElements);
                break;
            case LINK:
                invertedElements = new ArrayList<>(netPlan.getLinks());
                invertedElements.removeAll(getNetworkElements());
                elementSelection = new ElementSelection(elementType, invertedElements);
                break;
            case DEMAND:
                invertedElements = new ArrayList<>(netPlan.getDemands());
                invertedElements.removeAll(getNetworkElements());
                elementSelection = new ElementSelection(elementType, invertedElements);
                break;
            case MULTICAST_DEMAND:
                invertedElements = new ArrayList<>(netPlan.getMulticastDemands());
                invertedElements.removeAll(getNetworkElements());
                elementSelection = new ElementSelection(elementType, invertedElements);
                break;
            case ROUTE:
                invertedElements = new ArrayList<>(netPlan.getRoutes());
                invertedElements.removeAll(getNetworkElements());
                elementSelection = new ElementSelection(elementType, invertedElements);
                break;
            case MULTICAST_TREE:
                invertedElements = new ArrayList<>(netPlan.getMulticastTrees());
                invertedElements.removeAll(getNetworkElements());
                elementSelection = new ElementSelection(elementType, invertedElements);
                break;
            case RESOURCE:
                invertedElements = new ArrayList<>(netPlan.getResources());
                invertedElements.removeAll(getNetworkElements());
                elementSelection = new ElementSelection(elementType, invertedElements);
                break;
            case SRG:
                invertedElements = new ArrayList<>(netPlan.getSRGs());
                invertedElements.removeAll(getNetworkElements());
                elementSelection = new ElementSelection(elementType, invertedElements);
                break;
            case FORWARDING_RULE:
                final List<Pair<Demand, Link>> forwardingRules = new ArrayList<>(netPlan.getForwardingRules().keySet());
                forwardingRules.removeAll(getForwardingRules());
                elementSelection = new ElementSelection(NetworkElementType.FORWARDING_RULE , forwardingRules);
                break;
            default:
                return null;
        }

        return elementSelection;
    }
}


text:
#include <gtest/gtest.h>
#include <thrift/lib/cpp2/test/gen-cpp2/TestService.h>
#include <thrift/lib/cpp2/server/ThriftServer.h>
#include <thrift/lib/cpp2/async/HeaderClientChannel.h>
#include <thrift/lib/cpp2/async/RequestChannel.h>

#include <thrift/lib/cpp/util/ScopedServerThread.h>
#include <thrift/lib/cpp/async/TEventBase.h>
#include <thrift/lib/cpp/async/TAsyncSocket.h>

#include <thrift/lib/cpp2/async/StubSaslClient.h>
#include <thrift/lib/cpp2/async/StubSaslServer.h>

#include <boost/cast.hpp>
#include <boost/lexical_cast.hpp>
#include <memory>

using namespace apache::thrift;
using namespace apache::thrift::test::cpp2;
using namespace apache::thrift::util;
using namespace apache::thrift::async;

class TestInterface : public TestServiceSvIf {
  void sendResponse(std::string& _return, int64_t size) {
    if (size >= 0) {
      usleep(size * 1000);
    }

    _return = "test";
  }

  void noResponse(int64_t size) {
    usleep(size * 1000);
  }
};

std::shared_ptr<ThriftServer> getServer() {
  std::shared_ptr<ThriftServer> server = std::make_shared<ThriftServer>();
  server->setPort(0);
  server->setInterface(std::unique_ptr<TestInterface>(new TestInterface));
  server->setIdleTimeout(std::chrono::milliseconds(10));
  return server;
}

class CloseChecker : public CloseCallback {
 public:
  CloseChecker() : closed_(false) {}
  void channelClosed() {
    closed_ = true;
  }
  bool getClosed() {
    return closed_;
  }
 private:
  bool closed_;
};

TEST(ThriftServer, IdleTimeoutTest) {
  ScopedServerThread sst(getServer());

  TEventBase base;
  std::shared_ptr<TAsyncSocket> socket(
    TAsyncSocket::newSocket(&base, *sst.getAddress()));

  auto client_channel = HeaderClientChannel::newChannel(socket);
  CloseChecker checker;
  client_channel->setCloseCallback(&checker);
  base.runAfterDelay([&base](){
      base.terminateLoopSoon();
    }, 100);
  base.loopForever();
  EXPECT_TRUE(checker.getClosed());
  client_channel->setCloseCallback(nullptr);
}

TEST(ThriftServer, NoIdleTimeoutWhileWorkingTest) {
  ScopedServerThread sst(getServer());

  TEventBase base;
  std::shared_ptr<TAsyncSocket> socket(
    TAsyncSocket::newSocket(&base, *sst.getAddress()));

  auto client_channel = HeaderClientChannel::newChannel(socket);
  auto client_channelp = client_channel.get();
  CloseChecker checker;

  client_channel->setCloseCallback(&checker);
  TestServiceAsyncClient client(std::move(client_channel));
  std::string ret;
  client.sync_sendResponse(ret, 20);

  client.sync_sendResponse(ret, 20);

  EXPECT_FALSE(checker.getClosed());
  client_channelp->setCloseCallback(nullptr);
}

TEST(ThriftServer, IdleTimeoutAfterTest) {
  ScopedServerThread sst(getServer());

  TEventBase base;

  std::shared_ptr<TAsyncSocket> socket(
    TAsyncSocket::newSocket(&base, *sst.getAddress()));

  auto client_channel = HeaderClientChannel::newChannel(socket);
  auto client_channelp = client_channel.get();
  CloseChecker checker;

  client_channel->setCloseCallback(&checker);
  TestServiceAsyncClient client(std::move(client_channel));
  std::string ret;
  client.sync_sendResponse(ret, 20);

  EXPECT_FALSE(checker.getClosed());

  base.runAfterDelay([&base](){
      base.terminateLoopSoon();
    }, 200);
  base.loopForever();
  EXPECT_TRUE(checker.getClosed());
  client_channelp->setCloseCallback(nullptr);
}

int main(int argc, char** argv) {
  testing::InitGoogleTest(&argc, argv);
  google::InitGoogleLogging(argv[0]);
  google::ParseCommandLineFlags(&argc, &argv, true);

  return RUN_ALL_TESTS();
}


text:
namespace FubarDev.FtpServer.FileSystem.Error
{
    /// <summary>
    /// Represents an error condition the underlying file system wants to communicate to the client.
    /// </summary>
    public abstract class FileSystemException : System.Exception
    {
        /// <summary>
        ///  Initializes a new instance of the <see cref="FileSystemException"/> class.
        /// </summary>
        protected FileSystemException()
        {
        }

        /// <summary>
        ///  Initializes a new instance of the <see cref="FileSystemException"/> class.
        /// </summary>
        /// <param name="message">The error message.</param>
        protected FileSystemException(string message)
            : base(message)
        {
        }

        /// <summary>
        ///  Initializes a new instance of the <see cref="FileSystemException"/> class.
        /// </summary>
        /// <param name="message">The error message.</param>
        /// <param name="innerException">The underlying exception.</param>
        protected FileSystemException(string message, System.Exception innerException)
            : base(message, innerException)
        {
        }

        /// <summary>
        /// Gets the FTP error code.
        /// </summary>
        public abstract int FtpErrorCode { get; }

        /// <summary>
        /// Gets a human-readable generic error description.
        /// </summary>
        public abstract string FtpErrorName { get; }
    }
}


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using QRCoder;

namespace Cluedo
{
    public partial class Form1 : Form
    {
        QRCodeGenerator qrGenerator = new QRCodeGenerator();
        private Button myButton;

        // Declare array with 24 elements of type BoardSquare, these represent the board squares (not rooms)
        // The BoardSquare buttons will be created dynamically
        BoardSquare[] squares = new BoardSquare[24];

        String[] names = { "Chris", "Jeni", "Craig", "Warren", "Melissa", "Ethan", "Megan", "Keira", "Grace" };
        Suspect[] suspects = new Suspect[9];

        // xPos and yPos arrays representing the X and Y coordinates of the buttons
        int[] xPos = { 0, 75, 150, 225, 300, 375, 450, 450, 450, 450, 450, 450, 450, 375, 300, 225, 150, 75, 0, 0, 0, 0, 0, 0};
        int[] yPos = { 0, 0, 0, 0, 0, 0, 0, 75, 150, 225, 300, 375, 450, 450, 450, 450, 450, 450, 450, 375, 300, 225, 150, 75};
        int xOffset = 250; // Offset from left hand side
        int yOffset = 100;

        /*
         * Initialise the main form
         */
        public Form1()
        {
            InitializeComponent();

//            button7.Click += new System.EventHandler(this.myEventHandler);
//            myButton = createButton("Dynamic Button", 100, 100, 100, 100);
//            myButton.Click += new System.EventHandler(this.myEventHandler);
//            this.Controls.Add(myButton);
//            Console.WriteLine("Button should be added");

            drawBoard(); // Draw board components

            Room room = new Room("Computer Room");

            for (int t = 0; t < names.Length; t++)
            {
                suspects[t] = new Suspect(names[t], t);

                if (!room.AddVisitor(suspects[t]))
                {
                    Console.WriteLine("Visitor Already in Room: " + suspects[t]);
                }

            }

            room.ListVisitors();

            suspects[7].room = 0;

            if (!room.AddVisitor(suspects[7]))
            {
                Console.WriteLine("ERROR WRONG VISITOR");
            }

            int j = 0;
            // TRY DELETING ALL VISITORS
            while (room.Count() > 0)
            {

                room.RemoveVisitor(suspects[j++]);
            }

            Console.WriteLine("Room is empty");
            room.ListVisitors();

        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        // Draw components onto the board
        private void drawBoard()
        {
            textBox1.Text = "Hello";

            // Board squares are actually form buttons
            // For loop to instantiate and draw squares onto the board
            // Dynamically create buttons, give them an event handler and place on the board
            for(int t = 0; t < squares.Length; t++) {
                squares[t] = new BoardSquare(); // Construct the board square
                squares[t].square = createButton("Square " + t, 75, 75, xPos[t] + xOffset, yPos[t] + yOffset); // Add form button to square
                squares[t].square.Click += new System.EventHandler(this.myEventHandler); // Add event handler to the square
                this.Controls.Add(squares[t].square); // Add the square to the board
            }

            // Draw rooms onto the board

            this.Controls.Add(new RoomPanel("Computer Lab").panel);

        }

        // Deal Cards
        private void dealCards()
        {

        }

        // Initialise the players
        private void iniPlayers()
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {
//            Console.WriteLine("Hello There");
//            MessageBox.Show("Hello Again", "MyMessage", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Exclamation); // A message box with Yes, No and Cancel buttons

            if (textBox1.Text == "")
                return;

            QRCodeGenerator.QRCode qrCode = qrGenerator.CreateQrCode(textBox1.Text, QRCodeGenerator.ECCLevel.Q);
            pictureBox1.BackgroundImage = qrCode.GetGraphic(20); // Generate QR code and store in picture box

            button1.Text = textBox1.Text;
            label2.Text = textBox1.Text;
        }

        private void myEventHandler(object sender, EventArgs e)
        {
            textBox1.Text = "Using my event handler";

        }

        // This method creates a  button dynamically, according to the parameters recieved
        // It does not place the button on a form or give it an even listener
        private Button createButton(String label, int width, int height, int topLeft, int topRight)
        {
            Button button = new Button();   // Instantiate button

            button.Text = label;            // Assign label

            button.Width = width;           // Set the width
            button.Height = height;         // Set the height
            button.Location = new Point(topLeft, topRight); // Set the button location

            return button; // Return the button
        }

    }
}


text:
Neste repositório contém traduções de:

 * Core
 * Libraries
 * Helpers

## Contribuição
Fique totalmente a vontade para contribuir e ajudar em novas traduções e correções.

## Licença

[MIT License](http://dhyegofernando.mit-license.org/) © Dhyego Fernando


text:
namespace DylanSharp.Core.Expressions
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;

    public class AssignExpression : IExpression
    {
        private string name;
        private IExpression expression;

        public AssignExpression(string name, IExpression expression)
        {
            this.name = name;
            this.expression = expression;
        }

        public string Name { get { return this.name; } }

        public IExpression Expression { get { return this.expression; } }

        public object Evaluate(Context context)
        {
            var value = this.expression.Evaluate(context);

            if (!context.HasValue(this.name))
                throw new InvalidOperationException(string.Format("Undefined variable '{0}'", this.name));

            context.SetValue(this.name, value);
            return value;
        }
    }
}


text:
package com.ourcode.models.process;

import com.ourcode.models.input.OCShipment;

import java.util.ArrayList;

/**
 * Created by LEOLEOl on 5/4/2017.
 */
public class SimpleBreakdown implements ShipmentBreakdown{
    private double minWeightOfVehicles;
    private double minVolumeOfVehicles;
    private OCShipment shipment;

    public SimpleBreakdown(double minWeight, double minVolume, OCShipment shipment) {
        this.minWeightOfVehicles = minWeight; // min của maxWeight của đội xe
        this.minVolumeOfVehicles = minVolume; // min của maxVoluem của đội xe
        this.shipment = new OCShipment(shipment);
    }

    @Override
    public ArrayList<OCShipment> breakDownShipmentsByWeight() {
        double minWeight = minWeightOfVehicles;
        int num = ((int) Math.ceil(shipment.getWeight() / minWeight));

        ArrayList<OCShipment> ret = new ArrayList<>();
        int i = 0;
        OCShipment shipmentUnit;
        while (i++ < num - 1) {
            shipmentUnit = new OCShipment(shipment.getShipCode() +  "---" + i,
                shipment.getPickupServiceTime() / num, shipment.getDeliveryServiceTime() / num,
                minWeight, shipment.getVolume() / num,
                shipment.getPickupLocationCode(), shipment.getDeliveryLocationCode(),
                shipment.getPickupTimeWindows(), shipment.getDeliveryTimeWindows(), shipment.getPriority());
            ret.add(shipmentUnit);
        }
        shipmentUnit = new OCShipment(shipment.getShipCode() +  "---" + i,
            shipment.getPickupServiceTime() / num, shipment.getDeliveryServiceTime() / num,
            shipment.getWeight() - minWeight * (num-1), shipment.getVolume() / num,
            shipment.getPickupLocationCode(), shipment.getDeliveryLocationCode(),
            shipment.getPickupTimeWindows(), shipment.getDeliveryTimeWindows(), shipment.getPriority());
        ret.add(shipmentUnit);
        return ret;
    }

    @Override
    public ArrayList<OCShipment> breakDownShipmentsByVolume() {
        double minVolume = minVolumeOfVehicles;
        int num = ((int) Math.ceil(shipment.getVolume() / minVolume));

        ArrayList<OCShipment> ret = new ArrayList<>();
        int i = 0;
        OCShipment shipmentUnit;
        while (i++ < num - 1) {
            shipmentUnit = new OCShipment(shipment.getShipCode() + "---" + i,
                shipment.getPickupServiceTime() / num, shipment.getDeliveryServiceTime() / num,
                shipment.getWeight() / num, minVolume,
                shipment.getPickupLocationCode(), shipment.getDeliveryLocationCode(),
                shipment.getPickupTimeWindows(), shipment.getDeliveryTimeWindows(), shipment.getPriority());
            ret.add(shipmentUnit);
        }
        shipmentUnit = new OCShipment(shipment.getShipCode() + "---" + i,
            shipment.getPickupServiceTime() / num, shipment.getDeliveryServiceTime() / num,
            shipment.getWeight() / num, shipment.getVolume() - minVolume * (num-1),
            shipment.getPickupLocationCode(), shipment.getDeliveryLocationCode(),
            shipment.getPickupTimeWindows(), shipment.getDeliveryTimeWindows(), shipment.getPriority());
        ret.add(shipmentUnit);
        return ret;
    }
}


text:
<!DOCTYPE html>

    <meta charset='utf-8'>
    <title>
      Land Registry Open Data – page not found
    </title>
    <link rel="stylesheet" href="/stylesheets/landing.css" type="text/css">
    <link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" type="text/css">
    <link href="/images/favicon.ico" rel="shortcut icon" type="image/vnd.microsoft.icon" />
    <meta name="Description" content="Linked Open Data resources from the Land Registry"/>
    <meta name="Monitoring" content="Confirming site availability." />

                Land Registry Linked Open Data

                  beta

                    House Price Index

                    Price Paid Data

                    SPARQL query

            Application error

            We're very sorry, but the request you just made resulted in an internal error in the application.
            If this problem persists, please use one of the contact methods below to report the problem
            to us, so that we can resolve it and help you get the data you require.

            Who to contact

            If you are unable to access the data please fill in our contact form.

            For general transaction data enquiries email DRO@landregistry.gov.uk

            For general price paid data enquiries contact commercial.services@landregistry.gov.uk.

          Support links

            © Crown copyright 2014–2016

            Personal Information Charter

            Land Registry Public Data

            All content is available under the Open Government Licence v3.0 except where otherwise stated


text:
import {vec4} from '../../global';
import {Tw2CurveKey, Tw2Curve} from './Tw2Curve';

/**
 * Tw2ColorKey
 *
 * @property {vec4} value
 * @property {vec4} left
 * @property {vec4} right
 * @property {number} interpolation
 * @class
 */
export class Tw2ColorKey extends Tw2CurveKey
{

    value = vec4.create();
    left = vec4.create();
    right = vec4.create();
    interpolation = 0;

}

/**
 * Tw2ColorCurve
 *
 * @property {number} start
 * @property {vec4} currentValue
 * @property {number} extrapolation
 * @property {Array.<Tw2ColorKey>} keys
 * @property {number} _currentKey
 * @property {number} length
 * @class
 */
export class Tw2ColorCurve extends Tw2Curve
{

    start = 0;
    value = vec4.create();
    extrapolation = 0;
    keys = [];
    _currentKey = 1;
    length = 0;

    /**
     * Sorts the curve's keys
     */
    Sort()
    {
        Tw2Curve.Sort(this);
    }

    /**
     * Gets the curve's length
     * @returns {number}
     */
    GetLength()
    {
        return this.length;
    }

    /**
     * Updates the current value at the given time
     * @param {number} time
     */
    UpdateValue(time)
    {
        this.GetValueAt(time, this.value);
    }

    /**
     * Gets a value at a specific time
     * @param {number} time
     * @param {vec4} value
     * @returns {vec4} value
     */
    GetValueAt(time, value)
    {
        if (this.length === 0)
        {
            return vec4.copy(value, this.value);
        }

        const
            firstKey = this.keys[0],
            lastKey = this.keys[this.keys.length - 1];

        if (time >= lastKey.time)
        {
            switch (this.extrapolation)
            {
                case Tw2ColorCurve.Extrapolation.NONE:
                    return vec4.copy(value, this.value);

                case Tw2ColorCurve.Extrapolation.CONSTANT:
                    return vec4.copy(value, lastKey.value);

                case Tw2ColorCurve.Extrapolation.GRADIENT:
                    return vec4.scaleAndAdd(value, lastKey.value, lastKey.right, time - lastKey.time);

                default:
                    time = time % lastKey.time;
            }
        }
        else if (time < 0 || time < firstKey.time)
        {
            switch (this.extrapolation)
            {
                case Tw2ColorCurve.Extrapolation.NONE:
                    return vec4.copy(value, this.value);

                case Tw2ColorCurve.Extrapolation.GRADIENT:
                    return vec4.scaleAndAdd(value, firstKey.value, firstKey.left, time * this.length - lastKey.time);

                default:
                    return vec4.copy(value, firstKey.value);
            }
        }

        let ck = this.keys[this._currentKey],
            ck_1 = this.keys[this._currentKey - 1];

        while ((time >= ck.time) || (time < ck_1.time))
        {
            if (time < ck_1.time) this._currentKey = 0;
            this._currentKey++;
            ck = this.keys[this._currentKey];
            ck_1 = this.keys[this._currentKey - 1];
        }

        const nt = (time - ck_1.time) / (ck.time - ck_1.time);

        switch (ck_1.interpolation)
        {
            case Tw2ColorCurve.Interpolation.CONSTANT:
                return vec4.copy(value, ck_1.value);

            default:
                value[0] = ck_1.value[0] * (1 - nt) + ck.value[0] * nt;
                value[1] = ck_1.value[1] * (1 - nt) + ck.value[1] * nt;
                value[2] = ck_1.value[2] * (1 - nt) + ck.value[2] * nt;
                value[3] = ck_1.value[3] * (1 - nt) + ck.value[3] * nt;
                return value;
        }
    }

    /**
     * The curve's key dimension
     * @type {number}
     */
    static inputDimension = 4;

    /**
     * The curve's dimension
     * @type {number}
     */
    static ouputDimension = 4;

    /**
     * The curve's current value property
     * @type {string}
     */
    static valueProperty = 'value';

    /**
     * The curve's type
     * @type {number}
     */
    static curveType = Tw2Curve.Type.CURVE;

    /**
     * The curve's key constructor
     * @type {Tw2ColorKey}
     */
    static Key = Tw2ColorKey;

    /**
     * Extrapolation types
     * @type {{NONE: number, CONSTANT: number, GRADIENT: number, CYCLE: number}}
     */
    static Extrapolation = {
        NONE: 0,
        CONSTANT: 1,
        GRADIENT: 2,
        CYCLE: 3
    };

    /**
     * Interpolation types
     * @type {{NONE: number, CONSTANT: number, LINEAR: number}}
     */
    static Interpolation = {
        NONE: 0,
        CONSTANT: 1,
        LINEAR: 2
    };

}


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

namespace NetCoreForce.Client.Models
{
    public class SObjectFieldMetadata
    {
        [JsonProperty(PropertyName = "autoNumber")]
        public bool AutoNumber { get; set; }

        [JsonProperty(PropertyName = "calculated")]
        public bool Calculated { get; set; }

        [JsonProperty(PropertyName = "createable")]
        public bool Creatable { get; set; }

        [JsonProperty(PropertyName = "custom")]
        public bool Custom { get; set; }

        [JsonProperty(PropertyName = "defaultValue")]
        public string DefaultValue { get; set; }

        [JsonProperty(PropertyName = "externalId")]
        public string ExternalId { get; set; }

        [JsonProperty(PropertyName = "htmlFormatted")]
        public bool HtmlFormatted { get; set; }

        [JsonProperty(PropertyName = "inlineHelpText")]
        public string InlineHelpText { get; set; }

        [JsonProperty(PropertyName = "label")]
        public string Label { get; set; }

        [JsonProperty(PropertyName = "length")]
        public int Length { get; set; }

        [JsonProperty(PropertyName = "name")]
        public string Name { get; set; }

        [JsonProperty(PropertyName = "nillable")]
        public bool Nillable { get; set; }

        [JsonProperty(PropertyName = "picklistValues")]
        public List<PickListValue> PicklistValues { get; set; }

        [JsonProperty(PropertyName = "referenceTo")]
        public List<string> ReferenceTo { get; set; }

        [JsonProperty(PropertyName = "relationshipName")]
        public string RelationshipName { get; set; }

        [JsonProperty(PropertyName = "type")]
        public string Type { get; set; }

        [JsonProperty(PropertyName = "unique")]
        public bool Unique { get; set; }

        [JsonProperty(PropertyName = "updateable")]
        public bool Updateable { get; set; }
    }
}


text:
<?php

namespace DataStream\Configuration;

/**
* Contains functions to be executed when a property is set
*/
class Configuration extends DefaultConfiguration
{

  /**
  * @var string The directory in which every file is located
  */
  private $directory;

  function __construct($directory)
  {
    $this->directory = $directory . DIRECTORY_SEPARATOR;
  }

  /**
  * Checks if the dataLocation provided is valid (i.e. files exist)
  */
  public function onDataLocationSet($dataLocation)
  {
    if(is_array($dataLocation)) {
      $dataLocation = array_map(function($path) {
        return $this->directory . $path;
      }, $dataLocation);

      foreach($dataLocation as $location) {
        if(!file_exists($location)) {
          throw new \Exception('Could not find file ' . $location);
        }
      }

    }else {
      $dataLocation = $this->directory . $dataLocation;

      if(!file_exists($dataLocation)) {
        throw new \Exception('Could not find file ' . $dataLocation);
      }

    }

    return $dataLocation;
  }
}


text:
import { expect } from 'chai';
import { AsyncQueue } from '../../../src/util/async_queue';
import { getLogLevel, LogLevel, setLogLevel } from '../../../src/util/log';
import { AnyJs } from '../../../src/util/misc';
import { Deferred, Rejecter, Resolver } from '../../../src/util/promise';

describe('AsyncQueue', () => {
  it('schedules ops in right order', () => {
    const queue = new AsyncQueue();
    const results: string[] = [];

    function pushResult(result: string): void {
      results.push(result);
    }

    const op1 = queue.schedule(() => {
      return defer(() => 'Hello')
        .then((result: string) => {
          return defer(() => result + ' world!');
        })
        .then(pushResult);
    });

    const op2 = queue.schedule(() => {
      return defer(() => 'Bye bye.').then(pushResult);
    });

    const op4 = new Deferred<void>();
    const op3 = queue.schedule(() => {
      queue.schedule(() => {
        return Promise.resolve('Bye for good.')
          .then(pushResult)
          .then(op4.resolve);
      });

      return Promise.resolve('Welcome back.').then(pushResult);
    });

    return Promise.all([op1, op2, op3])
      .then(() => {
        expect(results[0]).to.deep.equal('Hello world!');
        expect(results[1]).to.deep.equal('Bye bye.');
        expect(results[2]).to.deep.equal('Welcome back.');
        return op4.promise;
      })
      .then(() => {
        expect(results[3]).to.deep.equal('Bye for good.');
      });
  });

  it('handles failures', () => {
    const queue = new AsyncQueue();
    const expected = new Error('Firestore Test Simulated Error');

    // Disable logging for this test to avoid the assertion being logged
    const oldLogLevel = getLogLevel();
    setLogLevel(LogLevel.SILENT);

    // Schedule a failing operation and make sure it's handled correctly.
    const op1Promise = queue
      .schedule(() => {
        // This promise represents something that is rejected
        return defer(() => {
          throw expected;
        });
      })
      .then(
        () => {
          expect.fail('expected op1 to fail');
        },
        (err: AnyJs) => {
          expect(err).to.equal(expected);
        }
      )
      .then(() => {
        expect(queue.failure).to.equal(expected);
      });

    // Schedule a second failing operation (before the first one has actually
    // executed and failed). It should not be run.
    const op2Promise = queue
      .schedule(() => {
        return defer(() => {
          expect.fail('op2 should not be executed.');
        });
      })
      .then(
        () => {
          expect.fail('expected op2 to fail');
        },
        (err: AnyJs) => {
          // should be the original failure still.
          expect(err).to.equal(expected);
          expect(queue.failure).to.equal(expected);
        }
      );

    return Promise.all([op1Promise, op2Promise]).then(() => {
      // Once the queue is failed, trying to queue new operations will
      // synchronously throw with "already failed" error.
      const dummyOp = () => Promise.reject('dummyOp should not be run');
      expect(() => {
        queue.schedule(dummyOp);
      }).to.throw(/already failed:.*Simulated Error/);

      // Finally, restore log level.
      setLogLevel(oldLogLevel);
    });
  });
});

function defer<T>(op: () => T): Promise<T> {
  return new Promise((resolve: Resolver<T>, reject: Rejecter) => {
    setTimeout(() => {
      try {
        resolve(op());
      } catch (e) {
        reject(e);
      }
    }, 0);
  });
}