text:
package org.sakaiproject.jsf.util;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * This source file collects the dependencies of the Sakai tag library
 * on the JSF implementation into one place.
 * This is where JSF tags, renderers, and components that extend the
 * Sun JSF implementation (or the MyFaces implementation) live.
 * To switch between Sun RI vs. MyFaces, just comment/uncomment
 * the appropriate block of inner classes and recompile.
 */
public class JSFDepends
{
    private static final Log logger = LogFactory.getLog(JSFDepends.class);

	  /** Sun JSF RI dependent classes */
	  public static class CommandButtonTag extends com.sun.faces.taglib.html_basic.CommandButtonTag {}
	  public static class InputTextTag extends com.sun.faces.taglib.html_basic.InputTextTag {}
	  public static class OutputTextTag extends com.sun.faces.taglib.html_basic.OutputTextTag {}
	  public static class PanelGridTag extends com.sun.faces.taglib.html_basic.PanelGridTag {}
	  public static class DataTableTag extends com.sun.faces.taglib.html_basic.DataTableTag {}
	  public static class MessagesTag extends com.sun.faces.taglib.html_basic.MessagesTag {}
	  public static class ColumnTag extends com.sun.faces.taglib.html_basic.ColumnTag {}

	  public static class ButtonRenderer extends com.sun.faces.renderkit.html_basic.ButtonRenderer {}
	  public static class CommandLinkRenderer extends com.sun.faces.renderkit.html_basic.CommandLinkRenderer {}

}


text:
CloudHole API is an in-memory RESTful API server.

You can deploy a live copy of this application to Heroku with the button below.

[![Deploy](https://www.herokucdn.com/deploy/button.png)](https://heroku.com/deploy?template=https://github.com/scakemyer/cloudhole-api)

redpajama_set_name: RedPajamaGithub


text:
package org.traccar.api.resource;

import org.traccar.Context;
import org.traccar.api.BaseResource;
import org.traccar.model.Group;

import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.sql.SQLException;
import java.util.Collection;

@Path("groups")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class GroupResource extends BaseResource {

    @GET
    public Collection<Group> get(
            @QueryParam("all") boolean all, @QueryParam("userId") long userId) throws SQLException {
        if (all) {
            if (Context.getPermissionsManager().isAdmin(getUserId())) {
                return Context.getDeviceManager().getAllGroups();
            } else {
                Context.getPermissionsManager().checkManager(getUserId());
                return Context.getDeviceManager().getManagedGroups(getUserId());
            }
        } else {
            if (userId == 0) {
                userId = getUserId();
            }
            Context.getPermissionsManager().checkUser(getUserId(), userId);
            return Context.getDeviceManager().getGroups(userId);
        }
    }

    @POST
    public Response add(Group entity) throws SQLException {
        Context.getPermissionsManager().checkReadonly(getUserId());
        Context.getDeviceManager().addGroup(entity);
        Context.getDataManager().linkGroup(getUserId(), entity.getId());
        Context.getPermissionsManager().refreshPermissions();
        if (Context.getGeofenceManager() != null) {
            Context.getGeofenceManager().refresh();
        }
        return Response.ok(entity).build();
    }

    @Path("{id}")
    @PUT
    public Response update(Group entity) throws SQLException {
        Context.getPermissionsManager().checkReadonly(getUserId());
        Context.getPermissionsManager().checkGroup(getUserId(), entity.getId());
        Context.getDeviceManager().updateGroup(entity);
        if (Context.getGeofenceManager() != null) {
            Context.getGeofenceManager().refresh();
        }
        return Response.ok(entity).build();
    }

    @Path("{id}")
    @DELETE
    public Response remove(@PathParam("id") long id) throws SQLException {
        Context.getPermissionsManager().checkReadonly(getUserId());
        Context.getPermissionsManager().checkGroup(getUserId(), id);
        Context.getDeviceManager().removeGroup(id);
        Context.getPermissionsManager().refreshPermissions();
        if (Context.getGeofenceManager() != null) {
            Context.getGeofenceManager().refresh();
        }
        return Response.noContent().build();
    }

}


text:
package org.hcm.jfbench.hr;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class BigSorting {
	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		int n = in.nextInt();
		List<String> unsortedInts = new ArrayList<>(n);
		for(int unsorted_i=0; unsorted_i < n; unsorted_i++){
			 unsortedInts.add(in.next());
		}
		// your code goes here
		unsortedInts.sort((o1, o2) -> o1.length() != o2.length() ? o1.length() - o2.length() : new BigInteger(o1).compareTo(new BigInteger(o2)));

		for (int i=0; i<n; i++) {
			System.out.println(unsortedInts.get(i));
		}
	}
}


text:
from __future__ import absolute_import, unicode_literals
import uuid
from .celery import app
import pika
import base64
import json
import os
from os import path as op
import cv2
import numpy as np
import pika
from facelib.monitor.FaceHandle import FaceDetector
from fdfs_client.client import *
import time
import pymysql

parameters = pika.URLParameters(
    'amqp://guest:guest@172.28.184.84:5672/%2F?connection_attempts=3&heartbeat_interval=3600')

@app.task
def detectface(queuename):
    connection = pika.BlockingConnection(parameters)
    channel = connection.channel()
    channel.queue_declare(queue= queuename, durable=False, exclusive=True, auto_delete=True)
    channel.queue_bind(queue= queuename, exchange="check", routing_key='stream.normal')

    while True:
        method_frame, header_frame, body = channel.basic_get(queue= queuename, no_ack=True)
        channel.queue_purge(queue=queuename)
        print("detect is ok")
        if (body == None):
            print("No body")
            continue
        else:
            print("body detected")
            data = json.loads(s=body)
            frame_body = base64.b64decode(data["body"])
            frame_array = np.fromstring(frame_body, dtype=np.uint8).reshape(data["shape"])
            frame_body = frame_array
            facehandle = FaceDetector().process_frame_with_detect(frame_body)

            if facehandle == None:
               print("no face")
               continue

            print("face detected")
            ret, jpeg = cv2.imencode('.jpg', frame_body)
            jpegstring = jpeg.tostring()

            r = post("1212",123,"aaa",jpegstring,"jpg")

    channel.close()
    connection.close()

# 提交新增
def post(message_id, camera_id,shape ,file,img_type):
    mysql_conn = pymysql.connect(host='172.28.189.101', port=3306, user='root',
                                      passwd='P@ssword0', db='facerecognize', charset='utf8')

    fileDir = os.path.dirname(os.path.realpath(__file__))
    configDir = os.path.join(fileDir, '..', 'server/configs/fdfsclient.conf')
    client = Fdfs_client(configDir)

    # 时间格式化为2017-06-30 14:59:51
    create_time = str(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()))
    img_time = str(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()))

    is_handled= False
    handled_result = ""

    # 首先存储文件,成功后再insert
    # file_metas = self.get_argument('file_metas')
    # file_metas = self.request.files['faceChecked']
    # img_type = self.get_argument('img_type')
    # 上传至文件服务器
    # rec = self.upload(file_metas[0]['body'], img_type)
    print("face upload")
    rec = client.upload_by_buffer(file, img_type)
    if rec['Status'] == 'Upload successed.':
        img_path = rec['Remote file_id']

    print(rec)

    # insert
    cur = mysql_conn.cursor(cursor=pymysql.cursors.DictCursor)
    sql = "insert into facerecognize.face_checked VALUES  \
          (uuid(), '%s', '%s', '%s',%d, %s, '%s', %d,'%s',%d,'%s')" % \
          (img_path, img_type,shape,camera_id, message_id, img_time, is_handled,handled_result, 0, create_time)
    # print sql
    print("face message save")
    cur.execute(sql)
    mysql_conn.commit()
    cur.close()
    mysql_conn.close()
    return {
         'message': 'ok'
    }


text:
#ifndef _PROC_H
#define _PROC_H

int mount_proc(const char *root_path);

#endif /* ! _PROC_H */


text:
package cloud.orbit.concurrent;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * Created by joeh on 2017-06-27.
 */
public class MessageDigestFactory
{
    private final String algorithm;
    private final MessageDigest digestPrototype;
    private final boolean supportsClone;

    public MessageDigestFactory(final String algorithm)
    {
        this.algorithm = algorithm;
        this.digestPrototype = createJDKDigest(algorithm);
        this.supportsClone = supportsCloning(digestPrototype);
    }

    public MessageDigest newDigest()
    {
        if(supportsClone)
        {
            try
            {
                return (MessageDigest) digestPrototype.clone();
            }
            catch(CloneNotSupportedException e)
            {
                // Eat it and fall through
            }
        }

        return createJDKDigest(algorithm);
    }

    private static boolean supportsCloning(MessageDigest messageDigest)
    {
        try
        {
            messageDigest.clone();
            return true;
        }
        catch (CloneNotSupportedException e)
        {
            return false;
        }
    }

    private static MessageDigest createJDKDigest(final String algorithm)
    {
        try
        {
            return MessageDigest.getInstance(algorithm);
        }
        catch(NoSuchAlgorithmException ex)
        {
            throw new IllegalArgumentException(ex);
        }
    }
}


text:
package bammerbom.ultimatecore.sponge.modules.unknowncommand;

import bammerbom.ultimatecore.sponge.UltimateCore;
import bammerbom.ultimatecore.sponge.api.config.defaultconfigs.module.ModuleConfig;
import bammerbom.ultimatecore.sponge.api.module.Module;
import bammerbom.ultimatecore.sponge.modules.unknowncommand.listeners.UnknowncommandListener;
import org.spongepowered.api.Sponge;
import org.spongepowered.api.event.game.state.GameInitializationEvent;
import org.spongepowered.api.event.game.state.GamePostInitializationEvent;
import org.spongepowered.api.event.game.state.GameStoppingEvent;
import org.spongepowered.api.text.Text;

import java.util.Optional;

public class UnknowncommandModule implements Module {
    @Override
    public String getIdentifier() {
        return "unknowncommand";
    }

    @Override
    public Text getDescription() {
        return Text.of("Allows you to change the message send to a player when a command is not found.");
    }

    @Override
    public Optional<ModuleConfig> getConfig() {
        return Optional.empty();
    }

    @Override
    public void onRegister() {

    }

    @Override
    public void onInit(GameInitializationEvent event) {
        Sponge.getEventManager().registerListeners(UltimateCore.get(), new UnknowncommandListener());
    }

    @Override
    public void onPostInit(GamePostInitializationEvent event) {

    }

    @Override
    public void onStop(GameStoppingEvent event) {

    }
}


text:
package net.ontopia.presto.jaxrs;

import net.ontopia.presto.spi.PrestoField;
import net.ontopia.presto.spi.PrestoTopic;
import net.ontopia.presto.spi.utils.PrestoContext;
import net.ontopia.presto.spi.utils.PrestoContextField;

import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

public class PathParserTest extends AbstractPrestoTest  {

    private TestEditorResource resource;
    private Presto session;

    @Before
    public void setUp() {
        String databaseId = "path-parser";
        createProviders(databaseId, "path-parser.data.json");
        this.resource = new TestEditorResource(schemaProvider, dataProvider);
        this.session = resource.createPresto(databaseId, false);
    }

    @Test
    public void testGetContextField() {
        PrestoContextField contextField = PathParser.getContextField(session, "o:root$pinfo$children$o:child1$cinfo$grandchildren");

        PrestoContext context = contextField.getContext();
        PrestoTopic topic = context.getTopic();
        Assert.assertEquals(topic.getId(), "o:child1");

        PrestoField field = contextField.getField();
        Assert.assertEquals(field.getId(), "grandchildren");
    }

    @Test
    public void testGetTopicByPathRoot() {
        PrestoContext topic = PathParser.getTopicByPath(session, "_", "o:root", "pinfo");
        Assert.assertEquals(topic.getTopicId(), "o:root");
    }

    @Test
    public void testGetTopicByPathChild() {
        PrestoContext topic = PathParser.getTopicByPath(session, "o:root$pinfo$children", "o:child1", "cinfo");
        Assert.assertEquals(topic.getTopicId(), "o:child1");
    }

    @Test
    public void testGetTopicByPathChildDirect() {
        PrestoContext topic = PathParser.getTopicByPath(session, "_", "o:child1", "cinfo");
        Assert.assertEquals(topic.getTopicId(), "o:child1");
    }

    @Test
    public void testGetTopicByPathGrandchild() {
        PrestoContext topic = PathParser.getTopicByPath(session, "o:root$pinfo$children$o:child1$cinfo$grandchildren", "o:grandchild1", "ginfo");
        Assert.assertEquals(topic.getTopicId(), "o:grandchild1");
    }

    @Test
    public void testGetTopicByPathGrandchildViaChild() {
        PrestoContext topic = PathParser.getTopicByPath(session, "o:child1$cinfo$grandchildren", "o:grandchild1", "ginfo");
        Assert.assertEquals(topic.getTopicId(), "o:grandchild1");
    }

    @Test
    public void testGetInlineTopicPath() {
        String inPath = "o:root$pinfo$children$o:child1$cinfo$grandchildren";
        PrestoContextField contextField = PathParser.getContextField(session, inPath);
        PrestoContext context = contextField.getContext();
        PrestoField field = contextField.getField();
        String outPath = PathParser.getInlineTopicPath(context, field);
        Assert.assertEquals(outPath, inPath);
    }

}


text:
layout: page
title: Morrison Family Reunion
date: 2016-05-24
author: Frank Bonilla
tags: weekly links, java
status: published
summary: Curabitur diam quam, condimentum eget.
banner: images/banner/leisure-02.jpg
booking:
  startDate: 09/07/2016
  endDate: 09/12/2016
  ctyhocn: BMCNMHX
  groupCode: MFR
published: true
---
Donec auctor ac sem eget egestas. Vivamus ultricies tortor nec sem elementum ultrices. Integer purus risus, tempor in dignissim ac, euismod eget quam. Morbi ac ante ac orci egestas congue. Aenean fringilla sit amet lectus at eleifend. Cras euismod mattis velit. Suspendisse est leo, porta at nunc in, sodales venenatis dolor. Nunc elementum nec tortor sit amet mollis. Nulla euismod risus sed laoreet feugiat. Sed vehicula maximus nunc. Nullam pretium efficitur leo, id gravida lectus. Suspendisse mi nulla, bibendum sit amet felis id, mollis posuere elit.

* Fusce ut augue sit amet tortor vestibulum suscipit
* Aenean maximus ipsum at leo malesuada hendrerit.

Nullam dignissim tempus laoreet. Aliquam malesuada velit eu vulputate dapibus. Proin molestie massa aliquam ligula aliquam, in pulvinar mi pretium. In et tempor orci. Sed commodo, leo ac pulvinar scelerisque, ligula turpis pharetra libero, id pulvinar diam nisi id lorem. Nunc tempus magna gravida odio sollicitudin viverra vitae eget nisi. Proin cursus porta elit, non ultricies nisi venenatis et. Pellentesque eget urna ligula. Etiam vehicula velit at erat vehicula imperdiet. Vivamus interdum tempus lacinia.


text:
"""Unit tests for FC Zone Manager."""

import mock

from jacket.storage import exception
from jacket.storage import test
from jacket.storage.volume import configuration as conf
from jacket.storage.zonemanager.drivers import fc_zone_driver
from jacket.storage.zonemanager import fc_zone_manager

fabric_name = 'BRCD_FAB_3'
init_target_map = {'10008c7cff523b01': ['20240002ac000a50']}
conn_info = {
    'driver_volume_type': 'fibre_channel',
    'data': {
        'target_discovered': True,
        'target_lun': 1,
        'target_wwn': '20240002ac000a50',
        'initiator_target_map': {
            '10008c7cff523b01': ['20240002ac000a50']
        }
    }
}
fabric_map = {'BRCD_FAB_3': ['20240002ac000a50']}
target_list = ['20240002ac000a50']

class TestFCZoneManager(test.TestCase):

    @mock.patch('oslo_config.cfg._is_opt_registered', return_value=False)
    def setUp(self, opt_mock):
        super(TestFCZoneManager, self).setUp()
        config = conf.Configuration(None)
        config.fc_fabric_names = fabric_name

        def fake_build_driver(self):
            self.driver = mock.Mock(fc_zone_driver.FCZoneDriver)

        self.stubs.Set(fc_zone_manager.ZoneManager, '_build_driver',
                       fake_build_driver)

        self.zm = fc_zone_manager.ZoneManager(configuration=config)
        self.configuration = conf.Configuration(None)
        self.configuration.fc_fabric_names = fabric_name
        self.driver = mock.Mock(fc_zone_driver.FCZoneDriver)

    def __init__(self, *args, **kwargs):
        super(TestFCZoneManager, self).__init__(*args, **kwargs)

    @mock.patch('oslo_config.cfg._is_opt_registered', return_value=False)
    def test_add_connection(self, opt_mock):
        with mock.patch.object(self.zm.driver, 'add_connection')\
                as add_connection_mock:
            self.zm.driver.get_san_context.return_value = fabric_map
            self.zm.add_connection(conn_info)
            self.zm.driver.get_san_context.assert_called_once_with(target_list)
            add_connection_mock.assert_called_once_with(fabric_name,
                                                        init_target_map,
                                                        None,
                                                        None)

    @mock.patch('oslo_config.cfg._is_opt_registered', return_value=False)
    def test_add_connection_error(self, opt_mock):
        with mock.patch.object(self.zm.driver, 'add_connection')\
                as add_connection_mock:
            add_connection_mock.side_effect = exception.FCZoneDriverException
            self.assertRaises(exception.ZoneManagerException,
                              self.zm.add_connection, conn_info)

    @mock.patch('oslo_config.cfg._is_opt_registered', return_value=False)
    def test_delete_connection(self, opt_mock):
        with mock.patch.object(self.zm.driver, 'delete_connection')\
                as delete_connection_mock:
            self.zm.driver.get_san_context.return_value = fabric_map
            self.zm.delete_connection(conn_info)
            self.zm.driver.get_san_context.assert_called_once_with(target_list)
            delete_connection_mock.assert_called_once_with(fabric_name,
                                                           init_target_map,
                                                           None,
                                                           None)

    @mock.patch('oslo_config.cfg._is_opt_registered', return_value=False)
    def test_delete_connection_error(self, opt_mock):
        with mock.patch.object(self.zm.driver, 'delete_connection')\
                as del_connection_mock:
            del_connection_mock.side_effect = exception.FCZoneDriverException
            self.assertRaises(exception.ZoneManagerException,
                              self.zm.delete_connection, conn_info)


text:
<!DOCTYPE html>

  <meta charset="utf-8">

  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <title>[cf240] B. Mashmokh and Tokens — amoshyc's CPsolution 1.0 documentation</title>

    <link rel="stylesheet" href="../../_static/css/theme.css" type="text/css" />

    <link rel="stylesheet" href="../../_static/css/mine.css" type="text/css" />

        <link rel="index" title="Index"
              href="../../genindex.html"/>
        <link rel="search" title="Search" href="../../search.html"/>
    <link rel="top" title="amoshyc's CPsolution 1.0 documentation" href="../../index.html"/>
        <link rel="up" title="交大暑訓 2016 題單:Divide and Conquer" href="index.html"/>
        <link rel="next" title="交大 2016 校內賽" href="../nctu_annual_2016/index.html"/>
        <link rel="prev" title="[cf128] C. Photographer" href="ph.html"/>

             amoshyc's CPsolution

                1.0

  <form id="rtd-search-form" class="wy-form" action="../../search.html" method="get">
    <input type="text" name="q" placeholder="Search docs" />
    <input type="hidden" name="check_keywords" value="yes" />
    <input type="hidden" name="area" value="default" />
  </form>

1. 常用演算法教學

2. CF

3. POJ

4. UVA

5. PTC

6. Other

[TOJ] 12. 遙控器

[TIOJ] 1208. 第 K 大連續和

交大暑訓 2016 題單:Enum

交大暑訓 2016 題單:DP

交大暑訓 2016 題單:Greedy

交大暑訓 2016 題單:Divide and Conquer

[cf321] B. Kefa and Company

[cf285] C. Building Permutation

[cf169] C. Little Girl and Maximum Sum

[cf168] C. k-Multiple Free Set

[cf202] C. Mafia

[cf256] C. Painting Fence

[cfother] B. Chat Order

[cf128] C. Photographer

[cf240] B. Mashmokh and Tokens

題目

Specification

分析

AC Code

交大 2016 校內賽

交大暑訓 2017 寒訓營

7. Template

8. Tags

9. Cheatsheet

          amoshyc's CPsolution

Docs »

6. Other »

交大暑訓 2016 題單:Divide and Conquer »

[cf240] B. Mashmokh and Tokens

             View page source

[cf240] B. Mashmokh and Tokens¶

Tags

tag_math

TOC

[cf240] B. Mashmokh and Tokens

題目

Specification

分析

AC Code

題目¶

\(w\) 個 tokens 可以換成 \(\floor{\frac{w * a}{b} }\) 元。
給定長度為 N 的序列 x[],代表 N 天。針對每一天,請問在保證獲得最大金錢的情況下,最多會剩下多少個 tokens?

Specification¶

1 <= n <= 10^5
1 <= a, b <= 10^9

分析¶

Note

數學

坑死人啊~

\(w\) 個 tokens 可以換成 \(\lfloor \frac{w * a}{b} \rfloor\) 元,那要得到 \(d\) 元,要用幾個 tokens 呢?答案是 \(\lceil \frac{d * b}{a} \rceil\) ──不是 \(\lfloor \frac{d * b}{a} \rfloor\) 啊!

大家應該都死很慘。

AC Code¶

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28

#include <bits/stdc++.h>
using namespace std;

typedef long long ll;

ll ceildiv(ll a, ll b) {
    return a / b + (a % b != 0);
}

int main() {
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);

    int N; ll a, b;
    cin >> N >> a >> b;

    for (int i = 0; i < N; i++) {
        ll x; cin >> x;
        ll money = x * a / b; // floor
        ll rest = x - ceildiv(money * b, a);
        // ll rest = x - ll(ceil(double(money) * b / a));
        cout << rest << " ";
    }
    cout << endl;

    return 0;
}

        Next

         Previous

        © Copyright 2016, amoshyc.

  Built with Sphinx using a theme provided by Read the Docs.


text:
package com.github.poad.functional.type.tuple;

import com.tngtech.jgiven.Stage;
import com.tngtech.jgiven.junit.ScenarioTest;
import org.junit.Test;

import java.util.Collections;
import java.util.List;

import static org.assertj.core.api.Assertions.assertThat;

public class QuadrupleTest extends ScenarioTest<QuadrupleTestStep, QuadrupleTestStep, QuadrupleTestStep>{

    @Test
    public void integer_normal() {
        given().generateInstanceWith(1, 2, 3, 4);
        then().quadrupleWith(1, 2, 3, 4);
    }

    @Test
    public void object_normal() {
        final List<Integer> list = Collections.singletonList(123);
        given().generateInstanceWith("abc", list, 123, 456);
        then().quadrupleWith("abc", list, 123, 456);
    }

    @Test
    public void object_with_null_normal() {
        given().generateInstanceWith("abc", null, null, null);
        then().quadrupleWith("abc", null, null, null);
    }
}

class QuadrupleTestStep extends Stage<QuadrupleTestStep> {
    private static class Quadruple<L, ML, MR, R> extends Triple<L, ML, MR> {
        public final R _4;

        private Quadruple(L _1, ML _2, MR _3, R _4) {
            super(_1, _2, _3);
            this._4 = _4;
        }

        public static <L, ML, MR, R> Quadruple of(L _1, ML _2, MR _3, R _4) {
            return new Quadruple(_1, _2, _3, _4);
        }

    }

    private Quadruple<?, ?, ?, ?> quadruple;

    public QuadrupleTestStep generateInstanceWith(Object i, Object i1, Object i2, Object i3) {
        quadruple = Quadruple.of(i, i1, i2, i3);
        return self();
    }

    public QuadrupleTestStep quadrupleWith(Object o, Object o1, Object o2, Object o3) {
        assertThat(quadruple._1).isEqualTo(o);
        assertThat(quadruple._2).isEqualTo(o1);
        assertThat(quadruple._3).isEqualTo(o2);
        assertThat(quadruple._4).isEqualTo(o3);
        return self();
    }
}


text:
[![Build Status](https://secure.travis-ci.org/klaussilveira/gitter.png)](http://travis-ci.org/klaussilveira/gitter)

Gitter allows you to interact in an object oriented manner with Git repositories
via PHP. The main goal of the library is not to replace the system `git` command,
but provide a coherent, stable and performatic object oriented interface.

Most commands are sent to the system's `git` command, parsed and then interpreted
by Gitter. Everything is transparent to you, so you don't have to worry about a thing.

## Requirements

* git (http://git-scm.com) (tested with 1.7.5.4)

## Authors and contributors
* [Klaus Silveira](http://www.klaussilveira.com) (Creator, developer)

## License
[New BSD license](http://www.opensource.org/licenses/bsd-license.php)

## Usage

Gitter is very easy to use and you'll just need a few method calls to get
started. For example, to create a new repository:

    $client = new Gitter\Client;
    $repository = $client->createRepository('/home/user/test');

Or a bare repository:

    $client = new Gitter\Client;
    $repository = $client->createRepository('/home/user/test', true);

Or to open an existing repository:

    $client = new Gitter\Client;
    $repository = $client->getRepository('/home/user/anothertest');

Both methods will return a `Repository` object, which has various methods
that allow you to interact with that repository.

### Getting a list of commits

Once you get hold of the `Repository` object, you can use:

    $commits = $repository->getCommits();
    print_r($commits);

To get a list of various commits.

### Getting a single commit

Given a specific commit hash, you can find information about that commit:

    $commit = $repository->getCommit('920be98a05');
    print_r($commit);


text:
package org.linqs.psl.model.rule;

import org.linqs.psl.model.atom.GroundAtom;
import org.linqs.psl.reasoner.function.ConstraintTerm;

public interface UnweightedGroundRule extends GroundRule {

    @Override
    public UnweightedRule getRule();

    /**
     * Get a GeneralFunction representation of this ground rule.
     * If mergeConstants is true, then don't merge together constant terms.
     * Merging terms is generally encouraged, but certain inference methods
     * may need direct access to these terms.
     */
    public ConstraintTerm getConstraintDefinition(boolean mergeConstants);

    /**
     * Returns the infeasibility of the truth values of this GroundRule's
     * {@link GroundAtom GroundAtoms}.
     *

     * Specifically, returns the distance between the value of the constraint's
     * functional definition and that function's nearest feasible value.
     *

     * Infeasibility is always non-negative.
     *
     * @return the infeasibility of the current truth values
     */
    public float getInfeasibility();
}


text:
<?php

namespace PhoneNumber\Filter;

use libphonenumber\NumberParseException;
use libphonenumber\PhoneNumberFormat;
use libphonenumber\PhoneNumberUtil;
use Traversable;
use Zend\Filter\AbstractFilter;
use Zend\Filter\Exception;
use Zend\ServiceManager\ServiceLocatorAwareInterface;
use Zend\ServiceManager\ServiceLocatorAwareTrait;
use Zend\Stdlib\ArrayUtils;

/**
 * Class PhoneNumberFilter
 *
 * @package PhoneNumber\Filter
 */
class PhoneNumberFilter extends AbstractFilter implements
    ServiceLocatorAwareInterface
{

    use ServiceLocatorAwareTrait;

    /**
     * @var string
     */
    private $region;

    /**
     * @return string
     */
    public function getRegion()
    {
        return $this->region;
    }

    /**
     * @param mixed $region
     */
    public function setRegion($region)
    {
        $this->region = $region;
    }

    /**
     * Sets the filter options.
     *
     * Allowed options are:
     *  'region'    => The region code used for parsing the number
     *
     * @param string|array|Traversable $options
     */
    public function __construct($options = null)
    {
        if ($options instanceof Traversable) {
            $options = ArrayUtils::iteratorToArray($options);
        }

        if (is_array($options) && !empty($options)) {
            if (isset($options['region'])) {
                $this->setRegion($options['region']);
            }
        }
    }

    /**
     * Returns the result of filtering $value.
     *
     * @param mixed $value
     *
     * @return mixed
     * @throws Exception\RuntimeException If filtering $value is impossible.
     */
    public function filter($value)
    {
        $region = $this->getRegion();
        $region = isset($region) ? $region : $this->getDefaultRegion();

        $phoneUtil = $this->getPhoneNUmberUtil();

        try {
            $numberProto = $phoneUtil->parse($value, $region);
        } catch (NumberParseException $e) {
            return $value;
        }

        return $phoneUtil->format($numberProto, PhoneNumberFormat::E164);
    }

    /**
     * @return PhoneNumberUtil
     */
    private function getPhoneNUmberUtil()
    {
        return PhoneNumberUtil::getInstance();
    }

    /**
     * @return string
     */
    private function getDefaultRegion()
    {
        $config = $this->getConfig();

        if (
            isset($config) &&
            isset($config['phone_number']) &&
            isset($config['phone_number']['default_region'])
        ) {
            return $config['phone_number']['default_region'];
        } else {
            return 'CH';
        }
    }

    /**
     * @return array
     */
    private function getConfig()
    {
        return $this->getServiceLocator()->getServiceLocator()->get('Config');
    }
}


text:
import React, { Component, PropTypes } from 'react';

import css from './Toggle.css';

export default class Toggle extends Component {
  render() {
    const { value, onChange, className } = this.props;
    return (

          <input
            type="checkbox"
            defaultChecked={value}
            onChange={onChange}
            className={css.input}
          />

    );
  }
}

Toggle.propTypes = {
  value: PropTypes.bool.isRequired,
  onChange: PropTypes.func.isRequired,
  className: PropTypes.string,
};


text:
/**
 * @author Klaus Stengel <siklsten@informatik.stud.uni-erlangen.de>
 * @author Víctor Ariño <victor.arino@tado.com>
 */
package se.sics.mspsim.core;

import java.util.Arrays;

import se.sics.mspsim.core.EmulationLogger.WarningType;
import se.sics.mspsim.core.Memory.AccessMode;
import se.sics.mspsim.util.Utils;
import edu.umass.energy.Capacitor;

public class Flash extends IOUnit {

  private static final int FCTL1 = 0x00;
  private static final int FCTL2 = 0x02;
  private static final int FCTL3 = 0x04;
  private static final int FCTL4 = 0x06;

  /* Size of the flash controller */
  public static final int SIZE = 8;

  private static final int FRKEY =   0x9600;
  private static final int FWKEY =   0xA500;
  private static final int KEYMASK = 0xff00;
  private static final int CMDMASK = 0x00ff;

  private static final int BLKWRT = 0x80;
  private static final int WRT =    0x40;

  private static final int ERASE_SHIFT = 1;
  private static final int ERASE_MASK = 0x06;

  /* Erase modes needs to be first due to usage of ordinality */
  private enum WriteMode {
    NONE,
    ERASE_SEGMENT,
    ERASE_MAIN,
    ERASE_ALL,
    WRITE_SINGLE,
    WRITE_BLOCK,
    WRITE_BLOCK_FINISH
  }

  private static final int EMEX =    0x20;
  private static final int LOCK =    0x10;
  private static final int WAIT =    0x08;
  private static final int ACCVIFG = 0x04;
  private static final int KEYV =    0x02;
  private static final int BUSY =    0x01;

  private static final int FSSEL_SHIFT = 6;
  private static final int FSSEL_MASK = 0xc0;

  private static final int RESET_VECTOR = 15;
  private static final int NMI_VECTOR = 14;
  private static final int ACCVIE = 1 << 5;

  private enum ClockSource {
    ACLK,
    MCLK,
    SMCLK
  };

  private static final int MASS_ERASE_TIME = 5297;
  private static final int SEGMENT_ERASE_TIME = 4354;

  private static final int WRITE_TIME = 35;

  private static final int BLOCKWRITE_FIRST_TIME = 30;
  private static final int BLOCKWRITE_TIME = 21;
  private static final int BLOCKWRITE_END_TIME = 6;

  private static final int FN_MASK = 0x3f;
  private static final int LOCKINFO = 0x80;

  private FlashRange main_range;
  private FlashRange info_range;

  private int mode;      /* FCTL1 */
  private int clockcfg;  /* FCTL2 */
  private int statusreg; /* FCTL3 */

  private boolean locked;
  private boolean wait;
  private boolean blocked_cpu;

  private WriteMode currentWriteMode;
  private int blockwriteCount;

  /**
   * Infomem Configurations
   */
  private int infomemcfg = 0;
  /**
   * Whether the infomem is locked or not
   */
  private boolean lockInfo = true;

  private TimeEvent end_process = new TimeEvent(0) {
    public void execute(long t) {
      System.err.println("Unblocking CPU at cycle " + cpu.cycles);
      blocked_cpu = false;
      cpu.getCapacitor().updateVoltage(false);
      cpu.getCapacitor().setPowerMode(Capacitor.POWERMODE_ACTIVE);

      switch(currentWriteMode) {
      case NONE:
        break;

      case ERASE_SEGMENT:
      case ERASE_MAIN:
      case ERASE_ALL:
        // Erase flags are automatically cleared after each erase
	mode = 0;
	currentWriteMode = WriteMode.NONE;
	cpu.isFlashBusy = false;
	break;

      case WRITE_SINGLE:
	cpu.isFlashBusy = false;
	// WRT flags are NOT automatically cleared
	break;

      case WRITE_BLOCK:
	blockwriteCount++;
	if (blockwriteCount == 64) {
	  // FIXME: What happens if we try to write more than 64 bytes
	  // on real hardware???
	  logw(WarningType.EXECUTION, "Last access in block mode. Forced exit?");
	  currentWriteMode = WriteMode.WRITE_BLOCK_FINISH;
	}
/*	if (DEBUG) {
	  System.out.println("Write cycle complete, flagged WAIT.");
	} */
	wait = true;
	break;

      case WRITE_BLOCK_FINISH:
	if (DEBUG) {
	  log("Programming voltage dropped, write mode disabled.");
	}
	currentWriteMode = WriteMode.NONE;
	cpu.isFlashBusy = false;
	wait = true;
	mode = 0;
	break;
      }
    }
  };

  public Flash(MSP430Core cpu, int[] memory, FlashRange main_range,
      FlashRange info_range, int offset) {
    super("Flash", "Internal Flash", cpu, memory, offset);
    this.main_range = main_range;
    this.info_range = info_range;
    locked = true;

    Arrays.fill(memory, main_range.start, main_range.end, 0xff);
    Arrays.fill(memory, info_range.start, info_range.end, 0xff);

    reset(MSP430.RESET_POR);
  }

  public boolean blocksCPU() {
    return blocked_cpu;
  }

  public void interruptServiced(int vector) {
    cpu.flagInterrupt(vector, this, false);
  }

  public boolean addressInFlash(int address) {
    if (main_range.isInRange(address)) {
      return true;
    }
    if (info_range.isInRange(address)) {
      return true;
    }

    return false;
  }

  private int getFlashClockDiv() {
    return (clockcfg & FN_MASK) + 1;
  }

  private void waitFlashProcess(int time) {
    int instr_addr = cpu.getPC();
    int freqdiv = getFlashClockDiv();
    int myfreq;
    double finish_msec;

    cpu.isFlashBusy = true;
    if (addressInFlash(instr_addr)) {
      blocked_cpu = true;
    }

    switch(getClockSource()) {
    case ACLK:
      myfreq = cpu.aclkFrq / freqdiv;
      finish_msec = ((double)time * freqdiv * 1000) / cpu.aclkFrq;
      if (DEBUG)
        log("Using ACLK source with f=" + myfreq + "Hz. Time required=" + finish_msec + " ms");
      cpu.scheduleTimeEventMillis(end_process, finish_msec);
      break;

    case SMCLK:
      myfreq = cpu.smclkFrq / freqdiv;
      finish_msec = ((double)time * freqdiv * 1000) / cpu.smclkFrq;
      /* if (DEBUG)
	System.out.println("Flash: Using SMCLK source with f=" + myfreq
	    + " Hz\nFlash: Time required=" + finish_msec + " ms"); */
      cpu.scheduleTimeEventMillis(end_process, finish_msec);
      break;

    case MCLK:
      if (DEBUG)
	log("Using MCLK source with div=" + freqdiv);
      cpu.scheduleCycleEvent(end_process, cpu.cycles + (long)time * freqdiv);
      cpu.getCapacitor().setPowerMode(Capacitor.POWERMODE_FLWRI);
      break;
    }
  }

  public boolean needsTick() {
    return false;
  }

  public void flashWrite(int address, int data, AccessMode dataMode) {
    int wait_time = -1;

    if (locked) {
      if (DEBUG) {
        log("Write to flash blocked because of LOCK flag.");
      }
      return;
    }

    if (lockInfo && info_range.isInRange(address)) {
      if (DEBUG) {
        log("Write to infomem blocked because of LOCKINFO flag.");
      }
    }

    if (cpu.isFlashBusy || wait == false) {
      if (!((mode & BLKWRT) != 0 && wait)) {
	triggerAccessViolation("Flash write prohbited while BUSY=1 or WAIT=0");
	return;
      }
    }

    switch(currentWriteMode) {
    case ERASE_SEGMENT:
      int a_area_start[] = new int[1];
      int a_area_end[] = new int[1];
      getSegmentRange(address, a_area_start, a_area_end);
      int area_start = a_area_start[0];
      int area_end = a_area_end[0];

      if (DEBUG) {
	log("Segment erase @" + Utils.hex(address, 4) +
	    ": erasing area " + Utils.hex(area_start, 4) + "-" +
	    Utils.hex(area_end, 4));
      }
      for (int i = area_start; i < area_end; i++) {
	memory[i] = 0xff;
      }
      waitFlashProcess(SEGMENT_ERASE_TIME);
      break;

    case ERASE_MAIN:
      if (! main_range.isInRange(address)) {
	return;
      }
      for (int i = main_range.start; i < main_range.end; i++) {
	memory[i] = 0xff;
      }
      waitFlashProcess(MASS_ERASE_TIME);
      break;

    case ERASE_ALL:
      for (int i = main_range.start; i < main_range.end; i++) {
	memory[i] = 0xff;
      }
      for (int i = info_range.start; i < info_range.end; i++) {
	memory[i] = 0xff;
      }
      waitFlashProcess(MASS_ERASE_TIME);
      break;
    case WRITE_SINGLE:
    case WRITE_BLOCK:
      if (currentWriteMode == WriteMode.WRITE_BLOCK) {
        wait = false;
        // TODO: Register target block and verify all writes stay in the same
        // block. What does the real hardware on random writes?!?
        if (blockwriteCount == 0) {
          wait_time = BLOCKWRITE_FIRST_TIME;
          if (DEBUG) {
            log("Flash write in block mode started @" + Utils.hex(address, 4));
          }
          if (addressInFlash(cpu.getPC())) {
            logw(WarningType.EXECUTION, "Oops. Block write access only allowed when executing from RAM.");
          }
        } else {
          wait_time = BLOCKWRITE_TIME;
        }
      } else {
        wait_time = WRITE_TIME;
      }
      /* Flash memory allows clearing bits only */
      memory[address] &= data & 0xff;
      if (dataMode != AccessMode.BYTE) {
          memory[address + 1] &= (data >> 8) & 0xff;
          if (dataMode == AccessMode.WORD20) {
              /* TODO should the write really write the full word? CHECK THIS */
              memory[address + 2] &= (data >> 16) & 0xff;
              memory[address + 3] &= (data >> 24) & 0xff;
          }
      }
      if (DEBUG) {
        log("Writing $" + Utils.hex20(data) + " to $" + Utils.hex(address, 4) + " (" + dataMode.bytes + " bytes)");
      }
      waitFlashProcess(wait_time);
      break;
    }
  }

  public void notifyRead(int address) {
    if (cpu.isFlashBusy) {
      triggerAccessViolation("Flash read not allowed while BUSY flag set");
      return;
    }
    if (DEBUG) {
      if (wait == false && currentWriteMode == WriteMode.WRITE_BLOCK) {
	log("Reading flash prohibited. Would read 0x3fff!!!");
	log("CPU PC=$" + Utils.hex(cpu.getPC(), 4)
	    + " read address $" + Utils.hex(address, 4));
      }
    }
  }

  private FlashRange getFlashRange(int address) {
    if (main_range.isInRange(address)) {
      return main_range;
    }
    if (info_range.isInRange(address)) {
      return info_range;
    }
    return null;
  }

  private void getSegmentRange(int address, int[] start, int[] end) {
    FlashRange addr_type = getFlashRange(address);
    int segsize, ioffset;

    if (addr_type == null) {
      throw new RuntimeException("Address not in flash");
    }

    segsize = addr_type.segment_size;
    ioffset = address - addr_type.start;

    ioffset /= segsize;
    ioffset *= segsize;

    start[0] = addr_type.start + ioffset;
    end[0] = start[0] + segsize;
  }

  public int read(int address, boolean word, long cycles) {
    address = address - offset;

    if (address == FCTL1) {
      return mode | FRKEY;
    }
    if (address == FCTL2) {
      return clockcfg | FRKEY;
    }
    if (address == FCTL3) {
      int retval = statusreg | FRKEY;

      if (cpu.isFlashBusy)
	retval |= BUSY;

      if (locked)
	retval |= LOCK;

      if (wait)
	retval |= WAIT;

      return retval;
    }
    if (address == FCTL4) {
      return infomemcfg | FRKEY;
    }

    return 0;
  }

  private ClockSource getClockSource() {
    switch((clockcfg & FSSEL_MASK) >> FSSEL_SHIFT) {
      case 0:
      return ClockSource.ACLK;
      case 1:
      return ClockSource.MCLK;
      case 2:
      case 3:
      return ClockSource.SMCLK;
    }
    throw new RuntimeException("Bad clock source");
  }

  private boolean checkKey(int value) {
    if ((value & KEYMASK) == FWKEY)
      return true;

    logw(WarningType.EXECUTION, "Bad key accessing flash controller --> reset");
    statusreg |= KEYV;
    cpu.flagInterrupt(RESET_VECTOR, this, true);
    return false;
  }

  private void triggerEmergencyExit() {
    mode = 0;
    cpu.isFlashBusy = false;
    blocked_cpu = false;
    wait = true;
    locked = true;
    currentWriteMode = WriteMode.NONE;
  }

  private WriteMode getEraseMode(int regdata) {
    int idx = (regdata & ERASE_MASK) >> ERASE_SHIFT;

    for (WriteMode em : WriteMode.values()) {
      if (em.ordinal() == idx)
	return em;
    }
    throw new IllegalArgumentException("Invalid erase mode: " + regdata);
  }

  private void triggerErase(int newmode) {
    currentWriteMode = getEraseMode(newmode);
  }

  private void triggerLockFlash() {
    locked = true;
  }

  private void triggerUnlockFlash() {
    locked = false;
  }

  private void triggerAccessViolation(String reason) {
    logw(WarningType.EXECUTION, "Access violation: " + reason + ". PC=$" + Utils.hex(cpu.getPC(), 4));

    statusreg |= ACCVIFG;
    if (cpu.getSFR().isIEBitsSet(SFR.IE1, ACCVIE)) {
      cpu.flagInterrupt(NMI_VECTOR, this, true);
    }
  }

  private void triggerSingleWrite() {
    /*if (DEBUG) {
      System.out.println("Single write triggered");
    }*/
    currentWriteMode = WriteMode.WRITE_SINGLE;
  }

  private void triggerBlockWrite() {
    if (DEBUG) {
      log("Block write triggered");
    }
    currentWriteMode = WriteMode.WRITE_BLOCK;
    blockwriteCount = 0;
  }

  private void triggerEndBlockWrite() {
    if (DEBUG) {
      log("Got end of flash block write");
    }
    currentWriteMode = WriteMode.WRITE_BLOCK_FINISH;
    waitFlashProcess(BLOCKWRITE_END_TIME);
  }

  public void write(int address, int value, boolean word, long cycles) {
    address = address - offset;
    if (!word) {
      logw(WarningType.EXECUTION, "Invalid access type to flash controller");
      return;
    }

    if (!(address == FCTL1 || address == FCTL2 || address == FCTL3
   		 || address == FCTL4)) {
      return;
    }

    if (!checkKey(value)) {
      return;
    }

    int regdata = value & CMDMASK;
    switch (address) {
    case FCTL1:
      // access violation while erase/write in progress
      // exception: block write mode and WAIT==1
//      if ((mode & ERASE_MASK) != 0 || (mode & WRT) != 0) {
      if (cpu.isFlashBusy && ((mode & BLKWRT) == 0 || wait == false)) {
          //	if (!((mode & BLKWRT) != 0 && wait)) {
        triggerAccessViolation("FCTL1 write not allowed while erase/write active");
        return;
      }

      if ((mode & ERASE_MASK) != (regdata & ERASE_MASK)) {
	if ((mode & ERASE_MASK) == 0) {
	  triggerErase(regdata);
	}
	mode &= ~ERASE_MASK;
	mode |= regdata & ERASE_MASK;
      }

      if ((mode & WRT) != (regdata & WRT)) {
	if ((regdata & WRT) != 0) {
	  if ((regdata & BLKWRT) != 0) {
	    triggerBlockWrite();
	    mode |= BLKWRT;
	  } else {
	    triggerSingleWrite();
	  }
	}
	mode &= ~WRT;
	mode |= regdata & WRT;
      }

      if ((mode & BLKWRT) != 0 && (regdata & BLKWRT) == 0) {
	triggerEndBlockWrite();
	mode &= ~BLKWRT;
      }
      break;

    case FCTL2:
      // access violation if BUSY==1
      if (cpu.isFlashBusy) {
	triggerAccessViolation(
	    "Register write to FCTL2 not allowed when busy");
	return;
      }
      clockcfg = regdata;
      break;

    case FCTL3:
      if ((statusreg & EMEX) == 0 && (regdata & EMEX) == 1) {
	triggerEmergencyExit();
      }

      if (locked && (regdata & LOCK) == 0) {
	triggerUnlockFlash();
      } else {
	if (!locked && (regdata & LOCK) != 0) {
	  triggerLockFlash();
	}
      }

      if (((statusreg ^ regdata) & KEYV) != 0) {
	statusreg ^= KEYV;
      }
      if (((statusreg ^ regdata) & ACCVIFG) != 0) {
	statusreg ^= ACCVIFG;
      }

      break;
    case FCTL4:
      lockInfo = (regdata & LOCKINFO) > 0;
      infomemcfg = regdata;
      break;
    }
  }

  public void reset(int type) {
    if (DEBUG) {
      log("Got reset!");
    }

    if (type == MSP430.RESET_POR)
      statusreg = 0;

    mode = 0;
    clockcfg = 0x42;
    cpu.isFlashBusy = false;
    blocked_cpu = false;
    wait = true;
    locked = true;
    currentWriteMode = WriteMode.NONE;
  }
}


text:
import unittest
from coord import Coord
from cell import Cell
from field import Field

def dummy():
    """ Dummy function for comparison of the return values """
    return

class CoordTest(unittest.TestCase):

    def setUp(self):
        self.field = Field()
        pass

    def tearDown(self):
        pass

    def testMain(self):
        self.coord = Coord()
        assert self.coord.main() == dummy(), 'Gol01.get_size() does not provide the right return value'

    def testCoordSavesItsCoordinates(self):
        coord = Coord(4,5)
        assert 4 == coord.x
        assert 5 == coord.y

    def testCreatedCellIsAlive(self):
        coord1 = Coord(4,5)
        cell = Cell(coord1)
        assert cell.isAlive() == True, 'cell.status() does not provide the right return value'

    def testCellKnowsIfItLivesInTheNextStep(self):
        cell = Cell(Coord(4,5))
        cell.nextStep(5)
        assert False == cell.isAlive()

    def addCell(self,x,y):
        self.field.add(Cell(Coord(x, y)))

    def fillExampleField(self):
        self.addCell(1,1)
        self.addCell(1,2)
        self.addCell(2,1)

    def testFieldIsWellCreated(self):
        self.fillExampleField()
        assert self.field.getNumberOfLivingCells() == 3, 'field.numberOfAliveCells does not provide the right return value'

# run all tests
if __name__ == "__main__":
    try:
        unittest.main()
    except SystemExit as inst:
        if inst.args[0] is True: # raised by sys.exit(True) when tests failed
            raise


text:
<?php

namespace App\Models;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'username', 'bio', 'designation', 'avatar', 'role', 'active', 'timezone', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    const ADMIN = 1;
    const MEMBER = 2;
}


text:
namespace google {
namespace cloud {
namespace texttospeech_internal {
GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN

TextToSpeechMetadata::TextToSpeechMetadata(
    std::shared_ptr<TextToSpeechStub> child)
    : child_(std::move(child)),
      api_client_header_(
          google::cloud::internal::ApiClientHeader("generator")) {}

StatusOr<google::cloud::texttospeech::v1::ListVoicesResponse>
TextToSpeechMetadata::ListVoices(
    grpc::ClientContext& context,
    google::cloud::texttospeech::v1::ListVoicesRequest const& request) {
  SetMetadata(context);
  return child_->ListVoices(context, request);
}

StatusOr<google::cloud::texttospeech::v1::SynthesizeSpeechResponse>
TextToSpeechMetadata::SynthesizeSpeech(
    grpc::ClientContext& context,
    google::cloud::texttospeech::v1::SynthesizeSpeechRequest const& request) {
  SetMetadata(context);
  return child_->SynthesizeSpeech(context, request);
}

void TextToSpeechMetadata::SetMetadata(grpc::ClientContext& context,
                                       std::string const& request_params) {
  context.AddMetadata("x-goog-request-params", request_params);
  SetMetadata(context);
}

void TextToSpeechMetadata::SetMetadata(grpc::ClientContext& context) {
  context.AddMetadata("x-goog-api-client", api_client_header_);
  auto const& options = internal::CurrentOptions();
  if (options.has<UserProjectOption>()) {
    context.AddMetadata("x-goog-user-project",
                        options.get<UserProjectOption>());
  }
  auto const& authority = options.get<AuthorityOption>();
  if (!authority.empty()) context.set_authority(authority);
}

GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END
}  // namespace texttospeech_internal
}  // namespace cloud
}  // namespace google


text:
{-# OPTIONS_GHC -fno-warn-redundant-constraints #-}
{-# LANGUAGE UndecidableInstances,
             MultiParamTypeClasses,
             KindSignatures,
             FlexibleInstances,
             FunctionalDependencies #-}

module Storage.Hashed.Monad () where

import Control.Applicative (Applicative(..))
import Data.Kind (Type)

class Monad m => TreeRO m where
    withDirectory :: (MonadError e m) => Int -> m a -> m a
    expandTo :: (MonadError e m) => Int -> m Int

instance (Monad m, MonadError e m) => TreeRO (M m) where
    expandTo = undefined
    withDirectory dir _ = do
      _ <- expandTo dir
      undefined

data M (m :: Type -> Type) a

instance Functor (M m) where
    fmap = undefined

instance Applicative (M m) where
    pure = undefined
    (<*>) = undefined

instance Monad m => Monad (M m) where
    (>>=) = undefined
    return = undefined

instance MonadError e m => MonadError e (M m)

class Monad m => MonadError e m | m -> e


text:
'use strict'

var pako = require('../../../');
var utils = require('../../../lib/utils/common');

exports.run = function(data, level) {
  utils.setTyped(false);
  pako.deflate(data.typed, {
    level: level
  });
  utils.setTyped(true);
}


text:
<?php
require 'shared.php';

$canOrder = !empty($shared->studentId) || $shared->isEmployee;
$canProxyOrder = in_array('checkout', $shared->employeePermissions);

if (!$canOrder) {
    header('Location: /sso');
    die;
}

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $c = $pdo->beginTransaction();

    $toProcess = array();
    $errors = array();

    foreach ($shared->currentCart as $id => $quantity) {
        if ($quantity <= 0) {
            continue;
        }
        $query = $pdo->prepare('SELECT id, price FROM Product WHERE id = ? AND quantity >= ? AND enabled IS TRUE LIMIT 1');
        $query->execute(array($id, $quantity));
        if ($query->rowCount() == 0) {
            $errors[$id] = true;
            continue;
        }
        $row = $query->fetchObject();

        $toProcess[$id] = array('quantity' => $quantity, 'price' => $row->price);
    }
    if (!empty($errors) || empty($toProcess)) {
        $pdo->rollback();
        header('Location: /cart/error/' . implode('.', array_keys($errors)));
        die;
    }

    $query = $pdo->prepare('INSERT INTO StoreOrder (status, student_id, employee_id) VALUES (\'Ordered\', ?, ?)');
    $studentId = $shared->studentId;
    if (!empty($_POST['student_id']) && $canProxyOrder) {
        $studentId = $_POST['student_id'];
    }
    $employee = $shared->employee;
    if (empty($employee)) {
        $employee = NULL;
    }
    $query->execute(array($studentId, $employee));

    if ($query->rowCount() == 0) {
        $pdo->rollback();
        header('Location: /cart/error/');
        die;
    }

    $orderId = $pdo->lastInsertId();

    foreach ($toProcess as $id => $value) {
        $quantity = $value['quantity'];
        $price = $value['price'];
        $query = $pdo->prepare('UPDATE Product SET quantity = quantity - ? WHERE id = ?');
        $query->execute(array($quantity, $id));

        $query = $pdo->prepare('INSERT INTO OrderContents (order_id, product_id, price, quantity) VALUES (?, ?, ?, ?)');
        $query->execute(array($orderId, $id, $price, $quantity));
    }
    $pdo->commit();

    setcookie('cart', '', time() - 3600);

    header('Location: /order-history/' . $orderId);
    die;
}

header('Location: /cart');


text:
package ru.spbau.mit.dbmsau.command;

import com.google.common.collect.Lists;
import junitx.util.PrivateAccessor;
import org.junit.Test;
import ru.spbau.mit.dbmsau.BaseTest;
import ru.spbau.mit.dbmsau.Context;
import ru.spbau.mit.dbmsau.relation.ColumnAccessor;
import ru.spbau.mit.dbmsau.relation.Relation;
import ru.spbau.mit.dbmsau.relation.StubRelation;
import ru.spbau.mit.dbmsau.table.StubTableManager;
import ru.spbau.mit.dbmsau.table.StubTableRecordManager;
import ru.spbau.mit.dbmsau.table.TableManager;
import ru.spbau.mit.dbmsau.table.TableRecordManager;
import ru.spbau.mit.dbmsau.table.exception.SemanticError;

import java.util.Arrays;

public class SelectCommandTest extends BaseTest {
    private Relation buildStubRelation() {
        return new StubRelation("test", "id", "name", "abc");
    }

    private int[] invokeBuildColumnIndexesToSelect(SelectCommand command) throws Throwable {
        return (int[]) PrivateAccessor.invoke(
            command, "buildColumnsIndexesToSelect",
            new Class[]{Relation.class},
            new Object[]{
                buildStubRelation()
            }
        );
    }

    @Test
    public void testBuildColumnsIndexesToSelect() throws Throwable {
        SelectCommand command = new SelectCommand(
            Arrays.asList(
                new ColumnAccessor(null, "name"),
                new ColumnAccessor("test", "id"),
                new ColumnAccessor(null, "abc")
            ),
            "test",
            null
        );
        command.setContext(context);

        int[] result = invokeBuildColumnIndexesToSelect(command);
        assertArrayEquals(result, new int[]{1, 0, 2});

        command = new SelectCommand(
            null,
            "test",
            null
        );
        command.setContext(context);

        result = invokeBuildColumnIndexesToSelect(command);
        assertArrayEquals(result, new int[]{0, 1, 2});
    }

    @Test
    public void testBuildColumnsIndexesToSelectError() throws Throwable {
        thrown.expect(SemanticError.class);
        thrown.expectMessage("Unknown column `abcee`");

        SelectCommand command = new SelectCommand(
            Arrays.asList(
                new ColumnAccessor(null, "name"),
                new ColumnAccessor("test", "id"),
                new ColumnAccessor(null, "abcee")
            ),
            "test",
            null
        );
        command.setContext(context);

        invokeBuildColumnIndexesToSelect(command);
    }

    @Test
    public void testSelectWithColumns() throws Exception {
        SelectCommand command = new SelectCommand(
            Arrays.asList(
                new ColumnAccessor(null, "name"),
                new ColumnAccessor("test", "id")
            ),
            "test",
            null
        );
        command.setContext(context);

        SQLCommandResult result = command.execute();

        assertTrue(result.isIterable());

        Object[] queryOutput = Lists.newArrayList(result.iterator()).toArray();

        assertArrayEquals(
            new String[]{
                "test.name:varchar(50);test.id:integer",
                "asd;1",
                "def;2"
            },
            queryOutput
        );
    }

    @Test
    public void testSelectWithAsterisk() throws Exception {
        SelectCommand command = new SelectCommand(
            null,
            "test",
            null
        );
        command.setContext(context);

        SQLCommandResult result = command.execute();

        assertTrue(result.isIterable());

        Object[] queryOutput = Lists.newArrayList(result.iterator()).toArray();

        assertArrayEquals(
            new String[]{
                "test.id:integer;test.name:varchar(50)",
                "1;asd",
                "2;def"
            },
            queryOutput
        );
    }

    @Override
    protected TableManager buildTableManager(Context context) {
        TableManager tableManager = new StubTableManager(context);
        try {
            tableManager.createNewTable(buildTestTable());
        } catch (Exception e) {

        }
        return tableManager;
    }

    @Override
    protected TableRecordManager buildTableRecordManager(Context context) {
        return new StubTableRecordManager(context);
    }
}


text:
<?php

/**
 * Parse exception thrown when something went wrong while parsing the scenario.
 *
 * @author Peter Decuyper <peter@serial-graphics.be>
 */
class Hostingcheck_Scenario_Parser_Exception
    extends Exception
{}


text:
package org.specs.util

object ExtendedFunctions extends ExtendedFunctions
trait ExtendedFunctions {
  implicit def extend[A, B](f: Function[A, B]) = new ExtendedFunction(f)
}
/**
 * this class allows to use a function as if it was a partial function.
 *
 * It is especially useful when one want to overload a function with both functions and partial function
 * literals. This usually is an issue because of the way the compiler interprets function and
 * partial function literals (see the Scala Language Specification, section 8.5).
 *
 * The following specification shows the how to use it:
 * <code>
 * 	class Test[T](val t: T) {
 *     def call[S](x: Function[T, S]): Option[S] = x.applySafely(t)
 *  }
 *  val test = new Test("hello")
 *  test call identity must beSome("hello")
 *  // this behaves like a partial function but is a function really
 *  test call { case s if s.size < 2 => "partial " + s } must beNone
 * </code>
 *
 */
class ExtendedFunction[A, B](f: Function[A, B]) {
  def applySafely(a: A): Option[B] = {
	try {
	  Some(f(a))
	} catch {
	  case e: MatchError => None
	}
  }
}


text:
package org.apache.spark

import org.apache.spark.util.Utils

/**
  * Created by aa on 4/20/2016.
  */
object UtilsAux {

  def createTempDir(
                     rootDir: String,
                     namePrefix: String = "repl"
                   ) = Utils.createTempDir(
      root = rootDir,
      namePrefix = namePrefix
    )

}


text:
require "railsblocks/tenant/engine"

module Railsblocks::Tenant
end


text:
/*
 * EmbeddedStratum.java
 *
 * Created on April 30, 2004, 4:12 PM
 */

package fm.ua.ikysil.smap;

import java.util.Iterator;

import fm.ua.ikysil.smap.collections.*;

/**
 *
 * @author  Illya Kysil
 */
public class EmbeddedStratum extends AbstractStratum implements Cloneable {

    private SourceMapList sourceMapList = new SourceMapList();

    /** Creates a new instance of EmbeddedStratum */
    public EmbeddedStratum() {
        this("");
    }

    public EmbeddedStratum(String name) {
        super(name);
    }

    @Override
    public Object clone() {
        EmbeddedStratum embeddedStratum = new EmbeddedStratum(getName());
        for (Iterator iter = sourceMapList.iterator(); iter.hasNext();) {
            embeddedStratum.getSourceMapList().add((SourceMap) ((SourceMap) iter.next()).clone());
        }
        return embeddedStratum;
    }

    /**
     * Getter for property sourceMapList.
     * @return Value of property sourceMapList.
     */
    public SourceMapList getSourceMapList() {
        return sourceMapList;
    }

    /**
     * Setter for property sourceMapList.
     * @param sourceMapList New value of property sourceMapList.
     */
    public void setSourceMapList(SourceMapList sourceMapList) {
        this.sourceMapList.clear();
        if (sourceMapList != null) {
            this.sourceMapList.addAll(sourceMapList);
        }
    }

}


text:
import yaml
import os
from uuid import uuid1
from jinja2 import Environment
from hashlib import sha256
global sshpubkey

def password(key, short=False):
    global sshpubkey
    password = sha256("{0}:{1}".format(sshpubkey, key)).hexdigest()
    if short:
        return password[:20]
    else:
        return password

def uuid(input):
    return str(uuid1())

def do_step(context):
    global sshpubkey

    env = Environment()
    env.filters['password'] = password
    env.filters['uuid'] = uuid

    settings = context.meta['settings']
    sshpubkey = settings['adminSSHKey']
    index_file = context.meta['index-file']

    f = open("manifests/{0}".format(index_file))
    manifests = yaml.safe_load(f)
    f.close()

    m_list = []
    for m in manifests['manifests']:
        m_list.append("manifests/{0}".format(m['file']))

    m_list.append('bosh.yml')

    # Normalize settings from ARM template
    norm_settings = {}
    norm_settings["DIRECTOR_UUID"] = "{{ DIRECTOR_UUID }}"
    norm_settings["CF_PUBLIC_IP_ADDRESS"] = settings["cf-ip"]

    for setting in context.meta['settings']:
        norm_settings[setting.replace("-", "_")] = settings[setting]

    # Render the yml template for bosh-init
    for template_path in m_list:

        if os.path.exists(template_path):
            with open(template_path, 'r') as f:
                contents = f.read()
                contents = env.from_string(contents).render(norm_settings)

        with open(os.path.join('bosh', template_path), 'w') as f:
            f.write(contents)

    return context


text:
package org.jfrog.artifactory.client;

import org.jfrog.artifactory.client.model.File;
import org.jfrog.artifactory.client.model.RepoPath;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static java.util.Arrays.asList;
import static org.apache.commons.lang.StringUtils.countMatches;
import static org.testng.Assert.*;

/**
 * @author jbaruch
 * @author rnaegele
 * @since 03/08/12
 */
public class SearchTests extends ArtifactoryTestsBase {
    private String colorsProp = "colors-";
    private String buildProp = "build-";
    private String releasedProp = "released-";
    private String artifactId = "com.example.searchtests-";

    @BeforeClass
    public void setup() {
        long now = System.currentTimeMillis();
        colorsProp += now;
        buildProp += now;
        releasedProp += now;
        artifactId += now;

        InputStream inputStream = this.getClass().getResourceAsStream("/sample.zip");
        assertNotNull(inputStream);
        final String targetPath = "com/example/" + artifactId + "/1.0.0/" + artifactId + "-1.0.0-zip.jar";
        File deployed = artifactory.repository(localRepository.getKey()).upload(targetPath, inputStream)
                .withProperty(colorsProp, "red", "green", "blue")
                .withProperty(buildProp, "28")
                .withProperty(releasedProp, true)
                .doUpload();
        assertNotNull(deployed);
    }

    @Test
    public void testLimitlessQuickSearch() throws IOException {
        List<RepoPath> results = artifactory.searches().artifactsByName("junit").doSearch();
        assertEquals(results.size(), countMatches(curl("api/search/artifact?name=junit"), "{") - 1);
    }

    @Test
    public void testLatestVersionSearch() throws IOException {
        String results = artifactory.searches().artifactsLatestVersion()
                .groupId("org.jfrog.maven.annomojo")
                .artifactId("maven-plugin-anno")
                .repositories(getJCenterRepoName())
                .doRawSearch();
        assertEquals(results, "1.4.1");
    }

    @Test
    public void testQuickSearchWithWrongSingleLimit() throws IOException {
        List<RepoPath> list = artifactory.searches().artifactsByName("junit").repositories(localRepository.getKey()).doSearch();
        assertTrue(list.isEmpty());
    }

    @Test
    public void testQuickSearchWithRightSingleLimit() throws IOException {
        List<RepoPath> results = artifactory.searches().artifactsByName("junit").repositories(getJcenterCacheName()).doSearch();
        assertEquals(results.size(), countMatches(curl("api/search/artifact?name=junit&repos=" + getJcenterCacheName()), "{") - 1);
    }

    @Test(expectedExceptions = IllegalArgumentException.class)
    public void testQuickSearchWithoutSearchTerm() throws IOException {
        artifactory.searches().doSearch();
    }

    @Test
    public void testQuickSearchWithMultipleLimits() throws IOException {
        List<RepoPath> results =
                artifactory.searches().artifactsByName("junit").repositories(localRepository.getKey(), getJcenterCacheName())
                        .doSearch();
        assertEquals(results.size(),
                countMatches(curl("api/search/artifact?name=junit&repos=" + localRepository.getKey() + "," + getJcenterCacheName()), "{") - 1);
    }

    @Test
    public void testSearchByProperty() throws IOException {
        List<RepoPath> results = artifactory.searches().itemsByProperty().property(colorsProp, "red").doSearch();
        assertEquals(results.size(), 1);
        assertTrue(results.get(0).getItemPath().contains(artifactId + "-1.0.0-zip.jar"));
    }

    @Test
    public void testSearchByPropertyWithMapNotation() throws IOException {
        Map<String, Boolean> properties = new HashMap<>();
        properties.put(releasedProp, true);
        List<RepoPath> results = artifactory.searches().itemsByProperty().properties(properties).doSearch();
        assertEquals(results.size(), 1);
        assertTrue(results.get(0).getItemPath().contains(artifactId + "-1.0.0-zip.jar"));
    }

    @Test
    public void testSearchByPropertyAndRepoFilter() throws IOException {
        List<RepoPath> results =
                artifactory.searches().itemsByProperty().property(releasedProp, true).repositories(localRepository.getKey()).doSearch();
        assertEquals(results.size(), 1);
        assertTrue(results.get(0).getItemPath().contains(artifactId + "-1.0.0-zip.jar"));
    }

    @Test
    public void testSearchByPropertyAndWrongRepoFilter() throws IOException {
        List<RepoPath> list = artifactory.searches().repositories(getJCenterRepoName()).itemsByProperty().property(releasedProp, true).doSearch();
        assertTrue(list.isEmpty());
    }

    @Test
    public void testSearchByPropertyWithMulipleValue() throws IOException {
        List<RepoPath> list = artifactory.searches().itemsByProperty().property(colorsProp, "red", "green", "blue").doSearch();
        assertTrue(list.isEmpty());
    }

    @Test
    public void testSearchByPropertyMapNotationWithMulipleValue() throws IOException {
        Map<String, List<String>> property = new HashMap<>();
        property.put(colorsProp, asList("black", "white", "pink"));
        property.put(buildProp, asList("29"));
        List<RepoPath> list = artifactory.searches().itemsByProperty().properties(property).doSearch();
        assertTrue(list.isEmpty());
    }

    @Test
    public void testSearchByPropertyWithoutValue() throws IOException {
        List<RepoPath> results =
                artifactory.searches().itemsByProperty().property(releasedProp).property(buildProp, 28).doSearch();
        assertEquals(results.size(), 1);
        assertTrue(results.get(0).getItemPath().contains(artifactId + "-1.0.0-zip.jar"));
    }

    @Test
    public void testSearchByPropertyWithWildCards() throws IOException {
        List<RepoPath> results = artifactory.searches().itemsByProperty().property(colorsProp, "r*?").doSearch();
        assertEquals(results.size(), 1);
        assertTrue(results.get(0).getItemPath().contains(artifactId + "-1.0.0-zip.jar"));
    }

    @Test
    public void testSearchByGavc() throws IOException {
        List<RepoPath> results = artifactory.searches().artifactsByGavc()
                .groupId("com.example")
                .artifactId(artifactId)
                .version("1.0.0")
                .classifier("zip")
                .doSearch();
        assertEquals(results.size(), 1);
        assertTrue(results.get(0).getItemPath().contains(artifactId + "-1.0.0-zip.jar"));
    }

    @Test
    public void testSearchByGavcAndRepository() throws IOException {
        List<RepoPath> results = artifactory.searches().artifactsByGavc()
                .groupId("com.example")
                .artifactId(artifactId)
                .version("1.0.0")
                .classifier("zip")
                .repositories(localRepository.getKey())
                .doSearch();
        assertEquals(results.size(), 1);
        assertTrue(results.get(0).getItemPath().contains(artifactId + "-1.0.0-zip.jar"));
    }

    @Test
    public void testArtifactsCreatedSinceSearch() throws IOException {
        long startTime = System.currentTimeMillis() - 86400000L;
        List<RepoPath> results = artifactory.searches().artifactsCreatedSince(startTime).doSearch();
        assertFalse(results.isEmpty());
    }

    @Test
    public void testArtifactsCreatedInDateRangeSearch() throws IOException {
        long now = System.currentTimeMillis() + 60000L;
        long startTime = now - 86400000L;
        List<RepoPath> results = artifactory.searches().artifactsCreatedInDateRange(startTime, now).doSearch();
        assertFalse(results.isEmpty());
    }
}


text:
namespace flutter_runner {

// A |VkImage| and its relevant metadata.
struct VulkanImage {
  VulkanImage() = default;
  VulkanImage(VulkanImage&&) = default;
  VulkanImage& operator=(VulkanImage&&) = default;

  VkBufferCollectionImageCreateInfoFUCHSIAX vk_collection_image_create_info;
  VkImageCreateInfo vk_image_create_info;
  VkMemoryRequirements vk_memory_requirements;
  vulkan::VulkanHandle<VkImage> vk_image;

  FML_DISALLOW_COPY_AND_ASSIGN(VulkanImage);
};

class VulkanSurface final : public SurfaceProducerSurface {
 public:
  VulkanSurface(vulkan::VulkanProvider& vulkan_provider,
                fuchsia::sysmem::AllocatorSyncPtr& sysmem_allocator,
                fuchsia::ui::composition::AllocatorPtr& flatland_allocator,
                sk_sp<GrDirectContext> context,
                scenic::Session* session,
                const SkISize& size,
                uint32_t buffer_id);

  ~VulkanSurface() override;

  // |SurfaceProducerSurface|
  size_t AdvanceAndGetAge() override;

  // |SurfaceProducerSurface|
  bool FlushSessionAcquireAndReleaseEvents() override;

  // |SurfaceProducerSurface|
  bool IsValid() const override;

  // |SurfaceProducerSurface|
  SkISize GetSize() const override;

  // Note: It is safe for the caller to collect the surface in the
  // |on_writes_committed| callback.
  void SignalWritesFinished(
      const std::function<void(void)>& on_writes_committed) override;

  // |SurfaceProducerSurface|
  void SetImageId(uint32_t image_id) override;

  // |SurfaceProducerSurface|
  uint32_t GetImageId() override;

  // |SurfaceProducerSurface|
  sk_sp<SkSurface> GetSkiaSurface() const override;

  // |SurfaceProducerSurface|
  fuchsia::ui::composition::BufferCollectionImportToken
  GetBufferCollectionImportToken() override;

  // |SurfaceProducerSurface|
  zx::event GetAcquireFence() override;

  // |SurfaceProducerSurface|
  zx::event GetReleaseFence() override;

  // |SurfaceProducerSurface|
  void SetReleaseImageCallback(
      ReleaseImageCallback release_image_callback) override;

  const vulkan::VulkanHandle<VkImage>& GetVkImage() {
    return vulkan_image_.vk_image;
  }

  const vulkan::VulkanHandle<VkSemaphore>& GetAcquireVkSemaphore() {
    return acquire_semaphore_;
  }

  vulkan::VulkanCommandBuffer* GetCommandBuffer(
      const vulkan::VulkanHandle<VkCommandPool>& pool) {
    if (!command_buffer_)
      command_buffer_ = std::make_unique<vulkan::VulkanCommandBuffer>(
          vulkan_provider_.vk(), vulkan_provider_.vk_device(), pool);
    return command_buffer_.get();
  }

  const vulkan::VulkanHandle<VkFence>& GetCommandBufferFence() {
    return command_buffer_fence_;
  }

  size_t GetAllocationSize() const { return vk_memory_info_.allocationSize; }

  size_t GetImageMemoryRequirementsSize() const {
    return vulkan_image_.vk_memory_requirements.size;
  }

  bool IsOversized() const {
    return GetAllocationSize() > GetImageMemoryRequirementsSize();
  }

  bool HasStableSizeHistory() const {
    return std::equal(size_history_.begin() + 1, size_history_.end(),
                      size_history_.begin());
  }

 private:
  static constexpr int kSizeHistorySize = 4;

  void OnHandleReady(async_dispatcher_t* dispatcher,
                     async::WaitBase* wait,
                     zx_status_t status,
                     const zx_packet_signal_t* signal);

  bool AllocateDeviceMemory(
      fuchsia::sysmem::AllocatorSyncPtr& sysmem_allocator,
      fuchsia::ui::composition::AllocatorPtr& flatland_allocator,
      sk_sp<GrDirectContext> context,
      const SkISize& size,
      uint32_t buffer_id);

  bool CreateVulkanImage(vulkan::VulkanProvider& vulkan_provider,
                         const SkISize& size,
                         VulkanImage* out_vulkan_image);

  bool SetupSkiaSurface(sk_sp<GrDirectContext> context,
                        const SkISize& size,
                        SkColorType color_type,
                        const VkImageCreateInfo& image_create_info,
                        const VkMemoryRequirements& memory_reqs);

  bool CreateFences();

  void PushSessionImageSetupOps(scenic::Session* session);

  void Reset();

  vulkan::VulkanHandle<VkSemaphore> SemaphoreFromEvent(
      const zx::event& event) const;

  vulkan::VulkanProvider& vulkan_provider_;
  scenic::Session* session_;
  VulkanImage vulkan_image_;
  vulkan::VulkanHandle<VkDeviceMemory> vk_memory_;
  VkMemoryAllocateInfo vk_memory_info_;
  vulkan::VulkanHandle<VkFence> command_buffer_fence_;
  sk_sp<SkSurface> sk_surface_;
  uint32_t buffer_id_ = 0;
  fuchsia::ui::composition::BufferCollectionImportToken import_token_;
  uint32_t image_id_ = 0;
  vulkan::VulkanHandle<VkBufferCollectionFUCHSIAX> collection_;
  zx::event acquire_event_;
  vulkan::VulkanHandle<VkSemaphore> acquire_semaphore_;
  std::unique_ptr<vulkan::VulkanCommandBuffer> command_buffer_;
  zx::event release_event_;
  async::WaitMethod<VulkanSurface, &VulkanSurface::OnHandleReady> wait_;
  std::function<void()> pending_on_writes_committed_;
  std::array<SkISize, kSizeHistorySize> size_history_;
  int size_history_index_ = 0;
  size_t age_ = 0;
  bool valid_ = false;
  ReleaseImageCallback release_image_callback_;

  FML_DISALLOW_COPY_AND_ASSIGN(VulkanSurface);
};

}  // namespace flutter_runner


text:
package com.ragdroid.dahaka.user;

import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

import javax.inject.Scope;

/**
 * Created by garimajain on 05/03/17.
 */
@Scope
@Documented
@Retention(value = RetentionPolicy.RUNTIME)
public @interface UserScope {
}


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

{% block title %}
     {% trans "Inventory Update" %}
{% endblock %}

{% block header %}

{% include "dojo_include.html" %}

{% endblock %}

{% block content %}

	{% include tabnav %}

    <form action="." method="POST" >{% csrf_token %}
		<input name='producer-id' type='hidden' value='{{ producer.id }}' />
		<input name='avail-date' type='hidden' value='{{ avail_date }}' />

                {% trans "Producer" %}:
                {{ producer.long_name }}

                {% trans "Week of" %}:
                {{ avail_date}}

            <input type="submit" value="{% trans 'Submit' %}" />

			{% trans "Product" %}
			{% trans "Lot Id" %}
			{% trans "Field" %}
			{% comment %}
			{% trans "Custodian" %}
			{% endcomment %}
			{% trans "Available Date" %}
			{% trans "Availability Ends" %}
			{% trans "Quantity" %}
			{% trans "Orders" %}
			{% trans "Notes" %}

            {% for item_form in item_forms %}

			  {{ item_form.description }}
			  {{ item_form.freeform_lot_id }}
			  {{ item_form.field_id }}
			 {% comment %}
			  {{ item_form.custodian }}
			 {% endcomment %}
			 {{ item_form.inventory_date }}
			 {{ item_form.expiration_date }}
			 {{ item_form.remaining }}
			 {{ item_form.ordered }}
			 {{ item_form.notes }}
			{{ item_form.item_id }}
			{{ item_form.prod_id }}

           {% endfor %}

            <input type="submit" value="{% trans 'Submit' %}" />

    </form>

{% endblock %}


text:
/*
 * Vanilla Crop Class.
 */
package com.infinityraider.agricraft.core;

import com.agricraft.agricore.core.AgriCore;
import com.agricraft.agricore.plant.AgriPlant;
import com.infinityraider.agricraft.api.v1.crop.IAgriCrop;
import com.infinityraider.agricraft.api.v1.plant.IAgriPlant;
import com.infinityraider.agricraft.api.v1.render.RenderMethod;
import com.infinityraider.agricraft.api.v1.requirement.BlockCondition;
import com.infinityraider.agricraft.api.v1.requirement.IGrowthReqBuilder;
import com.infinityraider.agricraft.api.v1.requirement.IGrowthRequirement;
import com.infinityraider.agricraft.api.v1.stat.IAgriStat;
import com.infinityraider.agricraft.api.v1.util.BlockRange;
import com.infinityraider.agricraft.api.v1.util.FuzzyStack;
import com.infinityraider.agricraft.farming.PlantStats;
import com.infinityraider.agricraft.farming.growthrequirement.GrowthReqBuilder;
import com.infinityraider.agricraft.init.AgriItems;
import com.infinityraider.agricraft.reference.AgriNBT;
import com.infinityraider.agricraft.reference.Constants;
import com.infinityraider.agricraft.renderers.PlantRenderer;
import com.infinityraider.infinitylib.render.tessellation.ITessellator;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.Random;
import java.util.function.Consumer;
import java.util.function.Function;
import net.minecraft.client.renderer.block.model.BakedQuad;
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.common.property.IExtendedBlockState;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;

public class JsonPlant implements IAgriPlant {

    private final AgriPlant plant;

    private final List<FuzzyStack> seedItems;
    private final IGrowthRequirement growthRequirement;

    public JsonPlant(AgriPlant plant) {
        this.plant = Objects.requireNonNull(plant, "A JSONPlant may not consist of a null AgriPlant! Why would you even try that!?");
        this.seedItems = initSeedItemsListJSON(plant);
        this.growthRequirement = initGrowthRequirementJSON(plant);
    }

    @Override
    public boolean isWeed() {
        return this.plant.isWeedable();
    }

    @Override
    public boolean isAggressive() {
        return this.plant.isAgressive();
    }

    @Override
    public boolean isFertilizable() {
        return this.plant.canBonemeal();
    }

    @Override
    public String getId() {
        return this.plant.getId();
    }

    @Override
    public String getPlantName() {
        return this.plant.getPlantName();
    }

    @Override
    public String getSeedName() {
        return this.plant.getSeedName();
    }

    @Override
    public Collection<FuzzyStack> getSeedItems() {
        return this.seedItems;
    }

    @Override
    public final ItemStack getSeed() {
        ItemStack stack = this.getSeedItems().stream()
                .map(s -> s.toStack())
                .findFirst()
                .orElse(new ItemStack(AgriItems.getInstance().AGRI_SEED));
        NBTTagCompound tag = new NBTTagCompound();
        tag.setString(AgriNBT.SEED, this.getId());
        new PlantStats().writeToNBT(tag);
        stack.setTagCompound(tag);
        return stack;
    }

    @Override
    public String getInformation() {
        return this.plant.getDescription().toString();
    }

    @Override
    public double getSpreadChance() {
        return this.plant.getSpreadChance();
    }

    @Override
    public double getSpawnChance() {
        return this.plant.getSpawnChance();
    }

    @Override
    public double getGrassDropChance() {
        return this.plant.getGrassDropChance();
    }

    @Override
    public double getGrowthChanceBase() {
        return plant.getGrowthChance();
    }

    @Override
    public double getGrowthChanceBonus() {
        return plant.getGrowthBonus();
    }

    @Override
    public double getSeedDropChanceBase() {
        return plant.getSeedDropChance();
    }

    @Override
    public double getSeedDropChanceBonus() {
        return plant.getSeedDropBonus();
    }

    @Override
    public int getGrowthStages() {
        return this.plant.getGrowthStages();
    }

    @Override
    public void getPossibleProducts(Consumer<ItemStack> products) {
        this.plant.getProducts().getAll().stream()
                .map(p -> p.toStack(FuzzyStack.class))
                .filter(Optional::isPresent)
                .map(p -> p.get().toStack())
                .forEach(products);
    }

    @Override
    public void getHarvestProducts(Consumer<ItemStack> products, IAgriCrop crop, IAgriStat stat, Random rand) {
        this.plant.getProducts().getRandom(rand).stream()
                .map(p -> p.toStack(FuzzyStack.class, rand))
                .filter(Optional::isPresent)
                .map(p -> p.get().toStack())
                .forEach(products);
    }

    @Override
    public IGrowthRequirement getGrowthRequirement() {
        return growthRequirement;
    }

    @Override
    @SideOnly(Side.CLIENT)
    public float getHeight(int meta) {
        return Constants.UNIT * 13;
    }

    @Override
    @SideOnly(Side.CLIENT)
    public RenderMethod getRenderMethod() {
        switch (this.plant.getTexture().getRenderType()) {
            default:
            case HASH:
                return RenderMethod.HASHTAG;
            case CROSS:
                return RenderMethod.CROSSED;
        }
    }

    @Override
    @SideOnly(Side.CLIENT)
    public ResourceLocation getPrimaryPlantTexture(int growthStage) {
        return new ResourceLocation(plant.getTexture().getPlantTexture(growthStage));
    }

    @Override
    @SideOnly(Side.CLIENT)
    public ResourceLocation getSecondaryPlantTexture(int growthStage) {
        return null;
    }

    @Override
    public ResourceLocation getSeedTexture() {
        return new ResourceLocation(plant.getTexture().getSeedTexture());
    }

    @Override
    @SideOnly(Side.CLIENT)
    public List<BakedQuad> getPlantQuads(IExtendedBlockState state, int growthStage, EnumFacing direction, Function<ResourceLocation, TextureAtlasSprite> textureToIcon) {
        //The quads returned from this method are added to the tessellator,
        // however the plant renderer directly adds them to the tessellator, so an empty list is returned
        if (textureToIcon instanceof ITessellator) {
            PlantRenderer.renderPlant((ITessellator) textureToIcon, this, growthStage);
        }
        return Collections.emptyList();
    }

    public static final List<FuzzyStack> initSeedItemsListJSON(AgriPlant plant) {
        final List<FuzzyStack> seeds = new ArrayList<>(plant.getSeedItems().size());
        plant.getSeedItems().stream()
                .map(i -> i.toStack(FuzzyStack.class))
                .filter(Optional::isPresent)
                .map(Optional::get)
                .forEach(seeds::add);
        if (seeds.isEmpty()) {
            seeds.add(new FuzzyStack(new ItemStack(AgriItems.getInstance().AGRI_SEED)));
        }
        return seeds;
    }

    public static final IGrowthRequirement initGrowthRequirementJSON(AgriPlant plant) {

        IGrowthReqBuilder builder = new GrowthReqBuilder();

        if (plant == null) {
            return builder.build();
        }

        if (plant.getRequirement().getSoils().isEmpty()) {
            AgriCore.getLogger("agricraft").warn("Plant: \"{0}\" has no valid soils to plant on!", plant.getPlantName());
        }

        plant.getRequirement().getSoils().stream()
                .map(JsonSoil::new)
                .forEach(builder::addSoil);

        plant.getRequirement().getConditions().forEach(obj -> {
            final Optional<FuzzyStack> stack = obj.toStack(FuzzyStack.class);
            if (stack.isPresent()) {
                builder.addCondition(
                        new BlockCondition(
                                stack.get(),
                                new BlockRange(
                                        obj.getMinX(), obj.getMinY(), obj.getMinZ(),
                                        obj.getMaxX(), obj.getMaxY(), obj.getMaxZ()
                                )
                        )
                );
            }
        });

        builder.setMinLight(plant.getRequirement().getMinLight());
        builder.setMaxLight(plant.getRequirement().getMaxLight());

        return builder.build();

    }

    @Override
    public boolean equals(Object obj) {
        return (obj instanceof IAgriPlant) && (this.getId().equals(((IAgriPlant) obj).getId()));
    }

    @Override
    public int hashCode() {
        return this.getId().hashCode();
    }

}


text:
1.1.0 / 2017-11-21
==================
### Changes

* [UPDATE] Update auto_conf template to support agent 6 and 5.20+. See [#860][]

1.0.0 / 2017-03-22
==================

### Changes

* [FEATURE] adds riak integration.

<!--- The following link definition list is generated by PimpMyChangelog --->
[#860]: https://github.com/DataDog/integrations-core/issues/860


text:
/****************************************************************************
**
**  Name: MicoFileStat.c
**
**  Description:
**        Implements _fstat, called by Newlib C library file functions
**
**  $Revision: $
**
** Disclaimer:
**
**   This source code is intended as a design reference which
**   illustrates how these types of functions can be implemented.  It
**   is the user's responsibility to verify their design for
**   consistency and functionality through the use of formal
**   verification methods.  Lattice Semiconductor provides no warranty
**   regarding the use or functionality of this code.
**
** --------------------------------------------------------------------
**
**                     Lattice Semiconductor Corporation
**                     5555 NE Moore Court
**                     Hillsboro, OR 97214
**                     U.S.A
**
**                     TEL: 1-800-Lattice (USA and Canada)
**                          (503)268-8001 (other locations)
**
**                     web:   http://www.latticesemi.com
**                     email: techsupport@latticesemi.com
**
** --------------------------------------------------------------------------
**
**  Change History (Latest changes on top)
**
**  Ver    Date        Description
** --------------------------------------------------------------------------
**
**  3.0   Mar-25-2008  Added Header
**
**---------------------------------------------------------------------------
*****************************************************************************/

#include <_ansi.h>
#include <_syslist.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include "MicoFileDevices.h"

#ifdef __cplusplus
extern "C" {
#endif

/******************************************************************
 *                                                                *
 * Implements _read required by NewLibC's _read_r function        *
 *                                                                *
 ******************************************************************/
int _fstat(int fd, struct stat *pstat)
{
    MicoFileDesc_t *pFD;
    int retValue =-1;

    /* given the file-id, fetch the associated file-descriptor */
    if(MicoGetFDEntry(fd, &pFD) != 0)
        return(-1);

    /* ask the device to write the data if it is capable of writing data */
    if(pFD->pFileOpsTable->stat)
        retValue = pFD->pFileOpsTable->stat(pFD, pstat);

    /* all done */
    return(retValue);

}

#ifdef __cplusplus
}
#endif


text:
package com.edwise.pocs.orikapoc.config;

import ma.glasnost.orika.CustomConverter;
import ma.glasnost.orika.metadata.Type;

import java.time.LocalDate;
import java.time.LocalDateTime;

public class LocalDateTimeToLocalDateConverter
        extends CustomConverter<LocalDateTime, LocalDate> {
    public LocalDate convert(LocalDateTime source,
                             Type<? extends LocalDate> destinationType) {
        return source.toLocalDate();
    }
}


text:
package edu.uci.ics.asterix.external.dataset.adapter;

import java.util.List;
import java.util.Map;
import java.util.UUID;

import twitter4j.Query;
import twitter4j.QueryResult;
import twitter4j.Tweet;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import edu.uci.ics.asterix.dataflow.data.nontagged.serde.ARecordSerializerDeserializer;
import edu.uci.ics.asterix.om.base.AMutableRecord;
import edu.uci.ics.asterix.om.base.AMutableString;
import edu.uci.ics.asterix.om.base.IAObject;
import edu.uci.ics.asterix.om.types.ARecordType;
import edu.uci.ics.hyracks.api.context.IHyracksTaskContext;

/**
 * An implementation of @see {PullBasedFeedClient} for the Twitter service.
 * The feed client fetches data from Twitter service by sending request at
 * regular (configurable) interval.
 */
public class PullBasedTwitterFeedClient extends PullBasedFeedClient {

    private String keywords;
    private Query query;
    private Twitter twitter;
    private int requestInterval = 10; // seconds
    private QueryResult result;

    private IAObject[] mutableFields;
    private String[] tupleFieldValues;
    private ARecordType recordType;
    private int nextTweetIndex = 0;

    public PullBasedTwitterFeedClient(IHyracksTaskContext ctx, ARecordType recordType, PullBasedTwitterAdapter adapter) {
        twitter = new TwitterFactory().getInstance();
        mutableFields = new IAObject[] { new AMutableString(null), new AMutableString(null), new AMutableString(null),
                new AMutableString(null), new AMutableString(null) };
        this.recordType = recordType;
        recordSerDe = new ARecordSerializerDeserializer(recordType);
        mutableRecord = new AMutableRecord(recordType, mutableFields);
        tupleFieldValues = new String[recordType.getFieldNames().length];
        initialize(adapter.getConfiguration());
    }

    public ARecordType getRecordType() {
        return recordType;
    }

    public AMutableRecord getMutableRecord() {
        return mutableRecord;
    }

    @Override
    public InflowState setNextRecord() throws Exception {
        Tweet tweet;
        tweet = getNextTweet();
        if (tweet == null) {
            return InflowState.DATA_NOT_AVAILABLE;
        }
        int numFields = recordType.getFieldNames().length;
        tupleFieldValues[0] = UUID.randomUUID().toString();
        tupleFieldValues[1] = tweet.getFromUser();
        tupleFieldValues[2] = tweet.getLocation() == null ? "" : tweet.getLocation();
        tupleFieldValues[3] = tweet.getText();
        tupleFieldValues[4] = tweet.getCreatedAt().toString();
        for (int i = 0; i < numFields; i++) {
            ((AMutableString) mutableFields[i]).setValue(tupleFieldValues[i]);
            mutableRecord.setValueAtPos(i, mutableFields[i]);
        }
        return InflowState.DATA_AVAILABLE;
    }

    private void initialize(Map<String, String> params) {
        this.keywords = (String) params.get(PullBasedTwitterAdapter.QUERY);
        this.requestInterval = Integer.parseInt((String) params.get(PullBasedTwitterAdapter.INTERVAL));
        this.query = new Query(keywords);
        query.setRpp(100);
    }

    private Tweet getNextTweet() throws TwitterException, InterruptedException {
        if (result == null || nextTweetIndex >= result.getTweets().size()) {
            Thread.sleep(1000 * requestInterval);
            result = twitter.search(query);
            nextTweetIndex = 0;
        }
        List<Tweet> tw = result.getTweets();
        return tw.get(nextTweetIndex++);
    }

}


text:
const dwarfNames = require('./names');

/**
 * Return first and last characters of the given name.
 *
 * @example
 *
 *  'Garrett' => ['g', 't']
 *  'Caira' => ['c', 'a']
 *
 * @private
 * @param {string} name
 * @return {string[]}
 */

function getNameLetters(name) {
    const letters = name.toLowerCase().split('');
    return letters.slice(0, 1).concat(letters.slice(-1));
}

/**
 * Are all passed names valid? (string of length > 0);
 *
 * @private
 * @param {string[]} names - Names to validate.
 * @return {boolean}
 */

function validNames(...names) {
    return names.every(name => typeof name === 'string' && name.length);
}

/**
 * Dwarfinate a name of the given kind (first name or last name).
 *
 * @private
 * @param {string} name - Name to dwarfinate.
 * @param {string} kind - Kind of name to dwarfinate (first or last).
 * @return {string} - Dwarfinated name.
 */

function dwarfName(name, kind = 'first') {
    const [first, last] = getNameLetters(name);
    return dwarfNames[kind].start[first] + dwarfNames[kind].end[last];
}

/**
 * Dwarfinate someone's first and last names.
 *
 * @example
 *
 *  'Garrett Parrot' => 'Marvi Goldgrip'
 *  'Caira Doo' => 'Urdar Ironstrike'
 *
 * @public
 * @param {string} first - First name to dwarfinate.
 * @param {string} last - Last name to dwarfinate.
 * @return {string} - Joined dwarfinated name.
 */

module.exports = function dwarfinate(first, last) {
    if (validNames(first, last)) {
        return `${dwarfName(first, 'first')} ${dwarfName(last, 'last')}`;
    } else {
        throw `Invalid names "${first}" and "${last}" given!`;
    }
};


text:
package kanekotic.specflow.rider;

import gherkin.Parser;
import gherkin.ast.Feature;
import gherkin.ast.GherkinDocument;
import gherkin.ast.ScenarioDefinition;
import gherkin.ast.Tag;
import org.junit.Test;

import java.util.ArrayList;
import java.util.List;

import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.*;

public class SpecflowAnalizerTest {

    @Test
    public void analizeCallsCorrectProcess() throws Exception {
        Parser<GherkinDocument> parser = (Parser<GherkinDocument>) mock(Parser.class);
        ISpecflowTranslator translator = mock(ISpecflowTranslator.class);
        ITestFrameworkConstants constants = mock(ITestFrameworkConstants.class);

        String document = Faker.getRandomString();
        GherkinDocument gherkinDocument = mock(GherkinDocument.class);
        when(parser.parse(document)).thenReturn(gherkinDocument);
        Feature feature = mock(Feature.class);
        List<ScenarioDefinition> scenarios = new ArrayList<>();
        List<Tag> tags = new ArrayList<>();
        when(feature.getChildren()).thenReturn(scenarios);
        when(feature.getTags()).thenReturn(tags);

        when(gherkinDocument.getFeature()).thenReturn(feature);
        SpecflowFileContents translatedScenarios =new SpecflowFileContents(Faker.getRandomString(), Faker.getRandomString());
        SpecflowFileContents translatedFeature =new SpecflowFileContents(Faker.getRandomString(), Faker.getRandomString());
        SpecflowFileContents translatedFile =new SpecflowFileContents(Faker.getRandomString(), Faker.getRandomString());
        String namespace = Faker.getRandomString();
        when(translator.translate(scenarios, tags, constants)).thenReturn(translatedScenarios);
        when(translator.translate(feature, translatedScenarios,constants)).thenReturn(translatedFeature);
        when(translator.translate(namespace,translatedFeature, constants)).thenReturn(translatedFile);

        SpecflowAnalyzer analyzer = new SpecflowAnalyzer(parser, translator, constants);
        SpecflowFileContents contents = analyzer.analyze(document, namespace);

        verify(parser).parse(document);
        assertEquals(translatedFile.feature, contents.feature);
        assertEquals(translatedFile.steps, contents.steps);
    }

}


text:
<?php

namespace Laravel\BrowserKitTesting;

use PHPUnit_Framework_ExpectationFailedException;

class HttpException extends PHPUnit_Framework_ExpectationFailedException
{
    //
}