text:
package org.apache.pulsar.sql.presto;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Sets;
import io.trino.spi.connector.ConnectorContext;
import io.trino.spi.predicate.TupleDomain;
import io.trino.testing.TestingConnectorContext;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
import org.apache.bookkeeper.mledger.Entry;
import org.apache.bookkeeper.mledger.ManagedLedgerConfig;
import org.apache.bookkeeper.mledger.ReadOnlyCursor;
import org.apache.bookkeeper.mledger.impl.PositionImpl;
import org.apache.bookkeeper.stats.NullStatsProvider;
import org.apache.commons.lang3.RandomUtils;
import org.apache.pulsar.broker.auth.MockedPulsarServiceBaseTest;
import org.apache.pulsar.client.api.Producer;
import org.apache.pulsar.client.api.Schema;
import org.apache.pulsar.client.impl.MessageIdImpl;
import org.apache.pulsar.common.api.raw.RawMessageImpl;
import org.apache.pulsar.common.naming.TopicName;
import org.apache.pulsar.common.policies.data.ClusterData;
import org.apache.pulsar.common.policies.data.TenantInfoImpl;
import org.jctools.queues.SpscArrayQueue;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

/**
 * Test cache size allocator.
 */
@Slf4j
public class TestCacheSizeAllocator extends MockedPulsarServiceBaseTest {

    private final int singleEntrySize = 500;

    @BeforeClass
    @Override
    public void setup() throws Exception {
        super.internalSetup();

        admin.clusters().createCluster("test", ClusterData.builder().serviceUrl(brokerUrl.toString()).build());

        // so that clients can test short names
        admin.tenants().createTenant("public",
                new TenantInfoImpl(Sets.newHashSet("appid1", "appid2"), Sets.newHashSet("test")));
        admin.namespaces().createNamespace("public/default");
        admin.namespaces().setNamespaceReplicationClusters("public/default", Sets.newHashSet("test"));
    }

    @AfterClass
    @Override
    public void cleanup() throws Exception {
        super.internalCleanup();
    }

    @DataProvider(name = "cacheSizeProvider")
    public Object[][] dataProvider() {
        return new Object[][] {
                {-1}, {0}, {2000}, {5000}
        };
    }

    @Test(dataProvider = "cacheSizeProvider", timeOut = 1000 * 20)
    public void cacheSizeAllocatorTest(long entryQueueSizeBytes) throws Exception {
        TopicName topicName = TopicName.get(
                "public/default/cache-size-" + entryQueueSizeBytes + "test_" + + RandomUtils.nextInt()) ;
        int totalMsgCnt = 1000;
        MessageIdImpl firstMessageId = prepareData(topicName, totalMsgCnt);

        ReadOnlyCursor readOnlyCursor = pulsar.getManagedLedgerFactory().openReadOnlyCursor(
                topicName.getPersistenceNamingEncoding(),
                PositionImpl.get(firstMessageId.getLedgerId(), firstMessageId.getEntryId()),
                new ManagedLedgerConfig());
        readOnlyCursor.skipEntries(totalMsgCnt);
        PositionImpl lastPosition = (PositionImpl) readOnlyCursor.getReadPosition();

        ObjectMapper objectMapper = new ObjectMapper();

        PulsarSplit pulsarSplit = new PulsarSplit(
                0,
                "connector-id",
                topicName.getNamespace(),
                topicName.getLocalName(),
                topicName.getLocalName(),
                totalMsgCnt,
                new String(Schema.BYTES.getSchemaInfo().getSchema()),
                Schema.BYTES.getSchemaInfo().getType(),
                firstMessageId.getEntryId(),
                lastPosition.getEntryId(),
                firstMessageId.getLedgerId(),
                lastPosition.getLedgerId(),
                TupleDomain.all(),
                objectMapper.writeValueAsString(new HashMap<>()),
                null);

        List<PulsarColumnHandle> pulsarColumnHandles = TestPulsarConnector.getColumnColumnHandles(
                topicName, Schema.BYTES.getSchemaInfo(), PulsarColumnHandle.HandleKeyValueType.NONE, true);

        PulsarConnectorConfig connectorConfig = new PulsarConnectorConfig();
        connectorConfig.setMaxSplitQueueSizeBytes(entryQueueSizeBytes);

        ConnectorContext prestoConnectorContext = new TestingConnectorContext();
        PulsarRecordCursor pulsarRecordCursor = new PulsarRecordCursor(
                pulsarColumnHandles, pulsarSplit, connectorConfig, pulsar.getManagedLedgerFactory(),
                new ManagedLedgerConfig(), new PulsarConnectorMetricsTracker(new NullStatsProvider()),
                new PulsarDispatchingRowDecoderFactory(prestoConnectorContext.getTypeManager()));

        Class<PulsarRecordCursor> recordCursorClass = PulsarRecordCursor.class;
        Field entryQueueField = recordCursorClass.getDeclaredField("entryQueue");
        entryQueueField.setAccessible(true);
        SpscArrayQueue<Entry> entryQueue = (SpscArrayQueue<Entry>) entryQueueField.get(pulsarRecordCursor);

        Field messageQueueField = recordCursorClass.getDeclaredField("messageQueue");
        messageQueueField.setAccessible(true);
        SpscArrayQueue<RawMessageImpl> messageQueue =
                (SpscArrayQueue<RawMessageImpl>) messageQueueField.get(pulsarRecordCursor);

        long maxQueueSize = 0;
        if (entryQueueSizeBytes == -1) {
            maxQueueSize = Long.MAX_VALUE;
        } else if (entryQueueSizeBytes == 0) {
            maxQueueSize = 1;
        } else if (entryQueueSizeBytes > 0) {
            maxQueueSize = entryQueueSizeBytes / 2 / singleEntrySize + 1;
        }

        int receiveCnt = 0;
        while (receiveCnt != totalMsgCnt) {
            if (pulsarRecordCursor.advanceNextPosition()) {
                receiveCnt ++;
            }
            Assert.assertTrue(entryQueue.size() <= maxQueueSize);
            Assert.assertTrue(messageQueue.size() <= maxQueueSize);
        }
    }

    private MessageIdImpl prepareData(TopicName topicName, int messageNum) throws Exception {
        Producer<byte[]> producer = pulsarClient.newProducer()
                .topic(topicName.toString())
                .create();

        MessageIdImpl firstMessageId = null;
        for (int i = 0; i < messageNum; i++) {
            MessageIdImpl messageId = (MessageIdImpl) producer.send(new byte[singleEntrySize]);
            if (firstMessageId == null) {
                firstMessageId = messageId;
            }
        }
        return firstMessageId;
    }

}


text:
require 'spec_helper'

describe PublicStatus do
  pending "add some examples to (or delete) #{__FILE__}"
end

redpajama_set_name: RedPajamaGithub


text:
echo "press any key to start"

read a

numactl --cpunodebind=0 --membind=1 ../memoptest 0 >> /dev/null &
sleep 1
numactl --cpunodebind=0 --membind=1 ../memoptest 0 >> /dev/null &
sleep 1
numactl --cpunodebind=0 --membind=1 ../memoptest 0 >> /dev/null &
sleep 1
numactl --cpunodebind=0 --membind=1 ../memoptest 0 >> /dev/null &
sleep 1
numactl --cpunodebind=0 --membind=1 ../memoptest 0 >> /dev/null &
sleep 1
numactl --cpunodebind=0 --membind=1 ../memoptest 0 >> /dev/null &
sleep 1
numactl --cpunodebind=0 --membind=1 ../memoptest 0 >> /dev/null &
sleep 1
numactl --cpunodebind=0 --membind=1 ../memoptest 0 >> /dev/null &

echo "Press any key"
read a

numactl --cpunodebind=1 --membind=0 ../memoptest 0 >> /dev/null &
sleep 1
numactl --cpunodebind=1 --membind=0 ../memoptest 0 >> /dev/null &
sleep 1
numactl --cpunodebind=1 --membind=0 ../memoptest 0 >> /dev/null &
sleep 1
numactl --cpunodebind=1 --membind=0 ../memoptest 0 >> /dev/null &
sleep 1
numactl --cpunodebind=1 --membind=0 ../memoptest 0 >> /dev/null &
sleep 1
numactl --cpunodebind=1 --membind=0 ../memoptest 0 >> /dev/null &
sleep 1
numactl --cpunodebind=1 --membind=0 ../memoptest 0 >> /dev/null &
sleep 1
numactl --cpunodebind=1 --membind=0 ../memoptest 0 >> /dev/null &
sleep 1

echo "press any key to exit"
read a

killall memoptest


text:
package br.com.splessons;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * Hello world!
 *
 */
public class App
{
    public static void main( String[] args )
    {
    	ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");

		HelloWorld obj = (HelloWorld) context.getBean("helloBean");
		System.out.println(obj.sayHello());
    }
}


text:
require 'test_helper'

class ActsAgainstDouchebarTest < ActiveSupport::TestCase
  # Replace this with your real tests.
  test "the truth" do
    assert true
  end
end


text:
_SlEventPropogationStatus_e sl_Provisioning_HttpServerEventHdl(
                            SlHttpServerEvent_t    *apSlHttpServerEvent,
                            SlHttpServerResponse_t *apSlHttpServerResponse)
{
	// Unused in this application
	return EVENT_PROPAGATION_CONTINUE;
}

//*****************************************************************************
//
//! \brief This function serves as first level network application events handler.
//!        It runs under driver context and performs only operation that can run
//!        from this context. For operations that can't is sets an indication of
//!        received token and preempts the provisioning context.
//!
//! \param apEventInfo Pointer to the net app event information
//!
//! \return None
//!
//*****************************************************************************
_SlEventPropogationStatus_e sl_Provisioning_NetAppEventHdl(SlNetAppEvent_t *apNetAppEvent)
{
	// Unused in this application
	return EVENT_PROPAGATION_CONTINUE;
}

//*****************************************************************************
//
//! \brief This function serves as first level WLAN events handler.
//!        It runs under driver context and performs only operation that can run
//!        from this context. For operations that can't is sets an indication of
//!        received token and preempts the provisioning context.
//!
//! \param apEventInfo Pointer to the WLAN event information
//!
//! \return None
//!
//*****************************************************************************
_SlEventPropogationStatus_e sl_Provisioning_WlanEventHdl(SlWlanEvent_t *apEventInfo)
{
	// Unused in this application
	return EVENT_PROPAGATION_CONTINUE;
}

//*****************************************************************************
// SimpleLink Asynchronous Event Handlers -- End
//*****************************************************************************

//*****************************************************************************
//
//! \brief This function handles General Events
//!
//! \param[in]     pDevEvent - Pointer to General Event Info
//!
//! \return None
//!
//*****************************************************************************
void SimpleLinkGeneralEventHandler(SlDeviceEvent_t *pDevEvent)
{

}


text:
CLI tool for replacing node dependencies with their respective git repositories.

## Installation

```
npm install -g gitify-dependencies
```

## Usage

```
gitify-deps [--options]
```

### Options

| Flag | Environment variable | Description | Allowed values | Default value |
|------|----------------------|-------------|----------------|---------------|
| --checkout-tags
-c | CHECKOUT_TAGS | If a dependency is already a git repo, the CLI will just "git checkout" the version specified in `npm-shrinkwrap.json`. | 'yes', 'no' | 'no' |
| --gitify-url-pattern
-p | GITIFY_URL_PATTERN | Specify a pattern that gets matched against the package's url.
 **Please note, that you must either set this flag or the environment variable!** | none | none |
| --node-projects-dir
 -d | NODE_PROJECTS_DIR | Set a path which will keep the git repository's data. | none | $HOME/.gitify |

## Idea

This tool walks through your `npm-shrinkwrap.json` file and does the following things for every dependency (and it's sub-dependencies):

1. Clone or update the package's repo in `{NODE_PROJECTS_DIR}/{name of the dependency}`.
2. Back up the package's private `node_modules` directory if present.
3. Remove any existing package.
4. Create a new git "workdir" in it's place that shares the same repository as `{NODE_PROJECTS_DIR}/{name of the dependency}`.
5. Restore the package's private `node_modules`.

In practice you can treat this like a sort of "linked clone" of the original repo. Objects and refs (branches and tags) will be shared between all workdirs, but each one will have it's own working tree, HEAD, and index (staging area). One caveat is that only the git repository is synced, making changes and commiting in one workdir doesn't affect the files in another workdir. Use feature branches

More information about workdirs:

 - [Nice explanation of git-new-workdir](http://nuclearsquid.com/writings/git-new-workdir/)
 - [The original script from git/git/contrib](https://github.com/git/git/blob/7b69fcb181941fafda99a5ffd25cea1f685d7e70/contrib/workdir/git-new-workdir)


text:
set(DOCUMENTATION "This module contains classes made to visually
enhance the images, mostly by adding them artificial colors")

itk_module(ITKImageFusion
  DEPENDS
    ITKBinaryMathematicalMorphology
  TEST_DEPENDS
    ITKTestKernel
  DESCRIPTION
    "${DOCUMENTATION}"
)


text:
module QuickNotify

  class Mailer < ActionMailer::Base

    def notification_email(notif)
      opts = notif.delivery_settings_for(:email)
      opts[:to] = notif.user.email
      opts[:subject] = notif.subject
      opts[:body] = notif.full_message || notif.message
      opts[:html_body] = notif.html_message
      opts[:scope] = {notification: notif}
      app_email(opts)

    end

    def app_email(opts)
      @options = opts
      @scope = opts[:scope] || {}

      html_lay = opts[:html_layout] || QuickNotify.options[:email][:html_layout]
      html_tpl = opts[:html_template]
      has_html_template = !html_tpl.nil?
      has_html_layout = !html_lay.nil?

      text_body = opts[:text_body] || opts[:body]
      html_body = opts[:html_body] || QuickNotify.convert_text_to_html(text_body)
      has_html_body = !html_body.nil?

      mail_opts = (QuickNotify.options[:email][:headers] || {}).merge( opts[:headers] || {} )
      mail_opts[:to] = opts[:to]
      mail_opts[:cc] = opts[:cc] if opts[:cc]
      mail_opts[:bcc] = opts[:bcc] if opts[:bcc]
      mail_opts[:subject] = opts[:subject]
      mail(mail_opts) do |format|
        if has_html_template
          format.html { render html_tpl, layout: html_lay }
        elsif has_html_body
          format.html { render body: html_body, layout: html_lay }
        end
        if !text_body.nil?
          format.text { render text: text_body }
        end
      end
    end

  end

end


text:
<?php

use app\assets\VCSBindingsAsset;
use user\models\User;
use user\models\UserAccountForm;
use user\widgets\ProfileMenu;
use yii\base\View;
use yii\helpers\Html;
use yii\widgets\Pjax;

/* @var $this View */
/* @var $model User */
/* @var $accounts UserAccountForm[] */
/* @var $newAccount UserAccountForm */
/* @var $successMessage string */
/* @var $errorMessage string */

VCSBindingsAsset::register($this);

$this->title = Html::encode(Yii::t('user', 'Your profile'));
?>

<?= Yii::t('user', 'VCS bindings') ?>

    <?php Pjax::begin(['enablePushState' => false]); ?>
        <?= $this->render('vcs-bindings-accounts', [
            'model' => $model,
            'accounts' => $accounts,
            'successMessage' => $successMessage,
            'errorMessage' => $errorMessage,
        ]) ?>
    <?php Pjax::end(); ?>

<?php
$this->blocks['left_block'] = ProfileMenu::widget([
    'authUser' => Yii::$app->user->identity,
    'options' => [
        'class' => 'nav nav-pills nav-stacked',
    ],
]);
?>


text:
<def-group>

  <!-- THIS FILE IS GENERATED by create_services_disabled.py according to RHEL-7 template
       from RHEL/7/input/checks/oval_5.11/templates/template_service_disabled. DO NOT EDIT.

       IF REQUIRED INSTEAD OF EDITING THIS FILE RATHER EDIT THAT TEMPLATE DIRECTLY.
       AFTER THAT BE SURE TO REGENERATE ALL CORRESPONDING UNCOMMENTED CHECKS FROM
       service_disabled.csv CSV FILE AND PLACE THOSE NEW OVAL VERSIONS into
       RHEL/7/input/checks/oval_5.11 DIRECTORY REPLACING THE FORMER ONES
  -->

  <definition class="compliance" id="service_atd_disabled" version="1">
    <metadata>
      <title>Service atd Disabled</title>
      <affected family="unix">
        <platform>Red Hat Enterprise Linux 7</platform>
      </affected>
      <description>The atd service should be disabled if possible.</description>
      <reference source="JL" ref_id="RHEL7_20150605" ref_url="test_attestation" />
    </metadata>
    <criteria comment="package at removed or service atd is not configured to start" operator="OR">
      <extend_definition comment="at removed" definition_ref="package_at_removed" />
      <criteria operator="OR" comment="service atd is not configured to start">
        <criterion comment="atd not wanted by multi-user.target" test_ref="test_atd_not_wanted_by_multi_user_target" />
      </criteria>
    </criteria>
  </definition>

  <linux:systemdunitdependency_test check="all" check_existence="any_exist" comment="systemd test" id="test_atd_not_wanted_by_multi_user_target" version="1">
    <linux:object object_ref="object_multi_user_target_for_atd" />
    <linux:state state_ref="state_systemd_atd_off"/>
  </linux:systemdunitdependency_test>

  <linux:systemdunitdependency_object id="object_multi_user_target_for_atd" comment="list of dependencies of multi-user.target" version="1">
    <linux:unit>multi-user.target</linux:unit>
  </linux:systemdunitdependency_object>

  <linux:systemdunitdependency_state id="state_systemd_atd_off" comment="atd is not listed in the dependencies" version="1">
    <linux:dependency entity_check="none satisfy">atd.service</linux:dependency>
  </linux:systemdunitdependency_state>

</def-group>


text:
"""
Mercurial-related tasks.
"""

__all__ = ["BundleMercurialRepository"]

import os
import subprocess
from abc import abstractmethod

import luigi

from law.task.base import Task
from law.target.file import get_path
from law.target.local import LocalFileTarget
from law.parameter import NO_STR, CSVParameter
from law.decorator import log
from law.util import rel_path, interruptable_popen

class BundleMercurialRepository(Task):

    task_namespace = "law.mercurial"

    exclude_files = CSVParameter(default=(), description="patterns of files to exclude, default: "
        "()")
    include_files = CSVParameter(default=(), description="patterns of files to force-include, "
        "takes precedence over .hgignore, default: ()")
    custom_checksum = luigi.Parameter(default=NO_STR, description="a custom checksum to use, "
        "default: NO_STR")

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

        self._checksum = None

    @abstractmethod
    def get_repo_path(self):
        return

    @property
    def checksum(self):
        if self.custom_checksum != NO_STR:
            return self.custom_checksum

        if self._checksum is None:
            checksum_script = rel_path(__file__, "scripts", "repository_checksum.sh")
            cmd = [checksum_script, self.get_repo_path()]

            code, out, _ = interruptable_popen(cmd, stdout=subprocess.PIPE)
            if code != 0:
                raise Exception("repository checksum calculation failed")

            self._checksum = out.strip()

        return self._checksum

    def output(self):
        repo_base = os.path.basename(self.get_repo_path())
        return LocalFileTarget("{}_{}.tgz".format(repo_base, self.checksum))

    @log
    def run(self):
        with self.output().localize("w") as tmp:
            self.bundle(tmp.path)

    def bundle(self, dst_path):
        bundle_script = rel_path(__file__, "scripts", "bundle_repository.sh")
        cmd = [bundle_script, self.get_repo_path(), get_path(dst_path)]
        cmd += [" ".join(self.exclude_files)]
        cmd += [" ".join(self.include_files)]

        code = interruptable_popen(cmd, executable="/bin/bash")[0]
        if code != 0:
            raise Exception("repository bundling failed")


text:
/* @test
 * @bug 4521942
 * @summary Ensure that InputStreamReaders work properly
 *          when the underlying byte stream times out
 */

import java.net.*;
import java.io.*;

public class StreamTimeout {

    private static PrintStream log = System.err;

    private static String charset = "US-ASCII";

    private static Object lock = new Object();
    private static synchronized void waitABit(int millisec) {
        synchronized(lock) {
            try {
                lock.wait(millisec);
            } catch (InterruptedException e) {
                //ignore
            }
        }
    }

    private static class Client extends Thread {
        public void run() {
            try {
                Socket so = new Socket("127.0.0.1", 22222);
                Writer wr = new OutputStreamWriter(so.getOutputStream(),
                                                   charset);
                wr.write("ab");
                wr.flush();
            } catch (IOException x) {
                log.print("Unexpected exception in writer: ");
                x.printStackTrace();
                System.exit(1);
            }
        }
    }

    private static void gobble(InputStream is, Reader rd,
                               int ec, boolean force)
        throws Exception
    {
        int a = is.available();
        boolean r = rd.ready();
        log.print("" + a + " bytes available, "
                  + "reader " + (r ? "" : "not ") + "ready");
        if (!r && !force) {
            log.println();
            return;
        }
        int c;
        try {
            c = rd.read();
        } catch (InterruptedIOException x) {
            log.println();
            throw x;
        }
        log.println(", read() ==> "
                    + (c >= 0 ? ("'" + (char)c + "'" ): "EOF"));
        if (c != ec)
            throw new Exception("Incorrect value read: Expected "
                                + ec + ", read " + (char)c);
    }

    public static void main(String[] args) throws Exception {

        if (args.length > 0)
            charset = args[0];

        ServerSocket ss = new ServerSocket(22222);
        Thread cl = new Client();
        cl.start();
        Socket s = ss.accept();
        s.setSoTimeout(150);
        InputStream is = s.getInputStream();
        Reader rd = new InputStreamReader(is, charset);

        while (is.available() <= 0)
            Thread.yield();

        gobble(is, rd, 'a', false);
        gobble(is, rd, 'b', false);
        gobble(is, rd, -1, false);

        boolean caught = false;
        try {
            gobble(is, rd, -1, true);
        } catch (InterruptedIOException e) {
            log.println("Read timed out, as expected");
            caught = true;
        }
        if (!caught) {
            log.println("Read did not time out, test inapplicable");
            return;
        }

        caught = false;
        try {
            gobble(is, rd, -1, true);
        } catch (InterruptedIOException x) {
            log.println("Second read timed out, as expected");
            caught = true;
        }
        if (!caught)
            throw new Exception("Second read completed");

    }

}


text:
package pl.kwarda.test.hellow;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;

import java.util.Date;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ((TextView)findViewById(R.id.details)).setText(new Date(System.currentTimeMillis()).toString());

    }

    public void goNext(View view) {
        startActivity(new Intent(this,LoginActivity.class));
    }
}


text:
bool UCSDKObserver::OnNotification(void* _item)
{
	if(NULL == _item)
	{
		return false;
	}

	ConversationMgr* pConvMgr = UCCallManager::Instance().GetConvMgr();
	if(NULL == pConvMgr)
	{
		return false;
	}

	if(pConvMgr->HandleConversationNotify(_item))
	{
		return true;
	}
	else
	{
		return false;
	}
}


text:
$listjs

	<form  method="POST" name="myform" action="watermark.php?anyid={$anyid}&lang=$lang" target="_self">
	<input type="hidden" name="action" value="do"/>

{$lang_batchtips36}{$lang_batchtips37}

{$lang_batchtips38}{$lang_marks}

		<select name="class1" id="class1select" class="noselect" onChange="changelocation1(document.myform.class1.options[document.myform.class1.selectedIndex].value,1)">
		<option value="-1">{$lang_modClass1}</option>

<option  value="$val1[id]" $class1[$k]>$val1[name]</option>

		</select>
		<select name="class2" id="class2select" onChange="changelocation1(document.myform.class2.options[document.myform.class2.selectedIndex].value,2)">
		<option value=0>{$lang_modClass2}</option>
		</select>
		<select name="class3" id="class3select" onChange="">
		<option value=0>{$lang_modClass3}</option>
		</select>
		{$lang_batchtips39}

			<input type="button" name="button" value="{$lang_batchtips40}" class="submit" onclick="return batch('csv')"/>
			{$lang_batchtips41}

	</form>

{$lang_batchtips42}{$lang_batchtips43}

	<input name="met_upsql" type="file" id="file_upload" />

{$lang_batchtips45}

<form  method="POST" name="csv" action="csv.php?lang=$lang" target="_self">
	<input type="hidden" name="class1" id="csvclass1" value="-1"/>
	<input type="hidden" name="class2" id="csvclass2" value="-1"/>
	<input type="hidden" name="class3" id="csvclass3" value="-1"/>
	<input type="hidden" name="action" value="do"/>
 </form>

$foot


text:
#region Copyright and license
//
// SCARF - Security Audit, Access and Action Logging
// Copyright (c) 2014 ReBuildAll Solutions Ltd
//
// Author:
//    Lenard Gunda
//
// Licensed under MIT license, see included LICENSE file for details
#endregion

using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using Scarf.Configuration;
using Scarf.Tests.Infrastructure;
using Scarf.WebApi;

namespace Scarf.Tests.WebApi
{
    [TestClass]
    public class LogApiAccessAttributeTests : ScarfApiLoggingAttributeTestBase<LogApiAccessAttribute>
    {
        [ClassInitialize]
        public static void InitializeClass(TestContext ctx)
        {
            InitTests();
            var accessElementMock = new Mock<AccessElement>();
            accessElementMock.SetupGet(a => a.Enabled).Returns(true);
            _scarfSectionMock.SetupGet(s => s.Access).Returns(accessElementMock.Object);
        }

        [TestMethod]
        public void Access()
        {
            using (IScarfContext context = ScarfLogging.BeginInlineContext())
            {
                var attribute = new LogApiAccessAttribute(MessageType.AccessRead);
                BeforeAction(attribute);
                AfterAction(attribute);
            }

            Assert.AreEqual(1, dataSource.Messages.Count);
        }

    }
}


text:
/*
 *
 * UsersPage reducer
 *
 */

import { fromJS } from 'immutable';
import {
  DEFAULT_ACTION,
} from './constants';

const initialState = fromJS({});

function usersPageReducer(state = initialState, action) {
  switch (action.type) {
    case DEFAULT_ACTION:
      return state;
    default:
      return state;
  }
}

export default usersPageReducer;


text:
@implementation SafetyPlanFinishedController

-(void) configureFromContent {
	[super configureFromContent];
    [[iStressLessAppDelegate instance] setSetting:@"finishedSafetyPlan" to:@"true"];
}

-(void) buttonPressed:(UIButton *)button {
	if (button.tag >= BUTTON_ADVANCE_EXERCISE) {
        NSManagedObject *parent = [[iStressLessAppDelegate instance] getContentWithName:@"safetyPlan"];
        NSManagedObject *child = [self getChildContentWithName:@"@subsequent" forContent:parent];
        ContentViewController *cvc = [[iStressLessAppDelegate instance] getContentControllerForObject:child];
        ((BaseExerciseController*)cvc).exerciseContent = self.exerciseContent;
        [self.masterController pushViewControllerAndRemoveAllNonRootPrevious:cvc];
    }
}

@end

#endif


text:
package cmds

import (
	"fmt"
	"os"
	"strings"

	vp "github.com/shyang107/go-twinvoices"
	util "github.com/shyang107/gout"
	"github.com/urfave/cli"
)

// RecoveryCommand represents the init command
func RecoveryCommand() cli.Command {
	return cli.Command{
		Name:        "recovery",
		Aliases:     []string{"r"},
		Usage:       "Empty and recovery the table of database",
		Description: `Empty the tables of inveoices and details, and recover them from filebunker`,
		Action:      recoveryAction,
	}
}

func droptables() {
	vp.Connectdb()

	if vp.DB.HasTable(&vp.Invoice{}) && vp.DB.HasTable(&vp.Detail{}) {
		util.Glog.Debugf("♲  Drop the tables %q and %q ...",
			vp.Invoice{}.TableName(), vp.Detail{}.TableName())
		vp.DB.DropTable(&vp.Invoice{}, &vp.Detail{})
	}

	util.Glog.Debugf("♲  Recreate the tables %q and %q ...",
		vp.Invoice{}.TableName(), vp.Detail{}.TableName())
	vp.DB.AutoMigrate(&vp.Invoice{}, &vp.Detail{})
	vp.DB.Model(&vp.Invoice{}).Related(&vp.Detail{}, "uin")
}

func recoveryAction(c *cli.Context) error {
	checkVerbose(c)

	util.DebugPrintCaller()

	droptables()

	fbc := vp.GetAllOriginalDataFromDB()

	ch := make(chan string)
	for _, f := range *fbc {

		go func(f *vp.FileBunker) {
			util.Glog.Infof("\n%s", f.GetArgsTable("", 0))
			// util.Glog.Debugf("%v\n", string(f.Contents))

			var vslice vp.InvoiceCollection
			var dslice vp.DetailCollection
			var cb util.ReadLinesCallback = func(idx int, line string) (stop bool) {
				// if f.Encoding == "big-5" {
				// line = vp.Big5ToUtf8(line)
				// }
				line = vp.Big5ToUtf8(line)
				recs := strings.Split(line, "|")
				head := recs[0]
				switch head {
				case "M": // invoice
					pinv := vp.UnmarshalCSVInvoice(recs)
					vslice.Add(pinv)
				case "D": // deltail of invoice
					pdet := vp.UnmarshalCSVDetail(recs)
					dslice.Add(pdet)
				}
				return
			}
			util.ReadLines(f.Contents, cb)

			vslice.Combine(&dslice)
			// util.Glog.Infof("♲  Invoices list:\n%s", vslice.GetInvoicesTable())
			vslice.AddToDB()

			ch <- fmt.Sprintf("* ch: ending %q", f.Name)
		}(f)
	}

	for range *fbc {
		fmt.Println(<-ch)
		// util.Glog.Info(<-ch)
	}

	os.Exit(0)
	return nil
}


text:
package com.facebook.buck.parser;

import com.facebook.buck.log.Logger;
import com.facebook.buck.model.BuildTarget;
import com.facebook.buck.model.BuildTargetException;
import com.facebook.buck.model.UnflavoredBuildTarget;
import com.facebook.buck.parser.thrift.BuildFileEnvProperty;
import com.facebook.buck.parser.thrift.RemoteDaemonicCellState;
import com.facebook.buck.rules.Cell;
import com.facebook.buck.util.MoreCollectors;
import com.facebook.buck.util.ObjectMappers;
import com.facebook.buck.util.concurrent.AutoCloseableLock;
import com.facebook.buck.util.concurrent.AutoCloseableReadWriteUpdateLock;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Preconditions;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.MapDifference;
import com.google.common.collect.Maps;
import com.google.common.collect.SetMultimap;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicReference;
import javax.annotation.concurrent.GuardedBy;

class DaemonicCellState {

  private static final Logger LOG = Logger.get(DaemonicCellState.class);

  private class CacheImpl<T> implements PipelineNodeCache.Cache<BuildTarget, T> {

    @GuardedBy("rawAndComputedNodesLock")
    public final ConcurrentMapCache<BuildTarget, T> allComputedNodes =
        new ConcurrentMapCache<>(parsingThreads);

    @Override
    public Optional<T> lookupComputedNode(Cell cell, BuildTarget target)
        throws BuildTargetException {
      try (AutoCloseableLock readLock = rawAndComputedNodesLock.readLock()) {
        return Optional.ofNullable(allComputedNodes.getIfPresent(target));
      }
    }

    @Override
    public T putComputedNodeIfNotPresent(Cell cell, BuildTarget target, T targetNode)
        throws BuildTargetException {
      try (AutoCloseableLock writeLock = rawAndComputedNodesLock.writeLock()) {
        T updatedNode = allComputedNodes.putIfAbsentAndGet(target, targetNode);
        Preconditions.checkState(
            allRawNodeTargets.contains(target.getUnflavoredBuildTarget()),
            "Added %s to computed nodes, which isn't present in raw nodes",
            target);
        if (updatedNode.equals(targetNode)) {
          targetsCornucopia.put(target.getUnflavoredBuildTarget(), target);
        }
        return updatedNode;
      }
    }
  }

  private final Path cellRoot;
  private final Optional<String> cellCanonicalName;
  private AtomicReference<Cell> cell;

  @GuardedBy("rawAndComputedNodesLock")
  private final SetMultimap<Path, Path> buildFileDependents;

  @GuardedBy("rawAndComputedNodesLock")
  private final SetMultimap<UnflavoredBuildTarget, BuildTarget> targetsCornucopia;

  @GuardedBy("rawAndComputedNodesLock")
  private final Map<Path, ImmutableMap<String, Optional<String>>> buildFileEnv;

  @GuardedBy("rawAndComputedNodesLock")
  private final ConcurrentMapCache<Path, ImmutableSet<Map<String, Object>>> allRawNodes;
  // Tracks all targets in `allRawNodes`.  Used to verify that every target in `allComputedNodes`
  // is also in `allRawNodes`, as we use the latter for bookkeeping invalidations.
  @GuardedBy("rawAndComputedNodesLock")
  private final Set<UnflavoredBuildTarget> allRawNodeTargets;

  @GuardedBy("rawAndComputedNodesLock")
  private final ConcurrentMap<Class<?>, CacheImpl<?>> typedNodeCaches;

  private final AutoCloseableReadWriteUpdateLock rawAndComputedNodesLock;
  private final int parsingThreads;

  DaemonicCellState(Cell cell, int parsingThreads) {
    this.cell = new AtomicReference<>(cell);
    this.parsingThreads = parsingThreads;
    this.cellRoot = cell.getRoot();
    this.cellCanonicalName = cell.getCanonicalName();
    this.buildFileDependents = HashMultimap.create();
    this.targetsCornucopia = HashMultimap.create();
    this.buildFileEnv = new HashMap<>();
    this.allRawNodes = new ConcurrentMapCache<>(parsingThreads);
    this.allRawNodeTargets = new HashSet<>();
    this.typedNodeCaches = Maps.newConcurrentMap();
    this.rawAndComputedNodesLock = new AutoCloseableReadWriteUpdateLock();
  }

  // TODO(mzlee): Only needed for invalidateBasedOn which does not have access to cell metadata
  Cell getCell() {
    return Preconditions.checkNotNull(cell.get());
  }

  Path getCellRoot() {
    return cellRoot;
  }

  @SuppressWarnings("unchecked")
  public <T> CacheImpl<T> getOrCreateCache(Class<T> type) {
    try (AutoCloseableLock updateLock = rawAndComputedNodesLock.updateLock()) {
      CacheImpl<?> cache = typedNodeCaches.get(type);
      if (cache == null) {
        try (AutoCloseableLock writeLock = rawAndComputedNodesLock.writeLock()) {
          cache = new CacheImpl<>();
          typedNodeCaches.put(type, cache);
        }
      }
      return (CacheImpl<T>) cache;
    }
  }

  @SuppressWarnings("unchecked")
  public <T> CacheImpl<T> getCache(Class<T> type) {
    try (AutoCloseableLock readLock = rawAndComputedNodesLock.readLock()) {
      return (CacheImpl<T>) typedNodeCaches.get(type);
    }
  }

  Optional<ImmutableSet<Map<String, Object>>> lookupRawNodes(Path buildFile) {
    try (AutoCloseableLock readLock = rawAndComputedNodesLock.readLock()) {
      return Optional.ofNullable(allRawNodes.getIfPresent(buildFile));
    }
  }

  ImmutableSet<Map<String, Object>> putRawNodesIfNotPresentAndStripMetaEntries(
      final Path buildFile,
      final ImmutableSet<Map<String, Object>> withoutMetaIncludes,
      final ImmutableSet<Path> dependentsOfEveryNode,
      ImmutableMap<String, Optional<String>> env) {
    try (AutoCloseableLock writeLock = rawAndComputedNodesLock.writeLock()) {
      ImmutableSet<Map<String, Object>> updated =
          allRawNodes.putIfAbsentAndGet(buildFile, withoutMetaIncludes);
      for (Map<String, Object> node : updated) {
        allRawNodeTargets.add(
            RawNodeParsePipeline.parseBuildTargetFromRawRule(
                cellRoot, cellCanonicalName, node, buildFile));
      }
      buildFileEnv.put(buildFile, env);
      if (updated == withoutMetaIncludes) {
        // We now know all the nodes. They all implicitly depend on everything in
        // the "dependentsOfEveryNode" set.
        for (Path dependent : dependentsOfEveryNode) {
          buildFileDependents.put(dependent, buildFile);
        }
      }
      return updated;
    }
  }

  int invalidatePath(Path path) {
    try (AutoCloseableLock writeLock = rawAndComputedNodesLock.writeLock()) {
      int invalidatedRawNodes = 0;
      ImmutableSet<Map<String, Object>> rawNodes = allRawNodes.getIfPresent(path);
      if (rawNodes != null) {
        // Increment the counter
        invalidatedRawNodes = rawNodes.size();
        for (Map<String, Object> rawNode : rawNodes) {
          UnflavoredBuildTarget target =
              RawNodeParsePipeline.parseBuildTargetFromRawRule(
                  cellRoot, cellCanonicalName, rawNode, path);
          LOG.debug("Invalidating target for path %s: %s", path, target);
          for (CacheImpl<?> cache : typedNodeCaches.values()) {
            cache.allComputedNodes.invalidateAll(targetsCornucopia.get(target));
          }
          targetsCornucopia.removeAll(target);
          allRawNodeTargets.remove(target);
        }
        allRawNodes.invalidate(path);
      }

      // We may have been given a file that other build files depend on. Iteratively remove those.
      Iterable<Path> dependents = buildFileDependents.get(path);
      LOG.debug("Invalidating dependents for path %s: %s", path, dependents);
      for (Path dependent : dependents) {
        if (dependent.equals(path)) {
          continue;
        }
        invalidatedRawNodes += invalidatePath(dependent);
      }
      buildFileDependents.removeAll(path);
      buildFileEnv.remove(path);

      return invalidatedRawNodes;
    }
  }

  Optional<MapDifference<String, String>> invalidateIfEnvHasChanged(Cell cell, Path buildFile) {
    // Invalidate if env vars have changed.
    ImmutableMap<String, Optional<String>> usedEnv;
    try (AutoCloseableLock readLock = rawAndComputedNodesLock.readLock()) {
      usedEnv = buildFileEnv.get(buildFile);
    }
    if (usedEnv == null) {
      this.cell.set(cell);
      return Optional.empty();
    }
    for (Map.Entry<String, Optional<String>> ent : usedEnv.entrySet()) {
      Optional<String> value =
          Optional.ofNullable(cell.getBuckConfig().getEnvironment().get(ent.getKey()));
      if (!value.equals(ent.getValue())) {
        LOG.verbose("invalidating for env change: %s (%s != %s)", buildFile, value, ent.getValue());
        invalidatePath(buildFile);
        this.cell.set(cell);
        return Optional.of(
            Maps.difference(
                value.map(v -> ImmutableMap.of(ent.getKey(), v)).orElse(ImmutableMap.of()),
                ent.getValue()
                    .map(v -> ImmutableMap.of(ent.getKey(), v))
                    .orElse(ImmutableMap.of())));
      }
    }
    return Optional.empty();
  }

  private Map<String, String> getAllRawNodesForSerialisation() throws IOException {
    Map<String, String> result = new HashMap<>();
    Path root = getCellRoot();
    ObjectMapper objectMapper = new ObjectMapper();
    for (Path path : allRawNodes.keySet()) {
      ImmutableSet<Map<String, Object>> v = allRawNodes.getIfPresent(path);
      if (v != null) {
        result.put(root.relativize(path).toString(), objectMapper.writeValueAsString(v));
      }
    }
    return result;
  }

  private Map<String, List<String>> getBuildFileDependentsForSerialisation() {
    Map<String, List<String>> result = new HashMap<>();
    Path root = getCellRoot();
    Map<Path, Collection<Path>> view = buildFileDependents.asMap();
    for (Path path : view.keySet()) {
      Collection<Path> paths = view.get(path);
      if (paths != null) {
        ImmutableList<String> pathList =
            paths
                .stream()
                .map(v -> root.relativize(v).toString())
                .collect(MoreCollectors.toImmutableList());
        result.put(root.relativize(path).toString(), pathList);
      }
    }

    return result;
  }

  private Map<String, Map<String, BuildFileEnvProperty>> getBuildFileEnvForSerialisation() {
    Map<String, Map<String, BuildFileEnvProperty>> result = new HashMap<>();
    for (Path path : buildFileEnv.keySet()) {
      ImmutableMap.Builder<String, BuildFileEnvProperty> buildFileEnvValuesMapBuilder =
          ImmutableMap.builder();
      ImmutableMap<String, Optional<String>> values = buildFileEnv.get(path);
      if (values != null) {
        values.forEach(
            (k, v) -> {
              BuildFileEnvProperty prop = new BuildFileEnvProperty();
              v.ifPresent(prop::setValue);
              buildFileEnvValuesMapBuilder.put(k, prop);
            });
      }
      result.put(path.toString(), buildFileEnvValuesMapBuilder.build());
    }

    return result;
  }

  RemoteDaemonicCellState serialise() throws IOException {
    RemoteDaemonicCellState result = new RemoteDaemonicCellState();
    try (AutoCloseableLock readLock = rawAndComputedNodesLock.readLock()) {
      result.allRawNodesJsons = getAllRawNodesForSerialisation();
      result.buildFileDependents = getBuildFileDependentsForSerialisation();
      result.buildFileEnv = getBuildFileEnvForSerialisation();
    }
    return result;
  }

  static DaemonicCellState deserialise(
      RemoteDaemonicCellState remote, Cell cell, int parsingThreads) throws IOException {
    DaemonicCellState daemonicCellState = new DaemonicCellState(cell, parsingThreads);
    Path root = cell.getRoot();
    for (String pathString : remote.buildFileDependents.keySet()) {
      Path key = root.resolve(pathString);
      remote
          .buildFileDependents
          .get(pathString)
          .forEach(
              valuePathString -> {
                daemonicCellState.buildFileDependents.put(key, root.resolve(valuePathString));
              });
    }

    for (String pathString : remote.buildFileEnv.keySet()) {
      Path key = Paths.get(pathString);
      Map<String, BuildFileEnvProperty> remoteValues = remote.buildFileEnv.get(pathString);
      ImmutableMap.Builder<String, Optional<String>> builder = ImmutableMap.builder();
      for (String k : remoteValues.keySet()) {
        BuildFileEnvProperty prop = remoteValues.get(k);
        if (prop != null && !prop.isSetValue()) {
          builder.put(k, Optional.empty());
        } else {
          builder.put(k, Optional.of(prop.value));
        }
      }
      daemonicCellState.buildFileEnv.put(key, builder.build());
    }

    for (String pathString : remote.allRawNodesJsons.keySet()) {
      String json = remote.allRawNodesJsons.get(pathString);
      ImmutableSet<Map<String, Object>> deserialisedRawNodes =
          ObjectMappers.readValue(json, new TypeReference<ImmutableSet<Map<String, Object>>>() {});
      Path key = root.resolve(pathString);
      daemonicCellState.allRawNodes.putIfAbsentAndGet(key, deserialisedRawNodes);
      deserialisedRawNodes.forEach(
          rawNode -> {
            daemonicCellState.allRawNodeTargets.add(
                UnflavoredBuildTarget.of(
                    root,
                    cell.getCanonicalName(),
                    "//" + rawNode.get("buck.base_path"),
                    (String) rawNode.get("name")));
          });
    }

    return daemonicCellState;
  }
}


text:
package com.devinci.lib.crash;

import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;

/**
 * Interface with generic methods for crash reporting.
 */
public interface CrashReporting {

  void initialize(@NonNull Context context);

  void sendException(@NonNull Throwable throwable);

  @NonNull CrashReporting addExtra(@NonNull String key, boolean extra);

  @NonNull CrashReporting addExtra(@NonNull String key, double extra);

  @NonNull CrashReporting addExtra(@NonNull String key, float extra);

  @NonNull CrashReporting addExtra(@NonNull String key, int extra);

  @NonNull CrashReporting addExtra(@NonNull String key, long extra);

  @NonNull CrashReporting addExtra(@NonNull String key, @Nullable String extra);

  @NonNull CrashReporting setUser(@Nullable String user);
}


text:
import * as Promise from 'bluebird';

import 'isomorphic-fetch';

import { JWT } from './jwt';
import { Utils } from './utils';
import { AppConfig } from './config';
import { dedupe } from './utils/dedupe-calls';
import { UrlConfig } from './urlconfig';
import { prefetchdata } from './scopes';
import { loadingIndicator } from './LoadingIndicator';
import { capabilityAugmenter } from './capability/index';

let refreshToken: string | null = null;

function isGetRequest(fetchOptions: RequestInit): boolean {
    return !fetchOptions || !fetchOptions.method || 'get'.localeCompare(fetchOptions.method) === 0;
}
export namespace FetchFunctions {
    export interface RawFetchOpts {
        onSuccess?: (success: A) => B;
        onError?: (error: A) => B;
        fetchOptions?: RequestInit;
        disableDedupe?: boolean;
        disableLoadingIndicator?: boolean;
        ignoreRefreshHeader?: boolean;
    }
}
export namespace Fetch {
    export interface FetchOpts {
        onSuccess?: (success: A) => B;
        onError?: (error: A) => B;
        fetchOptions?: RequestInit;
        disableCapabilities?: boolean;
        disableLoadingIndicator?: boolean;
        ignoreRefreshHeader?: boolean;
    }
}

export class FetchFunctions {
    /**
     * Ensures the URL starts with jenkins path if not an absolute URL.
     * @param url
     * @returns {string}
     */
    static prefixUrl(url: string): string {
        if (url.indexOf('http') === 0) {
            return url;
        }

        if (UrlConfig.getJenkinsRootURL() !== '' && !url.startsWith(UrlConfig.getJenkinsRootURL())) {
            return `${UrlConfig.getJenkinsRootURL()}${url}`;
        }

        return url;
    }

    static checkRefreshHeader(response: Response): Response {
        const _refreshToken = response.headers.get('X-Blueocean-Refresher');
        // No token in response, lets just ignore.
        if (!_refreshToken) {
            return response;
        }

        // First time we have seen a refresh token, early exit.
        if (!refreshToken) {
            refreshToken = _refreshToken;
            return response;
        }

        // We need to refresh the page now!
        if (refreshToken !== _refreshToken) {
            Utils.refreshPage();
            throw new Error('refreshing apge');
        }
        return response;
    }

    /**
     * This method checks for for 2XX http codes. Throws error it it is not.
     * This should only be used if not using fetch or fetchJson.
     */
    static checkStatus(response: Response): Response {
        if (response.status >= 300 || response.status < 200) {
            const message = `fetch failed: ${response.status} for ${response.url}`;
            const error: any = new Error(message); //FIXME
            error.response = response;
            throw error;
        }
        return response;
    }

    static stopLoadingIndicator(response: Response): Response {
        loadingIndicator.hide();
        return response;
    }

    /**
     * Adds same-origin option to the fetch.
     */
    static sameOriginFetchOption(options: RequestInit = {}): RequestInit {
        const newOpts: RequestInit = Utils.clone(options);
        newOpts.credentials = newOpts.credentials || 'same-origin';
        return newOpts;
    }

    /**
     * Enhances the fetchOptions with the JWT bearer token. Will only be needed
     * if not using fetch or fetchJson.
     */
    static jwtFetchOption(token: string, options: RequestInit = {}): RequestInit {
        const newOpts: RequestInit = Utils.clone(options);
        newOpts.headers = newOpts.headers || {};
        newOpts.headers['Authorization'] = newOpts.headers['Authorization'] || `Bearer ${token}`;
        return newOpts;
    }

    /**
     * REturns the json body from the response. It is only needed if
     * you are using FetchUtils.fetch
     *
     * Usage:
     * FetchUtils.fetch(..).then(FetchUtils.parseJSON)
     */
    static parseJSON<T>(response: Response): Promise<T> {
        return (
            response
                .json()
                // FIXME: workaround for status=200 w/ empty response body that causes error in Chrome
                // server should probably return HTTP 204 instead
                .catch(error => {
                    if (error.message.indexOf('Unexpected end of JSON input') !== -1) {
                        return {};
                    }
                    throw error;
                })
        );
    }

    /* eslint-disable no-param-reassign */
    /**
     * Parses the response body for the error generated in checkStatus.
     */
    static parseErrorJson(error: any): any {
        return error.response.json().then(
            body => {
                error.responseBody = body;
                throw error;
            },
            () => {
                error.responseBody = null;
                throw error;
            }
        );
    }
    /* eslint-enable no-param-reassign */

    /**
     * Error function helper to log errors to console.
     *
     * Usage;
     * fetchJson(..).catch(FetchUtils.consoleError)
     */
    static consoleError(error: any): void {
        console.error(error); // eslint-disable-line no-console
    }

    /**
     * Error function helper to call a callback on a rejected promise.
     * if callback is null, log to console). Use .catch() if you know it
     * will not be null though.
     *
     * Usage;
     * fetchJson(..).catch(FetchUtils.onError(error => //do something)
     */
    static onError(errorFunc: (any) => any): (any) => void {
        return error => {
            if (errorFunc) {
                errorFunc(error);
            } else {
                FetchFunctions.consoleError(error);
            }
        };
    }

    /**
     * Raw fetch that returns the json body.
     *
     * This method is semi-private, under normal conditions it should not be
     * used as it does not include the JWT bearer token
     *
     * @param {string} url - The URL to fetch from.
     * @param {Object} [options]
     * @param {function} [options.onSuccess] - Optional callback success function.
     * @param {function} [options.onError] - Optional error callback.
     * @param {Object} [options.fetchOptions] - Optional isomorphic-fetch options.
     * @param {boolean} [options.disableDedupe] - Optional flag to disable dedupe for this request.
     * @param {boolean} [options.disableLoadingIndicator] - Optional flag to disable loading indicator for this request.
     * @returns JSON body
     */
    static rawFetchJSON(
        url,
        { onSuccess, onError, fetchOptions, disableDedupe, disableLoadingIndicator, ignoreRefreshHeader }: FetchFunctions.RawFetchOpts = {}
    ) {
        const request = () => {
            let future = getPrefetchedDataFuture(url); // eslint-disable-line no-use-before-define

            if (!disableLoadingIndicator) {
                loadingIndicator.show();
            }

            if (!future) {
                future = fetch(url, FetchFunctions.sameOriginFetchOption(fetchOptions));

                if (!ignoreRefreshHeader) {
                    future = future.then(FetchFunctions.checkRefreshHeader);
                }

                future = future.then(FetchFunctions.checkStatus).then(FetchFunctions.parseJSON, FetchFunctions.parseErrorJson);

                if (!disableLoadingIndicator) {
                    future = future.then(FetchFunctions.stopLoadingIndicator, err => {
                        FetchFunctions.stopLoadingIndicator(err);
                        throw err;
                    });
                }
            } else if (!disableLoadingIndicator) {
                loadingIndicator.hide();
            }
            if (onSuccess) {
                return future.then(onSuccess).catch(FetchFunctions.onError(onError));
            }

            return future;
        };
        if (disableDedupe || !isGetRequest(fetchOptions)) {
            return request();
        }

        return dedupe(url, request);
    }
    /**
     * Raw fetch.
     *
     * This method is semi-private, under normal conditions it should not be
     * used as it does not include the JWT bearer token
     *
     * @param {string} url - The URL to fetch from.
     * @param {Object} [options]
     * @param {function} [options.onSuccess] - Optional callback success function.
     * @param {function} [options.onError] - Optional error callback.
     * @param {Object} [options.fetchOptions] - Optional isomorphic-fetch options.
     * @param {boolean} [options.disableDedupe] - Optional flag to disable dedupe for this request.
     * @param {boolean} [options.disableLoadingIndicator] - Optional flag to disable loading indicator for this request.
     * @returns fetch response
     */
    static rawFetch(url, { onSuccess, onError, fetchOptions, disableDedupe, disableLoadingIndicator, ignoreRefreshHeader }: FetchFunctions.RawFetchOpts = {}) {
        const request = () => {
            let future = getPrefetchedDataFuture(url); // eslint-disable-line no-use-before-define
            if (!future) {
                if (!disableLoadingIndicator) {
                    loadingIndicator.show();
                }

                future = fetch(url, FetchFunctions.sameOriginFetchOption(fetchOptions));

                if (!ignoreRefreshHeader) {
                    future = future.then(FetchFunctions.checkRefreshHeader);
                }

                future = future.then(FetchFunctions.checkStatus);

                if (!disableLoadingIndicator) {
                    future = future.then(FetchFunctions.stopLoadingIndicator, err => {
                        FetchFunctions.stopLoadingIndicator(err);
                        throw err;
                    });
                }
            }

            if (onSuccess) {
                return future.then(onSuccess).catch(FetchFunctions.onError(onError));
            }
            return future;
        };

        if (disableDedupe || !isGetRequest(fetchOptions)) {
            return request();
        }

        return dedupe(url, request);
    }
}

export class Fetch {
    /**
     * Fetch JSON data.
     *

     * Utility function that can be mocked for testing.
     *
     * @param {string} url - The URL to fetch from.
     * @param {Object} [options]
     * @param {function} [options.onSuccess] - Optional callback success function.
     * @param {function} [options.onError] - Optional error callback.
     * @param {Object} [options.fetchOptions] - Optional isomorphic-fetch options.
     * @returns JSON body.
     */
    static fetchJSON(url, { onSuccess, onError, fetchOptions, disableCapabilities, disableLoadingIndicator, ignoreRefreshHeader }: Fetch.FetchOpts = {}) {
        const fixedUrl = FetchFunctions.prefixUrl(url);
        let future;
        if (!AppConfig.isJWTEnabled()) {
            future = FetchFunctions.rawFetchJSON(fixedUrl, { onSuccess, onError, fetchOptions, disableLoadingIndicator, ignoreRefreshHeader });
        } else {
            future = JWT.getToken().then(token =>
                FetchFunctions.rawFetchJSON(fixedUrl, {
                    onSuccess,
                    onError,
                    fetchOptions: FetchFunctions.jwtFetchOption(token, fetchOptions),
                })
            );
        }

        if (!disableCapabilities) {
            return future.then(data => capabilityAugmenter.augmentCapabilities(Utils.clone(data)));
        }

        return future;
    }

    /**
     * Fetch data.
     *

     * Utility function that can be mocked for testing.
     *
     * @param {string} url - The URL to fetch from.
     * @param {Object} [options]
     * @param {function} [options.onSuccess] - Optional callback success function.
     * @param {function} [options.onError] - Optional error callback.
     * @param {Object} [options.fetchOptions] - Optional isomorphic-fetch options.
     * @returns fetch body.
     */
    static fetch(url, { onSuccess, onError, fetchOptions, disableLoadingIndicator, ignoreRefreshHeader }: Fetch.FetchOpts = {}) {
        const fixedUrl = FetchFunctions.prefixUrl(url);

        if (!AppConfig.isJWTEnabled()) {
            return FetchFunctions.rawFetch(fixedUrl, { onSuccess, onError, fetchOptions, disableLoadingIndicator, ignoreRefreshHeader });
        }

        return JWT.getToken().then(token =>
            FetchFunctions.rawFetch(fixedUrl, {
                onSuccess,
                onError,
                fetchOptions: FetchFunctions.jwtFetchOption(token, fetchOptions),
            })
        );
    }
}

function trimRestUrl(url) {
    const REST_PREFIX = 'blue/rest/';
    const prefixOffset = url.indexOf(REST_PREFIX);

    if (prefixOffset !== -1) {
        return url.substring(prefixOffset);
    }

    return url;
}

function getPrefetchedDataFuture(url): Promise<Response> | undefined {
    const trimmedUrl = trimRestUrl(url);

    for (const prop in prefetchdata) {
        if (prefetchdata.hasOwnProperty(prop)) {
            const preFetchEntry = prefetchdata[prop];
            if (preFetchEntry.restUrl && preFetchEntry.data) {
                // If the trimmed/normalized rest URL matches the url arg supplied
                // to the function, construct a pre-resolved future object containing
                // the prefetched data as the value.
                if (trimRestUrl(preFetchEntry.restUrl) === trimmedUrl) {
                    try {
                        return Promise.resolve(JSON.parse(preFetchEntry.data));
                    } finally {
                        // Delete the preFetchEntry i.e. we only use these entries once. So, this
                        // works only for the first request for the data at that URL. Subsequent
                        // calls on that REST endpoint will result in a proper fetch. A local
                        // store needs to be used (redux/mobx etc) if you want to avoid multiple calls
                        // for the same data. This is not a caching layer/mechanism !!!
                        delete prefetchdata[prop];
                    }
                }
            }
        }
    }

    return undefined;
}


text:
//
//  LNFoundShopViewModel.h
//  TinyDay
//

//  Created by tarena46 on 16/8/13.
//  Copyright © 2016年 Icemelt. All rights reserved.
//

#import "TDBaseViewModel.h"
#import "TDNetManager.h"

@interface TDFindViewModel : TDBaseViewModel

/******  tableview  ******/
//有几个分区
@property (nonatomic,readonly)NSInteger sectionNum;
//每个分区有几行
-(NSInteger)RowForSection:(NSInteger)section;
//第一个分区数组
@property (nonatomic) NSArray<TDFindCbdsModel *> *CbdsArr;
@property (nonatomic) NSArray<TDFindThemesModel *> *themesArr;
//cell 中的图片
-(NSURL *)headerIVForSection:(NSInteger)section Row:(NSInteger)row;
-(NSString *)titleLbForSection:(NSInteger)section Row:(NSInteger)row;
-(NSString *)nameLbForSection:(NSInteger)section Row:(NSInteger)row;

/******  collectionview  ******/
@property (nonatomic,readonly)NSInteger rowCollectionNum;
-(NSURL *)imageViewForRow:(NSInteger)row;
-(NSString *)labelForRow:(NSInteger)row;
@property (nonatomic) NSArray<TDFindTagsModel *> *tagArr;

@end


text:
require File.dirname(__FILE__) + '/helper'

class TestGrit < Test::Unit::TestCase
  def setup
    @old_debug  = Grit.debug
    @old_logger = Grit.logger
    Grit.debug  = true
  end

  def teardown
    Grit.debug  = @old_debug
    Grit.logger = @old_logger
  end

  def test_uses_stdout_logger_by_default
    assert_equal STDOUT, Grit.logger.instance_variable_get(:@logdev).dev
  end

  def test_can_override_logger
    my_logger = Logger.new(io = StringIO.new)
    Grit.logger = my_logger
    assert_equal my_logger, Grit.logger
  end

  def test_logs_to_specified_logger
    Grit.logger = Logger.new(io = StringIO.new)
    Grit.log 'hi mom'
    io.rewind
    assert io.read.include?('hi mom')
  end

end


text:
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;

namespace Plethora.Test
{
    [TestClass]
    public class WildcardSearch_Test
    {
        [TestMethod]
        public void IsMatch_Empty_Match()
        {
            // Arrange
            string pattern = "";
            string text = "";

            // Action
            bool isMatch = WildcardSearch.IsMatch(text, pattern);

            // Assert
            Assert.IsTrue(isMatch);
        }

        [TestMethod]
        public void IsMatch_PatternEmpty_NoMatch()
        {
            // Arrange
            string pattern = "";
            string text = "Sample search input text";

            // Action
            bool isMatch = WildcardSearch.IsMatch(text, pattern);

            // Assert
            Assert.IsFalse(isMatch);
        }

        [TestMethod]
        public void IsMatch_NoWildcard_Match()
        {
            // Arrange
            string pattern = "Sample search input text";
            string text = "Sample search input text";

            // Action
            bool isMatch = WildcardSearch.IsMatch(text, pattern);

            // Assert
            Assert.IsTrue(isMatch);
        }

        [TestMethod]
        public void IsMatch_NoWildcard_CaseNoMatch()
        {
            // Arrange
            string pattern = "sample search input text";
            string text = "Sample search input text";

            // Action
            bool isMatch = WildcardSearch.IsMatch(text, pattern);

            // Assert
            Assert.IsFalse(isMatch);
        }

        [TestMethod]
        public void IsMatch_NoWildcard_IgnoreCase()
        {
            // Arrange
            string pattern = "sample search input text";
            string text = "Sample search input text";

            // Action
            bool isMatch = WildcardSearch.IsMatch(text, pattern, StringComparison.OrdinalIgnoreCase);

            // Assert
            Assert.IsTrue(isMatch);
        }

        [TestMethod]
        public void IsMatch_NoWildcard_NoMatch()
        {
            // Arrange
            string pattern = "mismatch";
            string text = "Sample search input text";

            // Action
            bool isMatch = WildcardSearch.IsMatch(text, pattern);

            // Assert
            Assert.IsFalse(isMatch);
        }

        [TestMethod]
        public void IsMatch_LeadingWildcard_Match()
        {
            // Arrange
            string pattern = "*text";
            string text = "Sample search input text";

            // Action
            bool isMatch = WildcardSearch.IsMatch(text, pattern);

            // Assert
            Assert.IsTrue(isMatch);
        }

        [TestMethod]
        public void IsMatch_TrailingWildcard_Match()
        {
            // Arrange
            string pattern = "Sample*";
            string text = "Sample search input text";

            // Action
            bool isMatch = WildcardSearch.IsMatch(text, pattern);

            // Assert
            Assert.IsTrue(isMatch);
        }

        [TestMethod]
        public void IsMatch_LeadingAndTrailingWildcard_Match()
        {
            // Arrange
            string pattern = "*search*";
            string text = "Sample search input text";

            // Action
            bool isMatch = WildcardSearch.IsMatch(text, pattern);

            // Assert
            Assert.IsTrue(isMatch);
        }

        [TestMethod]
        public void IsMatch_MidWildcard_Match()
        {
            // Arrange
            string pattern = "Sample*text";
            string text = "Sample search input text";

            // Action
            bool isMatch = WildcardSearch.IsMatch(text, pattern);

            // Assert
            Assert.IsTrue(isMatch);
        }

        [TestMethod]
        public void IsMatch_SuccessiveWildcard_Match()
        {
            // Arrange
            string pattern = "*search**text";
            string text = "Sample search input text";

            // Action
            bool isMatch = WildcardSearch.IsMatch(text, pattern);

            // Assert
            Assert.IsTrue(isMatch);
        }
    }
}


text:
package com.webwarp.api.teamworkpm;

class ErrorException /*extends Exception*/ {
    /* Properties */
    protected int $severity ;

    /* Methods */
    //public __construct ([ string $message = "" [, int $code = 0 [, int $severity = 1 [, string $filename = __FILE__ [, int $lineno = __LINE__ [, Exception $previous = NULL ]]]]]] )
    //final public int getSeverity ( void );

    /* Inherited methods */
    //final public string Exception::getMessage ( void )
    //final public Exception Exception::getPrevious ( void )
    //final public mixed Exception::getCode ( void )
    //final public string Exception::getFile ( void )
    //final public int Exception::getLine ( void )
    //final public array Exception::getTrace ( void )
    //final public string Exception::getTraceAsString ( void )
    //public string Exception::__toString ( void )
    //final private void Exception::__clone ( void )
}


text:
import THREE = require('three');
import com                          from '../common/WorldInfo';
import { PartitionGeometryResult }  from '../worker/WorldGeometry';

import {
  Movement,
  AddBlockArgs,
  SetBlocksArgs,
  PlayerPositionChangeListener,
  BoundScriptsChangeListener
} from '../common/Types';

export default class WorkerInterface {
  geoWorker: Worker;
  callbacks: { [id: number]: (data: any) => void } = {};

  changeListener: (data: { changes: number[] }) => void = null;
  print: (msg: string) => void = null;
  lastId = 0;
  jumping: boolean = false;

  private playerPositionChangeListener: PlayerPositionChangeListener;
  private boundScriptsChangeListener: BoundScriptsChangeListener;

  constructor() {
    this.geoWorker = new Worker('build/worker.js');

    this.geoWorker.onmessage = e => {
      if (typeof e.data.id === 'number') {
        const callback = this.callbacks[e.data.id];

        delete this.callbacks[e.data.id];

        return callback(e.data.data);
      }

      if (e.data.action === 'update') {
        if (this.changeListener) {
          this.changeListener(e.data);
        }
      }

      if (e.data.action === 'playerPositionChange') {
        if (this.playerPositionChangeListener) {
          this.playerPositionChangeListener(e.data.data);
        }
      }

      if (e.data.action === 'boundScriptsChange') {
        if (this.boundScriptsChangeListener) {
          this.boundScriptsChangeListener(e.data.data);
        }
      }

      if (e.data.action === 'print') {
        if (this.print) {
          this.print(e.data.data);
        }
      }
    };
  }

  invoke<ReturnType>(action: string, data: Object) {
    return new Promise<ReturnType>((resolve, reject) => {
      const invocation = {
        action: action,
        id: this.lastId++,
        data: data
      };

      this.callbacks[invocation.id] = resolve;

      this.geoWorker.postMessage(invocation);
    });
  }

  invokeCallback<ReturnType>(action: string, data: Object, callback: (r: ReturnType) => void) {
    const invocation = {
      action: action,
      id: this.lastId++,
      data: data
    };

    this.callbacks[invocation.id] = callback;

    this.geoWorker.postMessage(invocation);
  }

  init() {
    return this.invoke<com.WorldInfo>('init', null);
  }

  runScript(code: string, expr: boolean) {
    return this.invoke<{ result: any }>('runScript', { code, expr });
  }

  undo() {
    return this.invoke<void>('undo', null);
  }

  getBlock(pos: THREE.Vector3) {
    return this.invoke<{ type: number }>('getBlock', { pos: pos }).then((result) => {
      return result.type;
    });
  }

  setBlocks(
    start: com.IntVector3,
    end: com.IntVector3,
    type: number,
    colour: number,
    update: boolean
  ) {
    const args: SetBlocksArgs = {
      start,
      end,
      type,
      colour,
      update
    };

    return this.invoke<Object>('setBlocks', args);
  }

  addBlock(position: com.IntVector3, side: number, type: number) {
    const args: AddBlockArgs = {
      position,
      side,
      type
    };

    return this.invoke<Object>('addBlock', args);
  }

  move(movement: Movement) {
    return this.invoke<Object>('move', movement);
  }

  jump() {
    this.jumping = true;
    return this.invoke<Object>('action', { action: 'jump' });
  }

  setGravity(gravity: number) {
    return this.invoke<Object>('setGravity', { gravity });
  }

  getPartition(index: number) {
    return this.invoke<{ geo: PartitionGeometryResult }>('getPartition', { index });
  }

  registerChangeHandler(changeHandlerOptions: com.ChangeHandlerOptions, callback: (Change: any) => void) {
    return this.invokeCallback<Object>('registerChangeHandler', changeHandlerOptions, callback);
  }

  addChangeListener(listener: (data: { changes: number[] }) => void) {
    this.changeListener = listener;
  }

  rightClick() {
    return this.invoke<Object>('rightClick', null);
  }

  getMousePosition() {
    return this.invoke<Object>('getMousePosition', null);
  }

  setMousePosition(position: { pos: com.IntVector3, side: number }) {
    return this.invoke<Object>('setMousePosition', position);
  }

  executeBoundScript(index: number) {
    this.invoke<Object>('executeBoundScript', { index });
  }

  onPlayerPositionChange(listener: PlayerPositionChangeListener) {
    this.playerPositionChangeListener = listener;
  }

  onBoundScriptsChange(listener: BoundScriptsChangeListener) {
    this.boundScriptsChangeListener = listener;
  }
}


text:
SYSLOG_SOURCES = syslog_agent.c

SOURCES += $(SYSLOG_SOURCES:%.c=io/syslog/%.c)


text:
import React, { Component } from 'react';
import { Link } from 'react-router';
import axios from 'axios';

export default class Posts extends React.Component{
	constructor(props) {
		super(props);
		this.state = {
			posts: [],
		};
	}

	componentDidMount(){
		var _this = this;
			this.serverRequest = axios.get("http://360.and-a.nl/wp-json/wp/v2/posts").then(function(result) {
	      _this.setState({
	        posts: result.data
	      });
	      console.log(result.data);
	    })
	}

	render() {
	    return (

Posts!

	        {/* Don't have an ID to use for the key, URL work ok? */}
	        {this.state.posts.map(function(post) {
	          return (

	            	{post.title.rendered} - <Link to={post.acf.event_link}>Facebook</Link>

	          );
	        })}

	    )
	}

}


text:
package de.fiverx.handling.server.resolver.sv0100;

import de.fiverx.crypto.xml.XmlHelper;
import de.fiverx.exceptions.FiverxLinkException;
import de.fiverx.exceptions.XmlValidationFailedException;
import de.fiverx.handling.server.RequestHandler;
import de.fiverx.handling.server.RequestWrapperHandler;
import de.fiverx.webservice.security.sv0100.RzeLadeRzSecurityVersionAnfrage;
import de.fiverx.webservice.security.sv0100.RzeLadeRzSecurityVersionAntwort;
import de.fiverx.webservice.types.EinParameterRequestMsg;
import de.fiverx.webservice.types.GenericResponseMsg;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

/**
 * author: Pascal Knueppel
 * created at: 30.04.2015
 */
public class LadeRzSecurityVersionResolver extends
                                           RequestWrapperHandler<EinParameterRequestMsg, Void,
                                               RzeLadeRzSecurityVersionAntwort> {

    private static final Logger logger = LogManager.getLogger(LadeRzSecurityVersionResolver.class);

    /**
     * Haupt-Konstruktor
     */
    public LadeRzSecurityVersionResolver() {
        super(null); // In diesem Fall gibt es keine Signatur die validiert werden müsste.
    }

    /**
     * Extrahiert die {@link de.fiverx.webservice.security.sv0100.ApoInformation} aus der gesendeten Anfrage des
     * Kunden und gibt die Anfrage dann an die Implementierung des RequestHandlers weiter.
     * @param requestMsg Die Anfrage des Kunden.
     * @param requestHandler Der Requesthandler, der die unverschlüsselte Anfrage weiterverarbeiten soll.
     * @return Die {@link GenericResponseMsg} für den Kunden.
     */
    @Override
    public GenericResponseMsg handleRequest(EinParameterRequestMsg requestMsg,
                                            RequestHandler<Void, RzeLadeRzSecurityVersionAntwort> requestHandler) {
        try {
            if (logger.isTraceEnabled()) {
                logger.trace("(LadeRzSecurityVersion) Eingehende Nachricht von einem Kunden...");
            }
            // extrahieren des ApoInformations-Elements
            super.setApoInformation(XmlHelper.extractApoInformation(requestMsg));
            requestHandler.setApoInformation(super.getApoInformation());
            String requestXml = requestMsg.getRzeEingabeDaten().trim();

            XmlHelper.validateXmlForClass(requestXml, RzeLadeRzSecurityVersionAnfrage.class);
            String requestSecurityVersion = XmlHelper.validateXmlAgainstUnknownSecuritySchemaVersion(
                requestXml, super.getSecurityOperationInterceptor());

            // Eine Validierung gegen das Security-Schema gibt es hier nicht, da hier noch nicht klar sein kann,
            // gegen welches Schema validiert werden soll.
            RzeLadeRzSecurityVersionAntwort antwort = super.giveMessageToRequestHandler(null, requestHandler);

            GenericResponseMsg genericResponseMsg = new GenericResponseMsg();
            String responseSecurityVersion = requestHandler.getResponseSecurityVersion();
            if (responseSecurityVersion == null) {
                logger.warn("Der RequestHandler hat keine explizite Security Version f\u00fcr die Antwort zur " +
                    "Verf\u00fcgung gestellt. Um eine Exception zu verhindern, wird die Antwort f\u00fcr den Client " +
                    "in der Version der Anfrage gesendet.");
                responseSecurityVersion = requestSecurityVersion;
            }
            genericResponseMsg.setRzeLadeRzSecurityVersion(responseSecurityVersion);
            String plainResponseXml = XmlHelper.marshalObject(antwort);

            // validiere Antwort für den Client gegen das das angegebene Security-Schema Rechenzentrums
            if (securityOperationInterceptor != null) {
                securityOperationInterceptor.doBeforeValidation(
                    XmlHelper.retrieveXml(plainResponseXml),
                    responseSecurityVersion);
            }
            super.validateXml(plainResponseXml, responseSecurityVersion,
                XmlValidationFailedException.Direction.OUTGOING);

            genericResponseMsg.setRzeAusgabeDaten(XmlHelper.marshalObject(antwort));

            if (logger.isTraceEnabled()) {
                logger.trace("Antwort f\u00fcr den Client erfolgreich verarbeitet.");
            }

            return genericResponseMsg;
        } catch (FiverxLinkException frxEx) {
            requestHandler.doOnFail(requestMsg, frxEx);
            if (getApoInformation() != null) {
                frxEx.setApoIK(getApoInformation().getApoIk());
                frxEx.setRzKdNr(getApoInformation().getRzKdNr());
            }
            throw frxEx;
        } catch (Throwable th) {
            requestHandler.doOnFail(requestMsg, th);
            throw resolveUnknownThrowable(th);
        }
    }

}


text:
'''OpenGL extension EXT.GL_422_pixels

This module customises the behaviour of the
OpenGL.raw.GL.EXT.GL_422_pixels to provide a more
Python-friendly API
'''
from OpenGL import platform, constants, constant, arrays
from OpenGL import extensions, wrapper
from OpenGL.GL import glget
import ctypes
from OpenGL.raw.GL.EXT.GL_422_pixels import *
### END AUTOGENERATED SECTION


text:
#ifndef __SneakyJoystickSkinnedBase_h__
#define __SneakyJoystickSkinnedBase_h__

NS_CC_BEGIN

class SneakyJoystick;

class SneakyJoystickSkinnedBase : public CCSprite
{
	public :

		static SneakyJoystickSkinnedBase*	create ( KDvoid );

	public :

		virtual KDbool				init ( KDvoid );

		virtual KDvoid				setContentSize ( const CCSize& tContentSize );

		virtual KDvoid				updatePositions ( KDfloat fDelta );

		virtual CCSprite*			getBackgroundSprite ( KDvoid );
		virtual KDvoid				setBackgroundSprite ( CCSprite* pSprite );

		virtual CCSprite*			getThumbSprite ( KDvoid );
		virtual KDvoid				setThumbSprite ( CCSprite* pSprite );

		virtual SneakyJoystick*		getJoystick ( KDvoid );
		virtual KDvoid				setJoystick ( SneakyJoystick* pJoystick );

	protected :

		CCSprite*					m_pBackgroundSprite;
		CCSprite*					m_pThumbSprite;
		SneakyJoystick*				m_pJoystick;
};

NS_CC_END

#endif	// __SneakyJoystickSkinnedBase_h__


text:
from tkinter import *
import math
import random
import time

from nchoosekvisualization import nChooseKVisualization as vis

# first level functions
def init(data):
    data.cursor = 0
    data.inputNames = ["Number of People", "Size of Subcommittee"]
    data.inputs = [8, 3]
    data.mouse = [0, 0]
    updateNM(data)

def mousePressed(event, data):
    pass

def keyDown(event, data):
    if event.keysym == "Left":
        data.cursor = (data.cursor - 1) % len(data.inputs)
    elif event.keysym == "Right":
        data.cursor = (data.cursor + 1) % len(data.inputs)
    elif event.keysym == "Up":
        data.inputs[data.cursor] += 1
        inputRestrictions(data)
        updateNM(data)
    elif event.keysym == "Down":
        data.inputs[data.cursor] -= 1
        inputRestrictions(data)
        updateNM(data)

def inputRestrictions(data):
    if (data.inputs[0] < 0):
        data.inputs[0] = 0
    data.inputs[1] = data.inputs[1] % (data.inputs[0] + 1)

def updateNM(data):
    data.visuals = [None] * ((data.inputs[0] - data.inputs[1] + 2) * 2 - 1)
    r = (data.width - 260) // 440
    for i in range(0, data.inputs[0] - data.inputs[1] + 1):
        x = i % r
        y = i // r
        bounds = (300 + x * 440, 200 + y * 220, 200, 200)
        data.visuals[2 * i] = vis(data.inputs[0], data.inputs[1] + i, bounds)
        bounds = (300 + x * 440 + 200, 200 + y * 220, 200, 200)
        data.visuals[2 * i + 1] = vis(data.inputs[1] + i, data.inputs[1], bounds)
    bounds = (50, 200, 200, 200)
    data.visuals[-1] = vis(data.inputs[0], data.inputs[1], bounds)

def keyUp(event, data):
    pass

def mouseMoved(event, data):
    data.mouse = [event.x, event.y]

def inBounds(mouse, bounds):
    if (mouse[0] < bounds[0] or mouse[1] < bounds[1]):
        return False
    if (mouse[0] > bounds[0] + bounds[2] or
        mouse[1] > bounds[1] + bounds[3]):
        return False
    return True

def timerFired(data):
    for v in data.visuals:
        b = v.bounds
        if inBounds(data.mouse, b):
            v.update(data.timerDelay / 500)

def redrawAll(canvas, data):
    drawFrameRate(canvas, data)
    for v in data.visuals:
        b = v.bounds
        canvas.create_rectangle(b[0], b[1], b[0] + b[2], b[1] + b[3])
        if inBounds(data.mouse, b):
            v.draw(canvas)
        else:
            text = ("Chooseing " + str(v.k) + " people from a group of " +
                    str(v.n) + " people")
            canvas.create_text(b[0], b[1], text=text, anchor="nw", width=b[2],
                               font = "120")
    drawPlusSigns(canvas, data)
    drawInputUI(canvas, data)

def drawPlusSigns(canvas, data):
    # first draw the equal sign
    cY = 300
    cX = (300 + 250) / 2
    canvas.create_text(cX, cY, text="=", font="40")
    # now draw a plus sign after every other box
    r = (data.width - 260) // 440
    for i in range(0, data.inputs[0] - data.inputs[1]):
        x = i % r
        y = i // r
        bounds = (300 + x * 440 + 200, 200 + y * 220, 200, 200)
        cX = 300 + x * 440 + 200 + 200 + 40 / 2
        cY = 200 + y * 220 + 200 / 2
        canvas.create_text(cX, cY, text="+", font="40")

def drawInputUI(canvas, data):
    for i in range(len(data.inputs)):
        cX = 300 + i * 200
        cY = 50
        canvas.create_text(cX, cY, text=data.inputNames[i], font="40")
        cY = 100
        if (data.cursor == i):
            r = 20
            canvas.create_rectangle(cX-r, cY-r, cX+r, cY+r, fill="yellow")
        canvas.create_text(cX, cY, text=str(data.inputs[i]), font="40")

def drawFrameRate(canvas, data):
    frameRate = len(data.t)
    canvas.create_text(data.width-10, 0, anchor=NE, text="fps:"+str(frameRate))

# run function adapted from 15-112 course website
def run(width=900, height=900):
    def redrawAllWrapper(canvas, data):
        canvas.delete(ALL)
        canvas.create_rectangle(0, 0, data.width, data.height,
                                fill='white', width=0)
        redrawAll(canvas, data)
        canvas.update()

    def mousePressedWrapper(event, canvas, data):
        mousePressed(event, data)
        redrawAllWrapper(canvas, data)

    def keyDownWrapper(event, canvas, data):
        keyDown(event, data)

    def keyUpWrapper(event, canvas, data):
        keyUp(event, data)

    def mouseMovedWrapper(event, canvas, data):
        mouseMoved(event, data)

    def timerFiredWrapper(canvas, data):
        # update times
        t0 = time.time()
        data.timerDelay = (t0 - data.lastTime) * 1000
        data.t.append(data.timerDelay)
        while (sum(data.t) > 1000):
            data.t.pop(0)
        data.lastTime = t0

        timerFired(data)
        redrawAllWrapper(canvas, data)

        # call timerFired again
        canvas.after(0, timerFiredWrapper, canvas, data)
    # create the root and the canvas
    root = Tk()
    root.overrideredirect(True)
    root.geometry("{0}x{1}+0+0".format(root.winfo_screenwidth(),
                                       root.winfo_screenheight()))
    canvas = Canvas(root, width=root.winfo_screenwidth(),
                    height=root.winfo_screenheight())
    canvas.pack()
    # Set up data and call init
    class Struct(object): pass
    data = Struct()
    data.width = root.winfo_screenwidth()
    data.height = root.winfo_screenheight()
    data.lastTime = time.time()
    data.timerDelay = 0
    data.t = []
    init(data)
    # set up events
    root.bind("<Button-1>", lambda event:
                            mousePressedWrapper(event, canvas, data))
    root.bind("<KeyPress>", lambda event:
                            keyDownWrapper(event, canvas, data))
    root.bind("<KeyRelease>", lambda event:
                            keyUpWrapper(event, canvas, data))
    root.bind("<Motion>", lambda event:
                            mouseMovedWrapper(event, canvas, data))
    timerFiredWrapper(canvas, data)
    # and launch the app
    root.mainloop()  # blocks until window is closed
    print("bye!")

if __name__ == "__main__":
    run()


text:
package lrumgr

import (
	"container/list"
	"errors"
	"sync"

	"github.com/pressly/chainstore"
	"golang.org/x/net/context"
)

var _ chainstore.Store = &lruManager{}

type lruManager struct {
	sync.Mutex

	store    chainstore.Store
	capacity int64 // in bytes
	cushion  int64 // 10% of bytes of the capacity, to free up this much if it hits

	items map[string]*lruItem
	list  *list.List
}

type lruItem struct {
	key         string
	size        int64
	listElement *list.Element
}

func newLruManager(capacity int64, store chainstore.Store) *lruManager {
	return &lruManager{
		store:    store,
		capacity: capacity,
		cushion:  int64(float64(capacity) * 0.1),
		items:    make(map[string]*lruItem, 10000),
		list:     list.New(),
	}
}

// New creates and returns a LRU backed store.
func New(capacity int64, store chainstore.Store) chainstore.Store {
	return newLruManager(capacity, store)
}

func (m *lruManager) Open() (err error) {

	if m.capacity < 10 {
		return errors.New("Invalid capacity, must be >= 10 bytes")
	}

	err = m.store.Open()

	// TODO: the items list will be empty after restarting a server
	// with an existing db. We should ask the store for a list of
	// keys and their size to seed this list. Keys are easy,
	// but having a generic way to get the size of each object quickly
	// from each kind of store is challenging / over-kill (ie. s3).
	// we could persist the LRU list of keys/objects somewhere..
	// perhaps using a bolt bucket.
	return
}

func (m *lruManager) Close() (err error) {
	return m.store.Close()
}

func (m *lruManager) Put(ctx context.Context, key string, val []byte) (err error) {
	select {
	case <-ctx.Done():
		return ctx.Err()
	default:
		defer m.prune(ctx) // free up space
		valSize := int64(len(val))

		m.Lock()
		if item, exists := m.items[key]; exists {
			m.list.MoveToFront(item.listElement)
			m.capacity += (item.size - valSize)
			item.size = valSize
			// m.promote(item)
		} else {
			m.addItem(key, valSize)
		}
		m.Unlock()

		// TODO: what if the value is larger then even the initial capacity?
		// ..error..
		return m.store.Put(ctx, key, val)
	}
}

func (m *lruManager) Get(ctx context.Context, key string) (val []byte, err error) {
	select {
	case <-ctx.Done():
		return nil, ctx.Err()
	default:
		val, err = m.store.Get(ctx, key)
		valSize := len(val)

		m.Lock()
		if item, exists := m.items[key]; exists {
			// m.promote(item)
			m.list.MoveToFront(item.listElement)
		} else if valSize > 0 {
			m.addItem(key, int64(valSize))
		}
		m.Unlock()
		return
	}
}

func (m *lruManager) Del(ctx context.Context, key string) (err error) {
	select {
	case <-ctx.Done():
		return ctx.Err()
	default:
		m.Lock()

		if item, exists := m.items[key]; exists {
			m.evict(item)
		}
		m.Unlock()

		return m.store.Del(ctx, key)
	}
}

func (m *lruManager) Capacity() int64 {
	m.Lock()
	defer m.Unlock()
	return m.capacity
}

func (m *lruManager) Cushion() int64 {
	return m.cushion
}

func (m *lruManager) NumItems() int {
	m.Lock()
	defer m.Unlock()
	return m.list.Len()
}

func (m *lruManager) addItem(key string, size int64) {
	item := &lruItem{key: key, size: size}
	item.listElement = m.list.PushFront(item)
	m.items[key] = item
	m.capacity -= size
}

func (m *lruManager) evict(item *lruItem) {
	m.list.Remove(item.listElement)
	delete(m.items, item.key)
	m.capacity += item.size
}

func (m *lruManager) prune(ctx context.Context) {
	if m.capacity > 0 {
		return
	}

	for m.capacity < m.cushion {
		m.Lock()
		tail := m.list.Back()
		if tail == nil {
			return
		}
		item := tail.Value.(*lruItem)
		m.Unlock()

		m.Del(ctx, item.key)
	}
}


text:
"""ncolony.directory_monitor
============================

Monitor directories for configuration and messages
"""

import functools
import os

from twisted.python import filepath

def checker(location, receiver):
    """Construct a function that checks a directory for process configuration

    The function checks for additions or removals
    of JSON process configuration files and calls the appropriate receiver
    methods.

    :param location: string, the directory to monitor
    :param receiver: IEventReceiver
    :returns: a function with no parameters
    """
    path = filepath.FilePath(location)
    files = set()
    filesContents = {}

    def _check(path):
        currentFiles = set(fname for fname in os.listdir(location)
                           if not fname.endswith('.new'))
        removed = files - currentFiles
        added = currentFiles - files
        for fname in added:
            contents = path.child(fname).getContent()
            filesContents[fname] = contents
            receiver.add(fname, contents)
        for fname in removed:
            receiver.remove(fname)
        same = currentFiles & files
        for fname in same:
            newContents = path.child(fname).getContent()
            oldContents = filesContents[fname]
            if newContents == oldContents:
                continue
            receiver.remove(fname)
            filesContents[fname] = newContents
            receiver.add(fname, newContents)
        files.clear()
        files.update(currentFiles)
    return functools.partial(_check, path)

def messages(location, receiver):
    """Construct a function that checks a directory for messages

    The function checks for new messages and
    calls the appropriate method on the receiver. Sent messages are
    deleted.

    :param location: string, the directory to monitor
    :param receiver: IEventReceiver
    :returns: a function with no parameters
    """
    path = filepath.FilePath(location)

    def _check(path):
        messageFiles = path.globChildren('*')
        for message in messageFiles:
            if message.basename().endswith('.new'):
                continue
            receiver.message(message.getContent())
            message.remove()
    return functools.partial(_check, path)


text:
Thank you for your support!

---

# adaptive-googlemaps v0.3.0 [![Build Status](https://travis-ci.org/angular-adaptive/adaptive-googlemaps.png?branch=master)](https://travis-ci.org/angular-adaptive/adaptive-googlemaps)

This module allows you to adapt googlemaps component for different occasions.
- static google map
- open map in a new tab / a native mobile application
- load dynamic google map

### Demo

Check out http://angular-adaptive.github.io/adaptive-googlemaps/demo/

# Requirements

- AngularJS v 1.0+
- Googlemaps JS API v3 (only for dynamic google map)

# Usage

We use [bower](http://twitter.github.com/bower/) for dependency management. Add

```json
dependencies: {
    "angular-adaptive-googlemaps": "latest"
}
```

To your `bower.json` file. Then run

    bower install

This will copy the angular-adaptive-googlemaps files into your `bower_components` folder, along with its dependencies. Load the script files in your application:

```html
<script src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript" src="bower_components/angular/angular.js"></script>
<script type="text/javascript" src="bower_components/angular-adaptive-googlemaps/angular-adaptive-googlemaps.min.js"></script>
```

Add the **adaptive.googlemaps** module as a dependency to your application module:

```js
var myAppModule = angular.module('MyApp', ['adaptive.googlemaps']);
```

Add **googlemaps** element into your template

```js
<googlemaps class="google-maps" options="map1"></googlemaps>
```

### Directive attributes

```js
$scope.map1 = {
    sensor: false,
    size: '500x300',
    zoom: 9,
    center: 'San Francisco International Airport',
    markers: ['San Francisco', 'San Jose'],
    maptype: 'terrain',
    mapevents: {redirect: false, loadmap: true},
    listen: true
};
```

#### Required:

- sensor: false // true, false
- size: '500x300' // width x height
- zoom: 6
- center: 'California'

#### Optional:

- markers: ['San Francisco', 'San Jose']
- maptype: 'roadmap' // roadmap, satellite, terrain, hybrid
- mapevents: {redirect: true, loadmap: false}
- listen: true // watch for attributes change

#### mapevents: { "redirect": false, "loadmap": true }
Loads dynamic google map.

#### { "redirect": true, "loadmap": false }
Opens google map in a new tab / a native mobile application.

#### mapevents: no mapevents
Nothing happens.

# Contributing

Contributions are welcome. Please make a pull request against canary branch and do not bump versions. Also include tests.

### Todo
- Let the device/browser decide what kinds of map events will be used. *Example: mobile device will open native maps application, browser with fast internet connection will auto load dynamic map...*

# Testing

More tests will be added...

We use karma and jshint to ensure the quality of the code. The easiest way to run these checks is to use grunt:

    npm install -g grunt-cli
    npm install
    bower install
    grunt

The karma task will try to open Chrome as a browser in which to run the tests. Make sure this is available or change the configuration in `test/test.config.js`

# References

If you are looking just for static google maps you can use [angular-google-staticmaps](https://github.com/passy/angular-google-staticmaps) repository.

# License

The MIT License

Copyright (c) 2013 [Jan Antala](http://www.janantala.com)


text:
<?php

namespace PHPCasts\Bundle\WebsiteBundle\Controller;

use PHPCasts\Entity\Proposal;
use PHPCasts\Bundle\WebsiteBundle\Form\Type\ProposalType;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class DefaultController extends Controller
{
    public function loginFbAction()
    {

    }

    public function indexAction()
    {
        $latestProposals = $this->getDoctrine()->getRepository('Entity:Proposal')->findBy([
            'status' => Proposal::STATUS_VOTING
        ], ['votes' => 'desc', 'createdAt' => 'desc'], 4);

        $latestScreencasts = $this->getDoctrine()->getRepository('Entity:Screencast')->findBy([
        ], ['createdAt' => 'desc'], 3);

        return $this->render('PHPCastsWebsiteBundle:Default:index.html.twig', [
            'latestProposals' => $latestProposals,
            'latestScreencasts' => $latestScreencasts,
        ]);
    }

    public function aboutAction()
    {
        return $this->render('PHPCastsWebsiteBundle:Default:about.html.twig');
    }
}


text:
Ti.include("geoFunctions.js");
Ti.include("mapFunctions.js");
Ti.include("collectionData.js");

var args = arguments[0] || {};
var trailName = args.title;
var trailColor = args.color;
var trailId = args.id;
var zoomLat = args.zoomlat;
var zoomLon = args.zoomlon;

var showingPosition = false;
var menuDetailVisible = false;

detailMap.removeAllAnnotations();
showMapDetail();
getSpecificIconsForTrail(trailId, detailMap);
displaySpecificMarkers(trailId, detailMap);

//-----------------------------------------------------------
// Om man öppnar detaljvy för båtleden ska navBar'en synas
//-----------------------------------------------------------
if(trailId == 8){
	$.detailwin.navBarHidden = '';
}

//-----------------------------------------------------------
// Visar kartan
//-----------------------------------------------------------
function showMapDetail() {
	$.mapDetailView.add(showDetailMap(detailMap, trailId, trailName, trailColor));
}

//-----------------------------------------------------------
// Switch för att visa användarens position på kartan
//-----------------------------------------------------------
function showUserPosition(){
	if (showingPosition == false) {
		getPosition(detailMap);
		showingPosition = true;
	} else {
		detailMap.userLocation = false;
		showingPosition = false;
	}
}

//-----------------------------------------------------------
// Öppnar hotspotDetail med info om vald hotspot
//-----------------------------------------------------------
function showHotspotfromDetailMap(hotId) {
	try {
		var jsonObjHot = returnSpecificHotspotsByName(hotId);
		var hotspotId;
		var x;
		var y;

		if(jsonObjHot[0].id == 32){
			hotspotId = 42;
			x = 58.893085;
			y = 11.047972;
		} else {
			hotspotId = jsonObjHot[0].id;
			x = jsonObjHot[0].xkoord;
			y = jsonObjHot[0].ykoord;
		}

		var hotspotTxt = {
			title : jsonObjHot[0].name,
			titleEng : jsonObjHot[0].engelsk_titel,
			infoTxt : jsonObjHot[0].infoTxt,
			infoTxtEng : jsonObjHot[0].engelsk_beskrivning,
			id : hotspotId,
			x : x,
			y : y
		};

		var hotDet = Alloy.createController("hotspotDetail", hotspotTxt).getView();
		$.mapNav.openWindow(hotDet);

		hotspotDetail = null;
	} catch(e) {
		newError("Något gick fel när sidan skulle laddas, prova igen!");
	}
}

//-----------------------------------------------------------
// Eventlistener för klick på hotspot
//-----------------------------------------------------------
var evtLists = function(evt){
	try {
		if (evt.clicksource == 'rightButton') {
			showHotspotfromDetailMap(evt.annotation.id);
		}
	} catch(e) {
		newError("Något gick fel när sidan skulle laddas, prova igen!", "Kartfunktioner");
	}
};
detailMap.addEventListener('click', evtLists);

//-----------------------------------------------------------
// Funktion för att stänga och rensa sida när man stänger sidan
//-----------------------------------------------------------
 function closeMap(){
 	$.mapNav.close();
 }

 var cleanup = function() {
	$.destroy();
	$.off();
	$.detailwin = null;
	detailMap.removeEventListener('click', evtLists);
};

$.detailwin.addEventListener('close', cleanup);


text:
package login

import (
	db "github.com/dancannon/gorethink"
	"github.com/gin-gonic/contrib/sessions"
	"github.com/gin-gonic/gin"
	"github.com/gophergala2016/ring_leader/models"
	"github.com/gophergala2016/ring_leader/services"
)

type Login struct {
	DB *db.Session
}

func Init(router *gin.Engine, DB *db.Session) {
	// Simple group: login
	l := &Login{DB}
	loginRouter := router.Group("/login")
	{
		loginRouter.POST("/register", l.registerUser)
		loginRouter.POST("/authorize", l.loginUser)
		loginRouter.GET("/logout", l.logoutUser)
		loginRouter.DELETE("/remove", l.deleteSelf)
	}
}
func (l *Login) registerUser(c *gin.Context) {
	var json models.CreateUser
	if err := c.BindJSON(&json); err != nil {
		c.String(500, err.Error())
		return
	}
	service := &services.UserService{}
	exists := service.UserExistByEmail(l.DB, json.Email)
	if exists == true {
		c.String(500, "user already exists")
		return
	}

	err := service.InsertUser(l.DB, json)
	if err != nil {
		c.String(500, err.Error())
		return
	}
	c.String(200, "worked")
}

func (l *Login) loginUser(c *gin.Context) {
	var json models.LoginUser
	if err := c.BindJSON(&json); err != nil {
		c.String(500, err.Error())
		return
	}
	service := &services.UserService{}
	auth, user := service.AuthenticateUser(l.DB, json)
	if auth == false {
		c.String(500, "bad credentials")
		return
	}
	session := sessions.Default(c)
	session.Set("user", *user)
	err := session.Save()
	if err != nil {
		c.String(500, err.Error())
	}
	c.String(200, "worked authenticated")
}

func (l *Login) logoutUser(c *gin.Context) {
	session := sessions.Default(c)
	session.Delete("user")
	session.Save()
	c.String(200, "worked unauthenticated")
}

func (l *Login) deleteSelf(c *gin.Context) {
	session := sessions.Default(c)
	u := session.Get("user")
	if u == nil {
		c.String(500, "something went wrong")
		// TODO Redirect
	}
	// Validate credentials
	switch user := u.(type) {
	case models.User:
		service := &services.UserService{}
		err := service.RemoveUser(l.DB, user)
		if err != nil {
			c.String(500, err.Error())
		}
	default:
		c.String(500, "something went really wrong")
	}
}

func (l Login) ChangeUser(form models.ChangeUser, id int32) error {
	return nil
}