text:
package com.b2international.snowowl.datastore.server.internal.cdo;

import static com.google.common.collect.Lists.newArrayList;
import static org.junit.Assert.*;

import java.util.List;
import java.util.Objects;

import org.eclipse.emf.cdo.common.revision.CDOList;
import org.eclipse.emf.cdo.common.revision.CDOListFactory;
import org.eclipse.emf.cdo.common.util.UnorderedListDifferenceAnalyzer;
import org.junit.Test;

import com.google.common.collect.ImmutableList;

public class UnorderedListDifferenceAnalyzerTest {

	private static interface Change { };

	private static final class Add implements Change {
		public int i;
		public Object newObject;

		public Add(int i, Object newObject) {
			this.i = i;
			this.newObject = newObject;
		}

		@Override
		public int hashCode() {
			return Objects.hash(i, newObject);
		}

		@Override
		public boolean equals(Object obj) {
			if (this == obj) return true;
			if (obj == null) return false;
			if (getClass() != obj.getClass()) return false;

			Add other = (Add) obj;
			return i == other.i && Objects.equals(newObject, other.newObject);
		}

		@Override
		public String toString() {
			return String.format("Add [i=%s, newObject=%s]", i, newObject);
		}
	}

	private static final class Remove implements Change {
		public int i;
		public Object oldObject;

		public Remove(int i, Object oldObject) {
			this.i = i;
			this.oldObject = oldObject;
		}

		@Override
		public int hashCode() {
			return Objects.hash(i, oldObject);
		}

		@Override
		public boolean equals(Object obj) {
			if (this == obj) return true;
			if (obj == null) return false;
			if (getClass() != obj.getClass()) return false;

			Remove other = (Remove) obj;
			return i == other.i && Objects.equals(oldObject, other.oldObject);
		}

		@Override
		public String toString() {
			return String.format("Remove [i=%s, oldObject=%s]", i, oldObject);
		}
	}

	private final CDOList oldList = CDOListFactory.DEFAULT.createList(10, 0, 0, false);
	private final CDOList newList = CDOListFactory.DEFAULT.createList(10, 0, 0, false);
	private final List<Change> changes = newArrayList();

	private final UnorderedListDifferenceAnalyzer analyzer = new UnorderedListDifferenceAnalyzer() {
		@Override
		protected void createAddListChange(CDOList oldList, Object newObject, int index) {
			changes.add(new Add(index, newObject));
			super.createAddListChange(oldList, newObject, index);
		}

		@Override
		protected void createRemoveListChange(CDOList oldList, Object oldObject, int index) {
			changes.add(new Remove(index, oldObject));
			super.createRemoveListChange(oldList, oldObject, index);
		}
	};

	@Test
	public void testAddition() throws Exception {
		oldList.addAll(ImmutableList.of(1, 2, 3, 4, 5));
		newList.addAll(ImmutableList.of(1, 2, 3, 4, 5, 6));

		analyzer.createListChanges(oldList, newList);

		assertEquals(1, changes.size());
		assertEquals(new Add(5, 6), changes.get(0));
	}

	@Test
	public void testRemove() throws Exception {
		oldList.addAll(ImmutableList.of(1, 2, 3, 4, 5));
		newList.addAll(ImmutableList.of(1, 2, 3, 4));

		analyzer.createListChanges(oldList, newList);

		assertEquals(1, changes.size());
		assertEquals(new Remove(4, 5), changes.get(0));
	}

	@Test
	public void testUnorderedRemove() throws Exception {
		oldList.addAll(ImmutableList.of(1, 2, 3, 4, 5));
		newList.addAll(ImmutableList.of(5, 2, 3, 4));

		analyzer.createListChanges(oldList, newList);

		assertEquals(1, changes.size());
		assertEquals(new Remove(0, 1), changes.get(0));
	}

	@Test
	public void testMove() throws Exception {
		oldList.addAll(ImmutableList.of(1, 2, 3, 4, 5));
		newList.addAll(ImmutableList.of(5, 2, 4, 3, 1));

		analyzer.createListChanges(oldList, newList);

		assertEquals(0, changes.size());
	}

	@Test
	public void testAddAndRemove() throws Exception {
		oldList.addAll(ImmutableList.of(1, 2, 3, 4, 5));
		// Add 6 to index 2, remove 3 from index 3
		newList.addAll(ImmutableList.of(1, 2, 6, 5, 4));

		analyzer.createListChanges(oldList, newList);

		// Seen as removing 3 from its original index 2, then adding 6 at the end to index 4
		assertEquals(2, changes.size());
		assertEquals(new Remove(2, 3), changes.get(0));
		assertEquals(new Add(4, 6), changes.get(1));
	}

	@Test
	public void testSmallAdd() throws Exception {
		for (int i = 0; i < 1_000_000; i++) {
			oldList.add(i);
			newList.add(i);
		}

		newList.add(1_000_000);

		analyzer.createListChanges(oldList, newList);

		assertEquals(1, changes.size());
		assertEquals(new Add(1_000_000, 1_000_000), changes.get(0));
	}

	@Test
	public void testSmallRemove() throws Exception {
		for (int i = 0; i < 1_000_000; i++) {
			oldList.add(i);
			newList.add(i);
		}

		newList.remove(500);

		analyzer.createListChanges(oldList, newList);

		assertEquals(1, changes.size());
		assertEquals(new Remove(500, 500), changes.get(0));
	}

	@Test(timeout=3000L)
	public void testNoChangeWorstCase() throws Exception {
		// Two lists in completely opposite element order results in n^2 iterations.
		for (int i = 0; i < 20_000; i++) {
			oldList.add(i);
			newList.add(19_999 - i);
		}

		analyzer.createListChanges(oldList, newList);

		assertEquals(0, changes.size());
	}
}

redpajama_set_name: RedPajamaGithub


text:
package com.zimbra.soap.mail.message;

import com.google.common.base.Objects;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;

import com.zimbra.common.soap.MailConstants;
import com.zimbra.soap.type.ZmBoolean;

@XmlAccessorType(XmlAccessType.NONE)
@XmlRootElement(name=MailConstants.E_TEST_DATA_SOURCE_RESPONSE)
public class TestDataSourceResponse {

    /**
     * @zm-api-field-tag success
     * @zm-api-field-description Flags whether the test was successful
     */
    @XmlAttribute(name=MailConstants.A_DS_SUCCESS /* success */, required=true)
    private final ZmBoolean success;

    /**
     * @zm-api-field-tag error-message
     * @zm-api-field-description Error message
     */
    @XmlAttribute(name=MailConstants.A_DS_ERROR /* error */, required=false)
    private String error;

    /**
     * no-argument constructor wanted by JAXB
     */
    @SuppressWarnings("unused")
    private TestDataSourceResponse() {
        this(false);
    }

    public TestDataSourceResponse(boolean success) {
        this.success = ZmBoolean.fromBool(success);
    }

    public void setError(String error) { this.error = error; }
    public boolean getSuccess() { return ZmBoolean.toBool(success); }
    public String getError() { return error; }

    public Objects.ToStringHelper addToStringInfo(Objects.ToStringHelper helper) {
        return helper
            .add("success", success)
            .add("error", error);
    }

    @Override
    public String toString() {
        return addToStringInfo(Objects.toStringHelper(this)).toString();
    }
}


text:
'use strict';

var mongoose = require('mongoose');

mongoose.connect('mongodb://localhost:27017/localdb');

var db = mongoose.connection;
var path = process.cwd();

var Users = require(path + '/app/models/users.js');

var gcmId = '';

db.on('open', function() {

    Users.find({
            gcmIds: gcmId
        })
        .exec(function(err, users) {
            if (err) return console.error(err);

            console.log(users);

            // if (users.length === 0) {
            //     var newUser = new Users();
            //     newUser.gcmIds.push(req.body.gcmId);
            //     Users.create(newUser, function(err, result) {
            //         if (err) return handleRes.error(res, err);
            //         handleRes.send(res, 'Register Successful', result._id);
            //     });
            // }

            // handleRes.send(res, 'Register Successful', users[0]._id);
        });

});


text:
FROM ubuntu:18.04

# release or debug
ENV ENV_TYPE release

COPY . /root/web_app
WORKDIR /root/web_app

ENV APP_CONFIG_FILE /root/flask_proj/webapp/instance/env_$ENV_TYPE.py

RUN apt-get update  && \
            apt-get install -y git  && \
            apt-get install -y python  && \
            apt-get install -y python-pip  && \
            apt-get install -y python-virtualenv  && \
            apt-get install -y nginx  && \
            apt-get install -y vim

EXPOSE 80

CMD ["/bin/bash", "/root/web_app/auto_setup.sh"]


text:
@class LSTargetGenerator;

@interface LSMatchTypeConfig : NSObject
{
    unsigned int _matchType;
    unsigned int _matchSubType;
    LSTargetGenerator *_targetGenerator;
    LSTargetGenerator *_nsMatchDescGenerator;
    LSTargetGenerator *_nsShortPYGenerator;
    LSTargetGenerator *_nsFullPYGenerator;
}

+ (id)matchType:(unsigned int)arg1 subType:(unsigned int)arg2 target:(id)arg3 desc:(id)arg4 shortPY:(id)arg5 fullPY:(id)arg6;
+ (id)matchType:(unsigned int)arg1 subType:(unsigned int)arg2 target:(id)arg3 desc:(id)arg4;
@property(retain, nonatomic) LSTargetGenerator *nsFullPYGenerator; // @synthesize nsFullPYGenerator=_nsFullPYGenerator;
@property(retain, nonatomic) LSTargetGenerator *nsShortPYGenerator; // @synthesize nsShortPYGenerator=_nsShortPYGenerator;
@property(retain, nonatomic) LSTargetGenerator *nsMatchDescGenerator; // @synthesize nsMatchDescGenerator=_nsMatchDescGenerator;
@property(retain, nonatomic) LSTargetGenerator *targetGenerator; // @synthesize targetGenerator=_targetGenerator;
@property(nonatomic) unsigned int matchSubType; // @synthesize matchSubType=_matchSubType;
@property(nonatomic) unsigned int matchType; // @synthesize matchType=_matchType;
- (void).cxx_destruct;
- (_Bool)applyRule:(int)arg1;

@end


text:
package niek.animalkingdom.birds;

import niek.animalkingdom.Interfaces.IBird;
import niek.animalkingdom.general.Animal;
import niek.animalkingdom.general.Egg;
import niek.animalkingdom.general.Gender;
import niek.animalkingdom.zoo.Zoo;

import java.util.ArrayList;

public abstract class Bird extends Animal implements IBird {
    public Bird() {
        super();
    }

    public Bird(Gender gender, String bodyCovering, String name, String color, double weight, int maxNumberOfEggs) {
        super(gender, bodyCovering, name, color, weight, maxNumberOfEggs);
    }

    public ArrayList<Egg> layEggs() {
        this.getGender().giveBirth();
        System.out.println("Laying eggs");
        return null;
    }

    public void hatchEggs(ArrayList<Egg> layedEggs) {
        Zoo z = new Zoo();
        for (Egg e : layedEggs) {
            Animal b = e.getEmbryo();
            Zoo.getInstance();
            z.addAnimal(b);
        }
    }

}


text:
import json
import re
import socket
import struct
import unittest

import pants

from pants.test._pants_util import *

try:
    import netstruct
except ImportError:
    netstruct = None

class LineOriented(pants.Stream):
    def on_connect(self):
        self.read_delimiter = '\r\n'

    def on_read(self, data):
        self.write(data * 2)

class TestReadDelimiterString(PantsTestCase):
    def setUp(self):
        self.server = pants.Server(ConnectionClass=LineOriented).listen(('127.0.0.1', 4040))
        PantsTestCase.setUp(self)

    def test_read_delimiter_string(self):
        sock = socket.socket()
        sock.settimeout(1.0)
        sock.connect(('127.0.0.1', 4040))
        request = "line1\r\nline2\r\n"
        sock.send(request)
        response = sock.recv(1024)
        sock.close()
        self.assertEqual(response, "line1line1line2line2")

    def tearDown(self):
        PantsTestCase.tearDown(self)
        self.server.close()

class StructOriented(pants.Stream):
    def on_connect(self):
        self.read_delimiter = struct.Struct("!2H")

    def on_read(self, val1, val2):
        self.write(str(val1 * val2))

class TestReadDelimiterStruct(PantsTestCase):
    def setUp(self):
        self.server = pants.Server(StructOriented).listen(('127.0.0.1', 4040))
        PantsTestCase.setUp(self)

    def tearDown(self):
        PantsTestCase.tearDown(self)
        self.server.close()

    def test_read_delimiter_struct(self):
        sock = socket.socket()
        sock.settimeout(1.0)
        sock.connect(('127.0.0.1', 4040))
        sock.send(struct.pack("!2H", 42, 81))
        response = sock.recv(1024)
        sock.close()
        self.assertEqual(int(response), 42*81)

class NetStructOriented(pants.Stream):
    def on_connect(self):
        self.read_delimiter = netstruct.NetStruct("ih$5b")

    def on_read(self, *data):
        self.write(json.dumps(data))

@unittest.skipIf(netstruct is None, "netstruct library not installed")
class TestReadDelimiterNetStruct(PantsTestCase):
    def setUp(self):
        self.server = pants.Server(NetStructOriented).listen(('127.0.0.1', 4040))
        PantsTestCase.setUp(self)

    def tearDown(self):
        PantsTestCase.tearDown(self)
        self.server.close()

    def test_read_delimiter_netstruct(self):
        sock = socket.socket()
        sock.settimeout(1.0)
        sock.connect(('127.0.0.1', 4040))
        print sock.send("\x00\x00\x05\x12\x00\x07default\x00\x00\x01\x00\x08")
        response = sock.recv(1024)
        sock.close()
        self.assertEqual(
            json.loads(response),
            [1298, 'default', 0, 0, 1, 0, 8]
        )

class RegexOriented(pants.Stream):
    def on_connect(self):
        self.read_delimiter = re.compile(r"\s\s+")

    def on_read(self, data):
        self.write(data)

class TestReadDelimiterRegex(PantsTestCase):
    def setUp(self):
        self.server = pants.Server(RegexOriented).listen(('127.0.0.1', 4040))
        PantsTestCase.setUp(self)

    def tearDown(self):
        PantsTestCase.tearDown(self)
        self.server.close()

    def test_read_delimiter_regex(self):
        sock = socket.socket()
        sock.settimeout(1.0)
        sock.connect(('127.0.0.1', 4040))
        sock.send("This is  a test.  ")
        response = sock.recv(1024)
        sock.close()
        self.assertEqual(response, "This isa test.")

class ChunkOriented(pants.Stream):
    def on_connect(self):
        self.read_delimiter = 4

    def on_read(self, data):
        self.write(data * 2)

class TestReadDelimiterChunk(PantsTestCase):
    def setUp(self):
        self.server = pants.Server(ConnectionClass=ChunkOriented).listen(('127.0.0.1', 4040))
        PantsTestCase.setUp(self)

    def test_read_delimiter_number(self):
        sock = socket.socket()
        sock.settimeout(1.0)
        sock.connect(('127.0.0.1', 4040))
        request = ('1' * 4) + ('2' * 4)
        sock.send(request)
        response = sock.recv(1024)
        sock.close()
        self.assertEqual(response, ('1' * 8) + ('2' * 8))

    def tearDown(self):
        PantsTestCase.tearDown(self)
        self.server.close()


text:
namespace boost {
  namespace logging {
    class rdLogger{
    public:
    rdLogger(std::ostream *dest,bool owner=false) : dp_dest(dest), df_owner(owner),
        df_enabled(true) {};
      std::ostream *dp_dest;
      bool df_owner,df_enabled;
      ~rdLogger(){
        if(dp_dest){
          dp_dest->flush();
          if(df_owner){
            delete dp_dest;
          }
        }
      }
    };
    void enable_logs(const char *arg);
    void enable_logs(const std::string &arg);
    void disable_logs(const char *arg);
    void disable_logs(const std::string &arg);
  }
}
namespace RDLog {
  std::ostream &toStream(std::ostream &);
}
#define BOOST_LOG(__arg__) if((!__arg__)||(!__arg__->dp_dest)||!(__arg__->df_enabled)) ; else RDLog::toStream(*(__arg__->dp_dest))

extern boost::logging::rdLogger *rdAppLog;
extern boost::logging::rdLogger *rdDebugLog;
extern boost::logging::rdLogger *rdInfoLog;
extern boost::logging::rdLogger *rdErrorLog;
extern boost::logging::rdLogger *rdWarningLog;
extern boost::logging::rdLogger *rdStatusLog;

#else
#define BOOST_LOG_NO_LIB
#include <boost/log/log.hpp>
BOOST_DECLARE_LOG(rdAppLog)
BOOST_DECLARE_LOG(rdDebugLog)
BOOST_DECLARE_LOG(rdInfoLog)
BOOST_DECLARE_LOG(rdErrorLog)
BOOST_DECLARE_LOG(rdWarningLog)
BOOST_DECLARE_LOG(rdStatusLog)
#endif
namespace RDLog {
  void InitLogs();
}
#endif


text: Not to be taking seriously.


text:
package mikrosoft.widget.calc.dialog;

import android.content.Context;
import android.database.DataSetObserver;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListAdapter;
import android.widget.TextView;

import java.io.IOException;

import mikrosoft.widget.calc.CalculatorData;

public class SavedResultsAdapter implements ListAdapter {

    String[] savedResults = null;
    Context context = null;

    public SavedResultsAdapter(Context context) throws IOException {
        this.context = context;
        savedResults = new CalculatorData().getSavedResults(context);
    }

    @Override
    public boolean areAllItemsEnabled() {
        return true;
    }

    @Override
    public boolean isEnabled(int position) {
        return true;
    }

    @Override
    public void registerDataSetObserver(DataSetObserver observer) {

    }

    @Override
    public void unregisterDataSetObserver(DataSetObserver observer) {

    }

    @Override
    public int getCount() {
        return savedResults.length;
    }

    @Override
    public Object getItem(int position) {
        return savedResults[position];
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public boolean hasStableIds() {
        return false;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        return convertView != null ? convertView : createListViewElement(position);
    }

    private View createListViewElement(int position) {
        LayoutInflater layoutInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        TextView listViewElement = (TextView)layoutInflater.inflate(android.R.layout.simple_dropdown_item_1line, null);
        listViewElement.setTextColor(Color.WHITE);
        listViewElement.setText(savedResults[position]);
        return listViewElement;
    }

    @Override
    public int getItemViewType(int position) {
        return 1;
    }

    @Override
    public int getViewTypeCount() {
        return 1;
    }

    @Override
    public boolean isEmpty() {
        return false;
    }
}


text:
Ext.application({
    name: 'OPF.console.domain',

    appFolder: 'domain',

    controllers: [
        'DomainController', 'PackageController', 'EntityController',
        'ActionController', 'ActorController', 'SystemController',
        'ProcessController', 'RelationshipController'
    ],

    launch: function() {
        Ext.QuickTips.init();

        var domainPageView = Ext.create('OPF.console.domain.view.DomainView');

        Ext.create('OPF.console.ManagerLayout', domainPageView);
    }
});


text:
trait Foo:
  class Bar:
    private[Foo] opaque type Baz = Int

  def foo: Bar#Baz


text:
<?xml version="1.0" encoding="utf-8"?>
<Product xmlns='http://code.google.com/p/open-zwave/'>

<!-- Qubino: ZMNHDA2 Flush Dimmer -->

	<!-- Configuration -->
	<CommandClass id="112">
		<Value type="list" genre="config" instance="1" index="2" label="Input 2 contact type" size="1" min="0" max="1" value="0">
			<Help/>
			<Item label="NO (normaly open) input type" value="0"/>
			<Item label="NC (normaly close) input type" value="1"/>
		</Value>

		<Value type="list" genre="config" instance="1" index="3" label="Input 3 contact type" size="1" min="0" max="1" value="0">
			<Help/>
			<Item label="NO (normaly open) input type" value="0"/>
			<Item label="NC (normaly close) input type" value="1"/>
		</Value>

		<Value type="list" genre="config" instance="1" index="10" label="Activate / deactivate functions ALL ON/ALL OFF" size="1" min="0" max="255" value="255">
			<Help>Flush 1 relay module responds to commands ALL ON / ALL OFF that may be sent by the main controller or by other controller belonging to the system.</Help>
			<Item label="ALL ON active, ALL OFF active" value="255" />
			<Item label="ALL ON is not active ALL OFF is not active" value="0" />
			<Item label="ALL ON is not active ALL OFF active" value="1" />
			<Item label="ALL ON active ALL OFF is not active" value="2" />
		</Value>

		<Value type="list" genre="config" instance="1" index="30" label="Saving the state of the relay after a power failure" size="1" min="0" max="1" value="0">
			<Help/>
			<Item label="Flush dimmer module saves its state before power failure (it returns to the last position saved before a power failure)" value="0" />
			<Item label="Flush dimmer module does not save the state after a power failure, it returns to off position" value="1" />
		</Value>

 		<Value type="byte" genre="config" instance="1" index="40" label="Power reporting in Watts on power change" size="1" min="0" max="100" value="5">
			<Help>Set value from 0 - 100 (0% - 100%). 0 - Reporting Disabled. 1 - 100 = 1% - 100% Reporting enabled. Power report is send (push) only when actual power in Watts in real time change for more than set percentage comparing to previous actual power in Watts, step is 1%. Default value 5</Help>
			</Value>

		<Value type="short" genre="config" instance="1" index="42" label="Power reporting in Watts by time interval" min="0" max="65535" value="300">
			<Help>Set value means time interval (0 - 65535) in seconds, when power report is send. 0 - Reporting Disabled. 1 - 65535 = 1 second - 65535 seconds. Reporting enabled. Power report is send with time interval set by entered value. Default value 300 (power report in Watts is send each 300s)</Help>
		</Value>

		<Value type="byte" genre="config" instance="1" index="60" label="Minimum dimming value" min="1" max="98" value="1">
			<Help>1 - 98 = 1% - 98%, step is 1%. Minimum dimming values is set by entered value. Default value 1 (Minimum dimming value is 1%)</Help>
		</Value>

		<Value type="byte" genre="config" instance="1" index="61" label="Maximum dimming value" min="2" max="99" value="2">
			<Help>2 - 99 = 2% - 99%, step is 1%. Maximum dimming values is set by entered value. Default value 99 (Maximum dimming value is 99 %)</Help>
		</Value>

		<Value type="byte" genre="config" instance="1" index="65" label="Dimming time (soft on/off)" min="1" max="255" value="100">
			<Help>Set value means time of moving the Dimmer between min. and max. dimming values by short press of push button I1 or controlled through. 1- 255 = 10mseconds - 2550mseconds (2,55s), step is 10mseconds. Default value 100 (Dimming time between min. and max. dimming values is 1s)</Help>
		</Value>

		<Value type="byte" genre="config" instance="1" index="66" label="Dimming time when key pressed" min="1" max="255" value="3">
			<Help>Time of moving the Dimmer between min. and max dimming values by continues hold of push button I1. 1- 255 = 1 second - 255 seconds. Default value 3 (Dimming time between min. and max. dimming values is 3s)</Help>
		</Value>

	</CommandClass>

	<!-- Association Groups -->
	<CommandClass id="133">
		<Associations num_groups="4">
			<Group index="1" max_associations="5" label="Multilevel" auto="true"/>
			<Group index="2" max_associations="5" label="Input I2 state" auto="true" />
			<Group index="3" max_associations="5" label="Input I3 state" auto="true"/>
			<Group index="4" max_associations="1" label="Default reporting" auto="true"/>
		</Associations>
	</CommandClass>

	<!-- Remove COMMAND_CLASS_BASIC -->
	<CommandClass id="32" action="remove" />

	<!-- Map endpoints to instances -->
	<CommandClass id="96" mapping="endpoints" />

</Product>


text:
import os

MAX_DEPTH = 3  # max depth of recursion

q = 'LICENSE'  # file to find
os.chdir('/Volumes/350GB/Projects/')  # starting directory to search
exclude_path = ['node_modules', 'bower_components']  # exclude going into these folders

Q = [(0, f) for f in os.listdir('.')]  # depth and filename

while len(Q) > 0:
    d, f = Q.pop(0)
    if not os.path.isdir(f):
        if os.path.basename(f) == q:
            print f
    else:
        if d < MAX_DEPTH and not os.path.basename(f) in exclude_path:
            c = os.listdir(f)
            for f1 in c:
                Q.append((d + 1, os.path.join(f, f1)))


text:
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('slides', '0002_auto_20150521_2312'),
    ]

    operations = [
        migrations.AlterField(
            model_name='slide',
            name='description',
            field=models.CharField(max_length=140, blank=True),
        ),
    ]


text:
#include "hmd_openvr.h"

BX_PRAGMA_DIAGNOSTIC_IGNORED_CLANG_GCC("-Wunused-variable")
#include <openvr/openvr_capi.h>

namespace bgfx
{
#if BX_PLATFORM_WINDOWS
#	define VR_CALLTYPE __cdecl
#else
#	define VR_CALLTYPE
#endif

	typedef uint32_t    (VR_CALLTYPE *PFN_VR_INITINTERNAL)(EVRInitError* peError, EVRApplicationType eType);
	typedef void        (VR_CALLTYPE *PFN_VR_SHUTDOWNINTERNAL)();
	typedef bool        (VR_CALLTYPE *PFN_VR_ISHMDPRESENT)();
	typedef void*       (VR_CALLTYPE *PFN_VR_GETGENERICINTERFACE)(const char* pchInterfaceVersion, EVRInitError* peError);
	typedef bool        (VR_CALLTYPE *PFN_VR_ISRUNTIMEINSTALLED)();
	typedef bool        (VR_CALLTYPE *PFN_VR_ISINTERFACEVERSIONVALID)(const char *pchInterfaceVersion);
	typedef uint32_t    (VR_CALLTYPE *PFN_VR_GETINITTOKEN)();
	typedef const char* (VR_CALLTYPE *PFN_VR_GETVRINITERRORASSYMBOL)(EVRInitError error);
	typedef const char* (VR_CALLTYPE *PFN_VR_GETVRINITERRORASENGLISHDESCRIPTION)(EVRInitError error);

	PFN_VR_INITINTERNAL                       VR_InitInternal;
	PFN_VR_SHUTDOWNINTERNAL                   VR_ShutdownInternal;
	PFN_VR_ISHMDPRESENT                       VR_IsHmdPresent;
	PFN_VR_GETGENERICINTERFACE                VR_GetGenericInterface;
	PFN_VR_ISRUNTIMEINSTALLED                 VR_IsRuntimeInstalled;
	PFN_VR_ISINTERFACEVERSIONVALID            VR_IsInterfaceVersionValid;
	PFN_VR_GETINITTOKEN                       VR_GetInitToken;
	PFN_VR_GETVRINITERRORASSYMBOL             VR_GetVRInitErrorAsSymbol;
	PFN_VR_GETVRINITERRORASENGLISHDESCRIPTION VR_GetVRInitErrorAsEnglishDescription;

	void* loadOpenVR()
	{
		void* openvrdll = bx::dlopen(
#if BX_PLATFORM_LINUX
			"libopenvr_api.so"
#elif BX_PLATFORM_OSX
			"libopenvr_api.dylib"
#else
			"openvr_api.dll"
#endif // BX_PLATFORM_*
			);
		if (NULL != openvrdll)
		{
			VR_InitInternal            = (PFN_VR_INITINTERNAL           )bx::dlsym(openvrdll, "VR_InitInternal");
			VR_ShutdownInternal        = (PFN_VR_SHUTDOWNINTERNAL       )bx::dlsym(openvrdll, "VR_ShutdownInternal");
			VR_IsHmdPresent            = (PFN_VR_ISHMDPRESENT           )bx::dlsym(openvrdll, "VR_IsHmdPresent");
			VR_GetGenericInterface     = (PFN_VR_GETGENERICINTERFACE    )bx::dlsym(openvrdll, "VR_GetGenericInterface");
			VR_IsRuntimeInstalled      = (PFN_VR_ISRUNTIMEINSTALLED     )bx::dlsym(openvrdll, "VR_IsRuntimeInstalled");
			VR_IsInterfaceVersionValid = (PFN_VR_ISINTERFACEVERSIONVALID)bx::dlsym(openvrdll, "VR_IsInterfaceVersionValid");
			VR_GetInitToken            = (PFN_VR_GETINITTOKEN           )bx::dlsym(openvrdll, "VR_GetInitToken");
			VR_GetVRInitErrorAsSymbol             = (PFN_VR_GETVRINITERRORASSYMBOL            )bx::dlsym(openvrdll, "VR_GetVRInitErrorAsSymbol");
			VR_GetVRInitErrorAsEnglishDescription = (PFN_VR_GETVRINITERRORASENGLISHDESCRIPTION)bx::dlsym(openvrdll, "VR_GetVRInitErrorAsEnglishDescription");

			if (NULL == VR_InitInternal
			||  NULL == VR_ShutdownInternal
			||  NULL == VR_IsHmdPresent
			||  NULL == VR_GetGenericInterface
			||  NULL == VR_IsRuntimeInstalled
			||  NULL == VR_IsInterfaceVersionValid
			||  NULL == VR_GetInitToken
			||  NULL == VR_GetVRInitErrorAsSymbol
			||  NULL == VR_GetVRInitErrorAsEnglishDescription)
			{
				bx::dlclose(openvrdll);
				return NULL;
			}

			EVRInitError err;
			uint32_t token = VR_InitInternal(&err, EVRApplicationType_VRApplication_Scene);
			BX_UNUSED(token);

			BX_TRACE("OpenVR: HMD is %spresent, Runtime is %sinstalled."
				, VR_IsHmdPresent() ? "" : "not "
				, VR_IsRuntimeInstalled() ? "" : "not "
				);
		}

		return openvrdll;
	}

	void unloadOpenVR(void* _openvrdll)
	{
		VR_ShutdownInternal();
		bx::dlclose(_openvrdll);
	}

} // namespace bgfx


text:
package org.apache.isis.core.metamodel.spec.feature;

import org.apache.isis.applib.annotation.When;
import org.apache.isis.applib.annotation.Where;
import org.apache.isis.core.metamodel.adapter.ObjectAdapter;
import org.apache.isis.core.metamodel.consent.Consent;
import org.apache.isis.core.metamodel.consent.InteractionInitiatedBy;
import org.apache.isis.core.metamodel.facets.all.hide.HiddenFacet;

/**
 * Provides reflective access to an action or a field on a domain object.
 */
public interface ObjectMember extends ObjectFeature {

    // /////////////////////////////////////////////////////////////
    // Name, Description, Help (convenience for facets)
    // /////////////////////////////////////////////////////////////

    /**
     * Return the help text for this member - the field or action - to
     * complement the description.
     *
     * @see #getDescription()
     */
    String getHelp();

    // /////////////////////////////////////////////////////////////
    // Hidden (or visible)
    // /////////////////////////////////////////////////////////////

    /**
     * When the member is always hidden.
     *
     *

     * Determined as per the {@link HiddenFacet} being present and
     * {@link HiddenFacet#when()} returning {@link When#ALWAYS}, and
     * {@link HiddenFacet#where()} returning {@link When#ANYWHERE}.
     */
    boolean isAlwaysHidden();

    /**
     * Determines if this member is visible, represented as a {@link Consent}.
     * @param target
     *            may be <tt>null</tt> if just checking for authorization.
     * @param interactionInitiatedBy
     * @param where
     */
    Consent isVisible(
            final ObjectAdapter target,
            final InteractionInitiatedBy interactionInitiatedBy,
            final Where where);

    // /////////////////////////////////////////////////////////////
    // Disabled (or enabled)
    // /////////////////////////////////////////////////////////////

    /**
     * Determines whether this member is usable, represented as a
     * {@link Consent}.
     * @param target
     *            may be <tt>null</tt> if just checking for authorization.
     * @param interactionInitiatedBy
     * @param where
     */
    Consent isUsable(
            final ObjectAdapter target,
            final InteractionInitiatedBy interactionInitiatedBy,
            final Where where);

    // /////////////////////////////////////////////////////////////
    // isAssociation, isAction
    // /////////////////////////////////////////////////////////////

    /**
     * Whether this member represents a {@link ObjectAssociation}.
     *
     *

     * If so, can be safely downcast to {@link ObjectAssociation}.
     */
    boolean isPropertyOrCollection();

    /**
     * Whether this member represents a {@link OneToManyAssociation}.
     *
     *

     * If so, can be safely downcast to {@link OneToManyAssociation}.
     */
    boolean isOneToManyAssociation();

    /**
     * Whether this member represents a {@link OneToOneAssociation}.
     *
     *

     * If so, can be safely downcast to {@link OneToOneAssociation}.
     */
    boolean isOneToOneAssociation();

    /**
     * Whether this member represents a {@link ObjectAction}.
     *
     *

     * If so, can be safely downcast to {@link ObjectAction}.
     */
    boolean isAction();

    // /////////////////////////////////////////////////////////////
    // Debugging
    // /////////////////////////////////////////////////////////////

    String debugData();

    /**
     * Thrown if the user is not authorized to access an action or any property/collection of an entity.
     *
     *

     *     For the former case, is thrown by
     *     {@link ObjectAction#executeWithRuleChecking(org.apache.isis.core.metamodel.adapter.ObjectAdapter, org.apache.isis.core.metamodel.adapter.ObjectAdapter[], org.apache.isis.core.commons.authentication.AuthenticationSession, org.apache.isis.applib.annotation.Where)}
     *     when the action being executed is not visible or not usable for the specified session.  One reason this
     *     might occur if there was an attempt to construct a URL (eg a bookmarked action) and invoke in an unauthenticated session.
     *

     *
     *

     *     For the latter case, is thrown by <tt>EntityPage</tt>
     *
     *

     */
    class AuthorizationException extends RuntimeException {

        public AuthorizationException() {
            this(null);
        }
        public AuthorizationException(final RuntimeException ex) {
            super("Not authorized or no such object", ex);
        }

    }
}


text:
package com.huayu.meits.storm.kafka.trident;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.huayu.meits.storm.kafka.DynamicBrokersReader;
import com.huayu.meits.storm.kafka.ZkHosts;

import java.util.Map;

public class ZkBrokerReader implements IBrokerReader {

	public static final Logger LOG = LoggerFactory.getLogger(ZkBrokerReader.class);

	GlobalPartitionInformation cachedBrokers;
	DynamicBrokersReader reader;
	long lastRefreshTimeMs;

	long refreshMillis;

	public ZkBrokerReader(Map conf, String topic, ZkHosts hosts) {
		try {
			reader = new DynamicBrokersReader(conf, hosts.brokerZkStr, hosts.brokerZkPath, topic);
			cachedBrokers = reader.getBrokerInfo();
			lastRefreshTimeMs = System.currentTimeMillis();
			refreshMillis = hosts.refreshFreqSecs * 1000L;
		} catch (java.net.SocketTimeoutException e) {
			LOG.warn("Failed to update brokers", e);
		}

	}

	@Override
	public GlobalPartitionInformation getCurrentBrokers() {
		long currTime = System.currentTimeMillis();
		if (currTime > lastRefreshTimeMs + refreshMillis) {
			try {
				LOG.info("brokers need refreshing because " + refreshMillis + "ms have expired");
				cachedBrokers = reader.getBrokerInfo();
				lastRefreshTimeMs = currTime;
			} catch (java.net.SocketTimeoutException e) {
				LOG.warn("Failed to update brokers", e);
			}
		}
		return cachedBrokers;
	}

	@Override
	public void close() {
		reader.close();
	}
}


text:
<?php

namespace Robo;

use Composer\Autoload\ClassLoader;
use Symfony\Component\Console\Input\ArgvInput;
use Symfony\Component\Console\Input\StringInput;
use Robo\Contract\BuilderAwareInterface;
use Robo\Collection\CollectionBuilder;
use Robo\Common\IO;
use Robo\Exception\TaskExitException;
use League\Container\ContainerAwareInterface;
use League\Container\ContainerAwareTrait;
use League\Container\Exception\ContainerException;
use Consolidation\Config\Util\EnvConfig;
use Symfony\Component\Console\Output\NullOutput;

class Runner implements ContainerAwareInterface
{
    use IO;
    use ContainerAwareTrait;

    const ROBOCLASS = 'RoboFile';
    const ROBOFILE = 'RoboFile.php';

    /**
     * @var string
     */
    protected $roboClass;

    /**
     * @var string
     */
    protected $roboFile;

    /**
     * Working dir of Robo.
     *
     * @var string
     */
    protected $dir;

    /**
     * @var string[]
     */
    protected $errorConditions = [];

    /**
     * GitHub Repo for SelfUpdate.
     *
     * @var string
     */
    protected $selfUpdateRepository = null;

    /**
     * Filename to load configuration from (set to 'robo.yml' for RoboFiles).
     *
     * @var string
     */
    protected $configFilename = 'conf.yml';

    /**
     * @var string prefix for environment variable configuration overrides
     */
    protected $envConfigPrefix = false;

    /**
     * @var null|\Composer\Autoload\ClassLoader
     */
    protected $classLoader = null;

    /**
     * @var string
     */
    protected $relativePluginNamespace;

    /**
     * Class Constructor
     *
     * @param null|string $roboClass
     * @param null|string $roboFile
     */
    public function __construct($roboClass = null, $roboFile = null)
    {
        // set the const as class properties to allow overwriting in child classes
        $this->roboClass = $roboClass ? $roboClass : self::ROBOCLASS ;
        $this->roboFile  = $roboFile ? $roboFile : self::ROBOFILE;
        $this->dir = getcwd();
    }

    /**
     * @param string $msg
     * @param string $errorType
     */
    protected function errorCondition($msg, $errorType)
    {
        $this->errorConditions[$msg] = $errorType;
    }

    /**
     * @param \Symfony\Component\Console\Output\OutputInterface $output
     *
     * @return bool
     */
    protected function loadRoboFile($output)
    {
        // If we have not been provided an output object, make a temporary one.
        if (!$output) {
            $output = new \Symfony\Component\Console\Output\ConsoleOutput();
        }

        // If $this->roboClass is a single class that has not already
        // been loaded, then we will try to obtain it from $this->roboFile.
        // If $this->roboClass is an array, we presume all classes requested
        // are available via the autoloader.
        if (is_array($this->roboClass) || class_exists($this->roboClass)) {
            return true;
        }
        if (!file_exists($this->dir)) {
            $this->errorCondition("Path `{$this->dir}` is invalid; please provide a valid absolute path to the Robofile to load.", 'red');
            return false;
        }

        $realDir = realpath($this->dir);

        $roboFilePath = $realDir . DIRECTORY_SEPARATOR . $this->roboFile;
        if (!file_exists($roboFilePath)) {
            $requestedRoboFilePath = $this->dir . DIRECTORY_SEPARATOR . $this->roboFile;
            $this->errorCondition("Requested RoboFile `$requestedRoboFilePath` is invalid, please provide valid absolute path to load Robofile.", 'red');
            return false;
        }
        require_once $roboFilePath;

        if (!class_exists($this->roboClass)) {
            $this->errorCondition("Class {$this->roboClass} was not loaded.", 'red');
            return false;
        }
        return true;
    }

    /**
     * @param array $argv
     * @param null|string $appName
     * @param null|string $appVersion
     * @param null|\Symfony\Component\Console\Output\OutputInterface $output
     *
     * @return int
     */
    public function execute($argv, $appName = null, $appVersion = null, $output = null)
    {
        $argv = $this->shebang($argv);
        $argv = $this->processRoboOptions($argv);
        $app = null;
        if ($appName && $appVersion) {
            $app = Robo::createDefaultApplication($appName, $appVersion);
        }
        $commandFiles = $this->getRoboFileCommands($output);
        return $this->run($argv, $output, $app, $commandFiles, $this->classLoader);
    }

    /**
     * Return an initialized application loaded with specified commands and configuration.
     *
     * This should ONLY be used for testing purposes. Works well in conjunction with Symfony's CommandTester.
     *
     * @see https://symfony.com/doc/current/console.html#testing-commands
     * @see CommandTestertTest
     * @see CommandTesterTrait
     *
     * @param string|null $appName
     *   Name of the application.
     * @param string|null $appVersion
     *   Version of the application.
     * @param string|array|null $commandFile
     *   Name of the specific command file, or array of commands, that should be included with the application.
     * @param \Robo\Config\Config|null $config
     *   Robo configuration to be used with the application.
     * @param \Composer\Autoload\ClassLoader|null $classLoader
     *   Class loader to use.
     *
     * @return \Robo\Application
     *   Initialized application based on passed configuration and command classes.
     */
    public function getAppForTesting($appName = null, $appVersion = null, $commandFile = null, $config = null, $classLoader = null)
    {
        $app = Robo::createDefaultApplication($appName, $appVersion);
        $output = new NullOutput();
        $container = Robo::createDefaultContainer(null, $output, $app, $config, $classLoader);
        if (!is_null($commandFile) && (is_array($commandFile) || is_string($commandFile))) {
            if (is_string($commandFile)) {
                $commandFile = [$commandFile];
            }
            $this->registerCommandClasses($app, $commandFile);
        }
        return $app;
    }

    /**
     * Get a list of locations where config files may be loaded
     *
     * @param string $userConfig
     *
     * @return string[]
     */
    protected function getConfigFilePaths($userConfig)
    {
        // Look for application config at the root of the application.
        // Find the root relative to this file, considering that Robo itself
        // might be the application, or it might be in the `vendor` directory.
        $roboAppConfig = dirname(__DIR__) . '/' . basename($userConfig);
        if (basename(dirname(__DIR__, 3)) == 'vendor') {
            $roboAppConfig = dirname(__DIR__, 4) . '/' . basename($userConfig);
        }
        $configFiles = [$roboAppConfig, $userConfig];
        if (dirname($userConfig) != '.') {
            $configFiles[] = basename($userConfig);
        }
        return $configFiles;
    }

    /**
     * @param null|array|\Symfony\Component\Console\Input\InputInterface $input
     * @param null|\Symfony\Component\Console\Output\OutputInterface $output
     * @param null|\Robo\Application $app
     * @param array[] $commandFiles
     * @param null|ClassLoader $classLoader
     *
     * @return int
     */
    public function run($input = null, $output = null, $app = null, $commandFiles = [], $classLoader = null)
    {
        // Create default input and output objects if they were not provided
        if (!$input) {
            $input = new StringInput('');
        }
        if (is_array($input)) {
            $input = new ArgvInput($input);
        }
        if (!$output) {
            $output = new \Symfony\Component\Console\Output\ConsoleOutput();
        }
        $this->setInput($input);
        $this->setOutput($output);

        // If we were not provided a container, then create one
        try {
            $this->getContainer();
        } catch (ContainerException $e) {
            $configFiles = $this->getConfigFilePaths($this->configFilename);
            $config = Robo::createConfiguration($configFiles);
            if ($this->envConfigPrefix) {
                $envConfig = new EnvConfig($this->envConfigPrefix);
                $config->addContext('env', $envConfig);
            }
            $container = Robo::createDefaultContainer($input, $output, $app, $config, $classLoader);
            $this->setContainer($container);
            // Automatically register a shutdown function and
            // an error handler when we provide the container.
            $this->installRoboHandlers();
        }

        if (!$app) {
            $app = Robo::application();
        }
        if ($app instanceof \Robo\Application) {
            $app->addSelfUpdateCommand($this->getSelfUpdateRepository());
            if (!isset($commandFiles)) {
                $this->errorCondition("Robo is not initialized here. Please run `robo init` to create a new RoboFile.", 'yellow');
                $app->addInitRoboFileCommand($this->roboFile, $this->roboClass);
                $commandFiles = [];
            }
        }

        if (!empty($this->relativePluginNamespace)) {
            $commandClasses = $this->discoverCommandClasses($this->relativePluginNamespace);
            $commandFiles = array_merge((array)$commandFiles, $commandClasses);
        }

        $this->registerCommandClasses($app, $commandFiles);

        try {
            $statusCode = $app->run($input, $output);
        } catch (TaskExitException $e) {
            $statusCode = $e->getCode() ?: 1;
        }

        // If there were any error conditions in bootstrapping Robo,
        // print them only if the requested command did not complete
        // successfully.
        if ($statusCode) {
            foreach ($this->errorConditions as $msg => $color) {
                // TODO: This was 'yell'. Add styling?
                $output->writeln($msg); // used to wrap at 40 and write in $color
            }
        }
        return $statusCode;
    }

    /**
     * @param \Symfony\Component\Console\Output\OutputInterface $output
     *
     * @return null|string
     */
    protected function getRoboFileCommands($output)
    {
        if (!$this->loadRoboFile($output)) {
            return;
        }
        return $this->roboClass;
    }

    /**
     * @param \Robo\Application $app
     * @param array $commandClasses
     */
    public function registerCommandClasses($app, $commandClasses)
    {
        foreach ((array)$commandClasses as $commandClass) {
            $this->registerCommandClass($app, $commandClass);
        }
    }

    /**
     * @param string $relativeNamespace
     *
     * @return string[]
     */
    protected function discoverCommandClasses($relativeNamespace)
    {
        /** @var \Robo\ClassDiscovery\RelativeNamespaceDiscovery $discovery */
        $discovery = Robo::service('relativeNamespaceDiscovery');
        $discovery->setRelativeNamespace($relativeNamespace . '\Commands')
            ->setSearchPattern('/.*Commands?\.php$/');
        return $discovery->getClasses();
    }

    /**
     * @param \Robo\Application $app
     * @param string|BuilderAwareInterface|ContainerAwareInterface $commandClass
     *
     * @return null|object
     */
    public function registerCommandClass($app, $commandClass)
    {
        $container = Robo::getContainer();
        $roboCommandFileInstance = $this->instantiateCommandClass($commandClass);
        if (!$roboCommandFileInstance) {
            return;
        }

        // Register commands for all of the public methods in the RoboFile.
        $commandFactory = $container->get('commandFactory');
        $commandList = $commandFactory->createCommandsFromClass($roboCommandFileInstance);
        foreach ($commandList as $command) {
            $app->add($command);
        }
        return $roboCommandFileInstance;
    }

    /**
     * @param string|\Robo\Contract\BuilderAwareInterface|\League\Container\ContainerAwareInterface $commandClass
     *
     * @return null|object
     */
    protected function instantiateCommandClass($commandClass)
    {
        $container = Robo::getContainer();

        // Register the RoboFile with the container and then immediately
        // fetch it; this ensures that all of the inflectors will run.
        // If the command class is already an instantiated object, then
        // just use it exactly as it was provided to us.
        if (is_string($commandClass)) {
            if (!class_exists($commandClass)) {
                return;
            }
            $reflectionClass = new \ReflectionClass($commandClass);
            if ($reflectionClass->isAbstract()) {
                return;
            }

            $commandFileName = "{$commandClass}Commands";
            Robo::addShared($container, $commandFileName, $commandClass);
            $commandClass = $container->get($commandFileName);
        }
        // If the command class is a Builder Aware Interface, then
        // ensure that it has a builder.  Every command class needs
        // its own collection builder, as they have references to each other.
        if ($commandClass instanceof BuilderAwareInterface) {
            $builder = CollectionBuilder::create($container, $commandClass);
            $commandClass->setBuilder($builder);
        }
        if ($commandClass instanceof ContainerAwareInterface) {
            $commandClass->setContainer($container);
        }
        return $commandClass;
    }

    public function installRoboHandlers()
    {
        register_shutdown_function(array($this, 'shutdown'));
        set_error_handler(array($this, 'handleError'));
    }

    /**
     * Process a shebang script, if one was used to launch this Runner.
     *
     * @param array $args
     *
     * @return array $args
     *   With shebang script removed.
     */
    protected function shebang($args)
    {
        // Option 1: Shebang line names Robo, but includes no parameters.
        // #!/bin/env robo
        // The robo class may contain multiple commands; the user may
        // select which one to run, or even get a list of commands or
        // run 'help' on any of the available commands as usual.
        if ((count($args) > 1) && $this->isShebangFile($args[1])) {
            return array_merge([$args[0]], array_slice($args, 2));
        }
        // Option 2: Shebang line stipulates which command to run.
        // #!/bin/env robo mycommand
        // The robo class must contain a public method named 'mycommand'.
        // This command will be executed every time.  Arguments and options
        // may be provided on the commandline as usual.
        if ((count($args) > 2) && $this->isShebangFile($args[2])) {
            return array_merge([$args[0]], explode(' ', $args[1]), array_slice($args, 3));
        }
        return $args;
    }

    /**
     * Determine if the specified argument is a path to a shebang script.
     * If so, load it.
     *
     * @param string $filepath
     *   File to check.
     *
     * @return bool
     *   Returns TRUE if shebang script was processed.
     */
    protected function isShebangFile($filepath)
    {
        // Avoid trying to call $filepath on remote URLs
        if ((strpos($filepath, '://') !== false) && (substr($filepath, 0, 7) != 'file://')) {
            return false;
        }
        if (!is_file($filepath)) {
            return false;
        }
        $fp = fopen($filepath, "r");
        if ($fp === false) {
            return false;
        }
        $line = fgets($fp);
        $result = $this->isShebangLine($line);
        if ($result) {
            while ($line = fgets($fp)) {
                $line = trim($line);
                if ($line == '<?php') {
                    $script = stream_get_contents($fp);
                    if (preg_match('#^class *([^ ]+)#m', $script, $matches)) {
                        $this->roboClass = $matches[1];
                        eval($script);
                        $result = true;
                    }
                }
            }
        }
        fclose($fp);

        return $result;
    }

    /**
     * Test to see if the provided line is a robo 'shebang' line.
     *
     * @param string $line
     *
     * @return bool
     */
    protected function isShebangLine($line)
    {
        return ((substr($line, 0, 2) == '#!') && (strstr($line, 'robo') !== false));
    }

    /**
     * Check for Robo-specific arguments such as --load-from, process them,
     * and remove them from the array.  We have to process --load-from before
     * we set up Symfony Console.
     *
     * @param array $argv
     *
     * @return array
     */
    protected function processRoboOptions($argv)
    {
        // loading from other directory
        $pos = $this->arraySearchBeginsWith('--load-from', $argv) ?: array_search('-f', $argv);
        if ($pos === false) {
            return $argv;
        }

        $passThru = array_search('--', $argv);
        if (($passThru !== false) && ($passThru < $pos)) {
            return $argv;
        }

        if (substr($argv[$pos], 0, 12) == '--load-from=') {
            $this->dir = substr($argv[$pos], 12);
        } elseif (isset($argv[$pos + 1])) {
            $this->dir = $argv[$pos + 1];
            unset($argv[$pos + 1]);
        }
        unset($argv[$pos]);
        // Make adjustments if '--load-from' points at a file.
        if (is_file($this->dir) || (substr($this->dir, -4) == '.php')) {
            $this->roboFile = basename($this->dir);
            $this->dir = dirname($this->dir);
            $className = basename($this->roboFile, '.php');
            if ($className != $this->roboFile) {
                $this->roboClass = $className;
            }
        }
        // Convert directory to a real path, but only if the
        // path exists. We do not want to lose the original
        // directory if the user supplied a bad value.
        $realDir = realpath($this->dir);
        if ($realDir) {
            chdir($realDir);
            $this->dir = $realDir;
        }

        return $argv;
    }

    /**
     * @param string $needle
     * @param string[] $haystack
     *
     * @return bool|int
     */
    protected function arraySearchBeginsWith($needle, $haystack)
    {
        for ($i = 0; $i < count($haystack); ++$i) {
            if (substr($haystack[$i], 0, strlen($needle)) == $needle) {
                return $i;
            }
        }
        return false;
    }

    public function shutdown()
    {
        $error = error_get_last();
        if (!is_array($error)) {
            return;
        }
        $this->writeln(sprintf("<error>ERROR: %s \nin %s:%d\n</error>", $error['message'], $error['file'], $error['line']));
    }

    /**
     * This is just a proxy error handler that checks the current error_reporting level.
     * In case error_reporting is disabled the error is marked as handled, otherwise
     * the normal internal error handling resumes.
     *
     * @return bool
     */
    public function handleError()
    {
        if (error_reporting() === 0) {
            return true;
        }
        return false;
    }

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

    /**
     * @param $selfUpdateRepository
     *
     * @return $this
     */
    public function setSelfUpdateRepository($selfUpdateRepository)
    {
        $this->selfUpdateRepository = $selfUpdateRepository;
        return $this;
    }

    /**
     * @param string $configFilename
     *
     * @return $this
     */
    public function setConfigurationFilename($configFilename)
    {
        $this->configFilename = $configFilename;
        return $this;
    }

    /**
     * @param string $envConfigPrefix
     *
     * @return $this
     */
    public function setEnvConfigPrefix($envConfigPrefix)
    {
        $this->envConfigPrefix = $envConfigPrefix;
        return $this;
    }

    /**
     * @param \Composer\Autoload\ClassLoader $classLoader
     *
     * @return $this
     */
    public function setClassLoader(ClassLoader $classLoader)
    {
        $this->classLoader = $classLoader;
        return $this;
    }

    /**
     * @param string $relativeNamespace
     *
     * @return $this
     */
    public function setRelativePluginNamespace($relativeNamespace)
    {
        $this->relativePluginNamespace = $relativeNamespace;
        return $this;
    }
}


text:
package com.chinamobile.bcbsp.fault.storage;

import java.io.File;
import java.io.IOException;
import java.io.Serializable;

import org.mortbay.log.Log;

/**
 * record the filePath in local and hdfs
 */
@SuppressWarnings("serial")
public class DirRecord implements Serializable, Cloneable {
  /**hdfs file num*/
  private int hdfsFileNum = 13;
  /**local file num*/
  private int localFileNum = 5;
  /**local file index length*/
  private int indexl = 0;
  /**hdfs file index length*/
  private int indexh = 0;
  /**hdfs file string list*/
  private String[] hdfsfilelists = new String[hdfsFileNum];
  /**local file list*/
  private File[] localfilelists = new File[localFileNum];
  /**file copy flag*/
  boolean copyFlag = false;
  // ---------------------localfile=--------------------------------------
  /**
   * record file path in DirRecord return last month directory position in order
   * to compress
   * @param file
   *        file path to record
   * @return
   *        last month directory position
   */
  public int pushLocalFile(File file) {
    localfilelists[indexl] = file;
    indexl = (indexl + 1) % localFileNum;
    deleteLocalFile(indexl);
    return ((indexl - 2) + localFileNum) % localFileNum;
  }

  /**
   * get local file list
   * @param indexl
   *        file list length
   * @return
   *        local file list.
   */
  public File getLocalFile(int indexl) {
    return localfilelists[indexl];
  }

  /**
   * delete local file.
   * @param indexl
   *        local file list length.
   */
  public void deleteLocalFile(int indexl) {
    if (localfilelists[indexl] == null) {
      return;
    } else if (localfilelists[indexl].exists()) {
      try {
        File localParentFile = localfilelists[indexl].getParentFile();
        del(localfilelists[indexl].getAbsolutePath());
        Log.info("localParentFile == null" + (localParentFile == null));
        if (localParentFile.listFiles().length == 0) { // delete year
          del(localParentFile.getAbsolutePath());
        }
      } catch (IOException e) {
        throw new RuntimeException("[deleteLocalFile] ", e);
        //e.printStackTrace();
      }
      localfilelists[indexl] = null;
    }
  }

  // --------------HDFS--------------------------------

  /**
   * return overdue directory and delete it from hdfs
   * @param filepath
   *        hdfsfile path
   * @return file list length
   */
  public int pushHdfsFile(String filepath) {
    hdfsfilelists[indexh] = filepath;
    indexh = (indexh + 1) % hdfsFileNum;
    return indexh;
  }

  /**
   * get hdfs file list.
   * @param indexh
   *        hdfs file length
   * @return hdfs file list.
   */
  public String getHdfsFile(int indexh) {
    return hdfsfilelists[indexh];
  }

  /**
   * delete hdfs file.
   * @param indexh
   *        hdfs file length.
   */
  public void deleteHdfsFile(int indexh) {
    if (hdfsfilelists[indexh] != null) {
      hdfsfilelists[indexh] = null;
    }
  }

  /**
   * get file list length
   * @return list length
   */
  public int getIndexl() {
    return indexl;
  }

  /**
   * set  local file list length
   * @param indexl
   *        list length to be set.
   */
  public void setIndexl(int indexl) {
    this.indexl = indexl;
  }

  /**
   * get local file list length
   * @return file list length
   */
  public int getIndexh() {
    return indexh;
  }

  /**
   * set hdfs file list length
   * @param indexh
   *        list length to be set.
   */
  public void setIndexh(int indexh) {
    this.indexh = indexh;
  }

  /**
   * get the local file num.
   * @return
   *        local file num.
   */
  public int getLocalFileNum() {
    return localFileNum;
  }

  /**
   * set local file num
   * @param localFileNum
   *        local file num to be set.
   */
  public void setLocalFileNum(int localFileNum) {
    this.localFileNum = localFileNum;
  }

  /**
   * get the hdfs file num
   * @return
   *        hdfs file num.
   */
  public int getHdfsFileNum() {
    return hdfsFileNum;
  }

  /**
   * set hdfs file num
   * @param hdfsFileNum
   *        hdfs file num to be set.
   */
  public void setHdfsFileNum(int hdfsFileNum) {
    this.hdfsFileNum = hdfsFileNum;
  }

  /**
   * delete file.
   * @param filepath
   *        need deleting file path
   * @throws IOException
   *         exceptions during delete the file.
   */
  public void del(String filepath) throws IOException {
    File f = new File(filepath);
    if (f.exists() && f.isDirectory()) {
      if (f.listFiles().length == 0) {
        f.delete();
      } else {
        File[] delFile = f.listFiles();
        int i = f.listFiles().length;
        for (int j = 0; j < i; j++) {
          if (delFile[j].isDirectory()) {
            del(delFile[j].getAbsolutePath());
          }
          delFile[j].delete();
        }
      }
      f.delete();
    }
  }

  /**
   * clone the dirRecord.
   * @return cloned dirrecord.
   * @throws CloneNotSupportedException
   *         incaset the dirrecord doesn't support clone.
   */
  @Override
  public DirRecord clone() throws CloneNotSupportedException {
    DirRecord dr;
    dr = (DirRecord) super.clone();
    dr.hdfsfilelists = this.hdfsfilelists.clone();
    dr.localfilelists = this.localfilelists.clone();
    return dr;
  }

  /**
   * if the DirRecord is copied
   * @return record copyFlag
   */
  public boolean isCopyFlag() {
    return copyFlag;
  }

  /**
   * set the record copyflag
   * @param copyFlag
   *        copyflag to be set.
   */
  public void setCopyFlag(boolean copyFlag) {
    this.copyFlag = copyFlag;
  }
}


text:
namespace ui {

namespace test {
class CountCheckingLayerAnimationObserver;
class LayerAnimationObserverTestApi;
}  // namespace test

class LayerAnimationSequence;
class ScopedLayerAnimationSettings;
class ImplicitAnimationObserver;

// LayerAnimationObservers are notified when animations complete.
class COMPOSITOR_EXPORT LayerAnimationObserver  {
 public:
  // Called when the |sequence| starts.
  virtual void OnLayerAnimationStarted(LayerAnimationSequence* sequence);

  // Called when the |sequence| ends. Not called if |sequence| is aborted.
  virtual void OnLayerAnimationEnded(
      LayerAnimationSequence* sequence) = 0;

  // Called when a |sequence| repetition ends and will repeat. Not called if
  // |sequence| is aborted.
  virtual void OnLayerAnimationWillRepeat(LayerAnimationSequence* sequence) {}

  // Called if |sequence| is aborted for any reason. Should never do anything
  // that may cause another animation to be started.
  virtual void OnLayerAnimationAborted(
      LayerAnimationSequence* sequence) = 0;

  // Called when the animation is scheduled.
  virtual void OnLayerAnimationScheduled(
      LayerAnimationSequence* sequence) = 0;

 protected:
  typedef std::set<LayerAnimationSequence*> AttachedSequences;

  LayerAnimationObserver();
  virtual ~LayerAnimationObserver();

  // If the LayerAnimator is destroyed during an animation, the animations are
  // aborted. The resulting NotifyAborted notifications will NOT be sent to
  // this observer if this function returns false. An observer who wants to
  // receive the NotifyAborted notifications during destruction can override
  // this function to return true.
  //
  // *** IMPORTANT ***: If a class overrides this function to return true and
  // that class is a direct or indirect owner of the LayerAnimationSequence
  // being observed, then the class must explicitly remove itself as an
  // observer during destruction of the LayerAnimationObserver! This is to
  // ensure that a partially destroyed observer isn't notified with an
  // OnLayerAnimationAborted() call when the LayerAnimator is destroyed.
  //
  // This opt-in pattern is used because it is common for a class to be the
  // observer of a LayerAnimationSequence that it owns indirectly because it
  // owns the Layer which owns the LayerAnimator which owns the
  // LayerAnimationSequence.
  virtual bool RequiresNotificationWhenAnimatorDestroyed() const;

  // Called when |this| is added to |sequence|'s observer list.
  virtual void OnAttachedToSequence(LayerAnimationSequence* sequence);

  // Called when |this| is removed to |sequence|'s observer list.
  virtual void OnDetachedFromSequence(LayerAnimationSequence* sequence);

  // Called when the relevant animator attaches to an animation timeline.
  virtual void OnAnimatorAttachedToTimeline() {}

  // Called when the relevant animator detaches from an animation timeline.
  virtual void OnAnimatorDetachedFromTimeline() {}

  // Detaches this observer from all sequences it is currently observing.
  void StopObserving();

  const AttachedSequences& attached_sequences() const {
    return attached_sequences_;
  }

 private:
  friend class LayerAnimationSequence;
  friend class test::CountCheckingLayerAnimationObserver;
  friend class test::LayerAnimationObserverTestApi;

  // Called when |this| is added to |sequence|'s observer list.
  void AttachedToSequence(LayerAnimationSequence* sequence);

  // Called when |this| is removed to |sequence|'s observer list.
  // This will only result in notifications if |send_notification| is true.
  void DetachedFromSequence(LayerAnimationSequence* sequence,
                            bool send_notification);

  AttachedSequences attached_sequences_;
};

// An implicit animation observer is intended to be used in conjunction with a
// ScopedLayerAnimationSettings object in order to receive a notification when
// all implicit animations complete.
// TODO(bruthig): Unify the ImplicitAnimationObserver with the
// CallbackLayerAnimationObserver. (See www.crbug.com/542825).
class COMPOSITOR_EXPORT ImplicitAnimationObserver
    : public LayerAnimationObserver {
 public:
  ImplicitAnimationObserver();
  ~ImplicitAnimationObserver() override;

  // Called when the first animation sequence has started.
  virtual void OnImplicitAnimationsScheduled() {}

  virtual void OnImplicitAnimationsCompleted() = 0;

 protected:
  // Deactivates the observer and clears the collection of animations it is
  // waiting for.
  void StopObservingImplicitAnimations();

  // Returns whether animation for |property| was aborted.
  // Note that if the property wasn't animated, then it couldn't have been
  // aborted, so this will return false for that property.
  bool WasAnimationAbortedForProperty(
      LayerAnimationElement::AnimatableProperty property) const;

  // Returns whether animation for |property| was completed successfully.
  // Note that if the property wasn't animated, then it couldn't have been
  // completed, so this will return false for that property.
  bool WasAnimationCompletedForProperty(
      LayerAnimationElement::AnimatableProperty property) const;

 private:
  enum AnimationStatus {
    ANIMATION_STATUS_UNKNOWN,
    ANIMATION_STATUS_COMPLETED,
    ANIMATION_STATUS_ABORTED,
  };

  friend class ScopedLayerAnimationSettings;

  // LayerAnimationObserver implementation
  void OnLayerAnimationEnded(LayerAnimationSequence* sequence) override;
  void OnLayerAnimationAborted(LayerAnimationSequence* sequence) override;
  void OnLayerAnimationScheduled(LayerAnimationSequence* sequence) override;
  void OnAttachedToSequence(LayerAnimationSequence* sequence) override;
  void OnDetachedFromSequence(LayerAnimationSequence* sequence) override;

  // OnImplicitAnimationsCompleted is not fired unless the observer is active.
  bool active() const { return active_; }
  void SetActive(bool active);

  void CheckCompleted();

  void UpdatePropertyAnimationStatus(LayerAnimationSequence* sequence,
                                     AnimationStatus status);
  AnimationStatus AnimationStatusForProperty(
      LayerAnimationElement::AnimatableProperty property) const;

  bool active_ = false;

  typedef std::map<LayerAnimationElement::AnimatableProperty,
                   AnimationStatus> PropertyAnimationStatusMap;
  PropertyAnimationStatusMap property_animation_status_;

  // True if OnLayerAnimationScheduled() has been called at least once.
  bool first_sequence_scheduled_ = false;

  // For tracking whether this object has been destroyed. Must be last.
  base::WeakPtrFactory<ImplicitAnimationObserver> weak_factory_{this};
};

}  // namespace ui

#endif  // UI_COMPOSITOR_LAYER_ANIMATION_OBSERVER_H_


text:
cookbook_file "#{node.disk.dir}/microboshes/Gemfile" do
  source "Gemfile.micro"
  owner node.user.username
  group node.user.username
  mode "0644"
end

directory "#{node.disk.dir}/microboshes" do
  owner node.user.username
  group node.user.username
  mode "0755"
  recursive true
  action :create
end

bash "install bosh micro" do
  cwd "#{node.disk.dir}/microboshes"
  user node.user.username
  code "source /etc/profile.d/chruby.sh; bundle install"
  action :run
end

cookbook_file "#{node.disk.dir}/systems/Gemfile" do
  source "Gemfile.cf"
  owner node.user.username
  group node.user.username
  mode "0644"
end

bash "install bosh cf" do
  cwd "#{node.disk.dir}/systems"
  user node.user.username
  code "source /etc/profile.d/chruby.sh; bundle install"
  action :run
end


text:
require 'active_support/inflector'

module BS::Reporters
  class BaseReporter
    def self.descendants
      ObjectSpace.each_object(Class).select { |klass| klass < self }
    end

    def self.reporter_name
      name.demodulize
    end

    def self.config_name
      reporter_name.underscore.gsub(/_reporter$/, '')
    end

    def report(config)
      # report commit/status
    end

    def report_settings(commits)
      # report settings before runnint
    end

    private

    def is_sha?(ref)
      /^[0-9a-f]{40}$/ === ref
    end

    def shorten_if_sha(ref)
      if is_sha?(ref)
        ref[0...6]
      else
        ref
      end
    end
  end
end


text:
package com.organic.maynard.util.crawler;

import com.organic.maynard.util.crawler.FileFilter;

import java.io.*;
import java.util.*;
import org.apache.oro.io.GlobFilenameFilter;
import org.apache.oro.text.GlobCompiler;

public class TypeGlobFileFilter implements FileFilter {

	// Constants
	private static final String GLOB_SEPERATOR = ";";

	// Declare Fields
	private ArrayList globIncludeFilters = new ArrayList();
	private ArrayList globExcludeFilters = new ArrayList();

	// Constructors
	public TypeGlobFileFilter() {}

	public TypeGlobFileFilter(
		String typeGlobIncludeListString,
		boolean ignoreCaseInclude,
		String typeGlobExcludeListString,
		boolean ignoreCaseExclude
	) {
		// Create Include Globs
		StringTokenizer tok = new StringTokenizer(typeGlobIncludeListString, GLOB_SEPERATOR);
		while (tok.hasMoreElements()) {
			String glob = tok.nextToken();

			GlobFilenameFilter filter = null;

			if (ignoreCaseInclude) {
				filter = new GlobFilenameFilter(glob, GlobCompiler.CASE_INSENSITIVE_MASK);
			} else {
				filter = new GlobFilenameFilter(glob);
			}

			globIncludeFilters.add(filter);
		}

		// Create Exclude Globs
		tok = new StringTokenizer(typeGlobExcludeListString, GLOB_SEPERATOR);
		while (tok.hasMoreElements()) {
			String glob = tok.nextToken();

			GlobFilenameFilter filter = null;

			if (ignoreCaseExclude) {
				filter = new GlobFilenameFilter(glob, GlobCompiler.CASE_INSENSITIVE_MASK);
			} else {
				filter = new GlobFilenameFilter(glob);
			}

			globExcludeFilters.add(filter);
		}
	}

	// FileFilter Interface
        @Override
	public boolean isValid(File file) {
		if (globIncludeFilters.size() > 0) {
			boolean matchFound = false;
			for (int i = 0; i < globIncludeFilters.size(); i++) {
				GlobFilenameFilter filter = (GlobFilenameFilter) globIncludeFilters.get(i);
				if (filter.accept(file)) {
					matchFound = true;
					break;
				}
			}

			if (!matchFound) {
				return false;
			}
		}

		for (int i = 0; i < globExcludeFilters.size(); i++) {
			GlobFilenameFilter filter = (GlobFilenameFilter) globExcludeFilters.get(i);
			if (filter.accept(file)) {
				return false;
			}
		}

		return true;
	}
}


text:
<?php
namespace CityPay\Lib;

/**
 *
 */
class UnsupportedOperationException
    extends \Exception
{

}


text:
<?php

namespace Adyen\Payment\Gateway\Data\Order;

use Adyen\Payment\Api\Data\AddressAdapterInterface;
use Magento\Sales\Api\Data\OrderAddressInterface;

class AddressAdapter extends \Magento\Payment\Gateway\Data\Order\AddressAdapter implements AddressAdapterInterface
{
    /**
     * @var OrderAddressInterface
     */
    private $address;

    public function __construct(OrderAddressInterface $address)
    {
        $this->address = $address;
        parent::__construct($address);
    }

    public function getStreetLine3()
    {
        $street = $this->address->getStreet();
        return isset($street[2]) ? $street[2] : '';
    }

    public function getStreetLine4()
    {
        $street = $this->address->getStreet();
        return isset($street[3]) ? $street[3] : '';
    }
}


text:
from distutils.core import setup

VERSION = "0.0.1"

setup(
    author='Nikolai Tschacher',
    name = "proxychecker",
    version = VERSION,
    description = "A Python proxychecker module that makes use of socks",
    url = "http://incolumitas.com",
    license = "BSD",
    author_email = "admin@incolumitas.com",
    keywords = ["socks", "proxy", "proxychecker"],
    py_modules = ['proxychecker', 'sockshandler', 'socks']
)


text:
require File.join(File.dirname(__FILE__), '..', '..', 'spec_helper')

describe YARD::Parser::Ruby::RubyParser do
  def stmt(stmt)
    YARD::Parser::Ruby::RubyParser.new(stmt, nil).parse.root.first
  end

  def stmts(stmts)
    YARD::Parser::Ruby::RubyParser.new(stmts, nil).parse.root
  end

  def tokenize(stmt)
    YARD::Parser::Ruby::RubyParser.new(stmt, nil).parse.tokens
  end

  describe '#parse' do
    it "should get comment line numbers" do
      s = stmt <<-eof
        # comment
        # comment
        # comment
        def method; end
      eof
      s.comments.should == "comment\ncomment\ncomment"
      s.comments_range.should == (1..3)

      s = stmt <<-eof

        # comment
        # comment
        def method; end
      eof
      s.comments.should == "comment\ncomment"
      s.comments_range.should == (2..3)

      s = stmt <<-eof
        # comment
        # comment

        def method; end
      eof
      s.comments.should == "comment\ncomment"
      s.comments_range.should == (1..2)

      s = stmt <<-eof
        # comment
        def method; end
      eof
      s.comments.should == "comment"
      s.comments_range.should == (1..1)

      s = stmt <<-eof
        def method; end # comment
      eof
      s.comments.should == "comment"
      s.comments_range.should == (1..1)
    end

    it "should only look up to two lines back for comments" do
      s = stmts <<-eof
        # comments

        # comments

        def method; end
      eof
      s[1].comments.should == "comments"

      s = stmts <<-eof
        # comments

        def method; end
      eof
      s[1].comments.should == nil

      ss = stmts <<-eof
        # comments

        def method; end

        # hello
        def method2; end
      eof
      ss[1].comments.should == nil
      ss[2].comments.should == 'hello'
    end

    it "should handle block comment followed by line comment" do
      ss = stmts <<-eof
# comments1

=begin
comments2
=end
# comments3
def hello; end
eof
      ss.last.comments.should == "comments3"
    end

    it "should handle block comment followed by block comment" do
      ss = stmts <<-eof
=begin
comments1
=end
=begin
comments2
=end
def hello; end
eof
      ss.last.comments.strip.should == "comments2"
    end

    it "should handle 1.9 lambda syntax with args" do
      src = "->(a,b,c=1,*args,&block) { hello_world }"
      stmt(src).source.should == src
    end

    it "should handle 1.9 lambda syntax" do
      src = "-> { hello_world }"
      stmt(src).source.should == src
    end

    it "should handle standard lambda syntax" do
      src = "lambda { hello_world }"
      stmt(src).source.should == src
    end

    it "should throw a ParserSyntaxError on invalid code" do
      lambda { stmt("Foo, bar.") }.should raise_error(YARD::Parser::ParserSyntaxError)
    end

    it "should handle bare hashes as method parameters" do
      src = "command :a => 1, :b => 2, :c => 3"
      stmt(src).jump(:command)[1].source.should == ":a => 1, :b => 2, :c => 3"

      src = "command a: 1, b: 2, c: 3"
      stmt(src).jump(:command)[1].source.should == "a: 1, b: 2, c: 3"
    end

    it "should handle source for hash syntax" do
      src = "{ :a => 1, :b => 2, :c => 3 }"
      stmt(src).jump(:hash).source.should == "{ :a => 1, :b => 2, :c => 3 }"
    end

    it "should handle an empty hash" do
      stmt("{}").jump(:hash).source.should == "{}"
    end

    it "new hash label syntax should show label without colon" do
      ast = stmt("{ a: 1 }").jump(:label)
      ast[0].should == "a"
      ast.source.should == "a:"
    end

    it "should handle begin/rescue blocks" do
      ast = stmt("begin; X; rescue => e; Y end").jump(:rescue)
      ast.source.should == "rescue => e; Y end"

      ast = stmt("begin; X; rescue A => e; Y end").jump(:rescue)
      ast.source.should == "rescue A => e; Y end"

      ast = stmt("begin; X; rescue A, B => e; Y end").jump(:rescue)
      ast.source.should == "rescue A, B => e; Y end"
    end

    it "should handle method rescue blocks" do
      ast = stmt("def x; A; rescue Y; B end")
      ast.source.should == "def x; A; rescue Y; B end"
      ast.jump(:rescue).source.should == "rescue Y; B end"
    end

    it "should handle defs with keywords as method name" do
      ast = stmt("# docstring\nclass A;\ndef class; end\nend")
      ast.jump(:class).docstring.should == "docstring"
      ast.jump(:class).line_range.should == (2..4)
    end

    it 'should handle defs with unnamed argument with default values' do
      ast = stmt('def hello(one, two = 2, three = 3) end').jump(:params)
      ast.source.should == 'one, two = 2, three = 3'
    end

    it 'should handle defs with splats' do
      ast = stmt('def hello(one, *two) end').jump(:params)
      ast.source.should == 'one, *two'
    end

    if YARD.ruby2?
      it 'should handle defs with named arguments with default values' do
        ast = stmt('def hello(one, two: 2, three: 3) end').jump(:params)
        ast.source.should == 'one, two: 2, three: 3'
      end
    end

    if NAMED_OPTIONAL_ARGUMENTS
      it 'should handle defs with named arguments without default values' do
        ast = stmt('def hello(one, two:, three:) end').jump(:params)
        ast.source.should == 'one, two:, three:'
      end

      it 'should handle defs with double splats' do
        ast = stmt('def hello(one, **two) end').jump(:params)
        ast.source.should == 'one, **two'
      end
    end

    it "should end source properly on array reference" do
      ast = stmt("AS[0, 1 ]   ")
      ast.source.should == 'AS[0, 1 ]'

      ast = stmt('def x(a = S[1]) end').jump(:params)
      ast.source.should == 'a = S[1]'
    end

    it "should end source properly on if/unless mod" do
      %w(if unless while).each do |mod|
        stmt("A=1 #{mod} true").source.should == "A=1 #{mod} true"
      end
    end

    it "should show proper source for assignment" do
      stmt("A=1").jump(:assign).source.should == "A=1"
    end

    it "should show proper source for a top_const_ref" do
      s = stmt("::\nFoo::Bar")
      s.jump(:top_const_ref).source.should == "::\nFoo"
      s.should be_ref
      s.jump(:top_const_ref).should be_ref
      s.source.should == "::\nFoo::Bar"
      s.line_range.to_a.should == [1, 2]
    end

    it "should show proper source for inline heredoc" do
      src = "def foo\n  foo(<<-XML, 1, 2)\n    bar\n\n  XML\nend"
      s = stmt(src)
      t = tokenize(src)
      s.source.should == src
      t.map {|x| x[1] }.join.should == src
    end

    it "should show proper source for regular heredoc" do
      src = "def foo\n  x = <<-XML\n  Hello \#{name}!\n  Bye!\n  XML\nend"
      s = stmt(src)
      t = tokenize(src)
      s.source.should == src
      t.map {|x| x[1] }.join.should == src
    end

    it "should show proper source for heredoc with comment" do
      src = "def foo\n  x = <<-XML # HI!\n  Hello \#{name}!\n  Bye!\n  XML\nend"
      s = stmt(src)
      t = tokenize(src)
      s.source.should == src
      t.map {|x| x[1] }.join.should == src
    end

    it "should show proper source for string" do
      ["'", '"'].each do |q|
        src = "#{q}hello\n\nworld#{q}"
        s = stmt(src)
        s.jump(:string_content).source.should == "hello\n\nworld"
        s.source.should == src
      end

      src = '("this is a string")'
      stmt(src).jump(:string_literal).source.should == '"this is a string"'
    end

    it "should show proper source for %w() array" do
      src = "%w(\na b c\n d e f\n)"
      stmt(src).jump(:qwords_literal).source.should == src
    end

    it "should show proper source for %w{} array" do
      src = "%w{\na b c\n d e f\n}"
      stmt(src).jump(:array).source.should == src
    end

    it "should parse %w() array in constant declaration" do
      s = stmt(<<-eof)
        class Foo
          FOO = %w( foo bar )
        end
      eof
      s.jump(:qwords_literal).source.should == '%w( foo bar )'
      if RUBY_VERSION >= '1.9.3' # ripper fix: array node encapsulates qwords
        s.jump(:array).source.should == '%w( foo bar )'
      end
    end

    it "should parse %w() array source in object[] parsed context" do
      s = stmts(<<-eof)
        {}[:key]
        FOO = %w( foo bar )
      eof
      s[1].jump(:array).source.should == '%w( foo bar )'
    end

    it "should parse %w() array source in object[]= parsed context" do
      s = stmts(<<-eof)
        {}[:key] = :value
        FOO = %w( foo bar )
      eof
      s[1].jump(:array).source.should == '%w( foo bar )'
    end

    it "should parse [] as array" do
      s = stmt(<<-eof)
        class Foo
          FOO = ['foo', 'bar']
        end
      eof
      s.jump(:array).source.should == "['foo', 'bar']"
    end

    it "should show source for unary minus" do
      stmt("X = - 1").jump(:unary).source.should == '- 1'
    end

    it "should show source for unary exclamation" do
      stmt("X = !1").jump(:unary).source.should == '!1'
    end

    it "should have the correct line range for class/modules" do
      s = stmt(<<-eof)
        class Foo
          def foo; end

          # Ending comment
        end
      eof
      s.jump(:class).line_range.should == (1..7)
    end

    it "should find lone comments" do
      Registry.clear
      ast = YARD.parse_string(<<-eof).enumerator
        class Foo
          ##
          # comment here

          def foo; end

          # end comment
        end
      eof
      comment = ast.first.last.first
      comment.type.should == :comment
      comment.docstring_hash_flag.should be_true
      comment.docstring.strip.should == "comment here"

      ast.first.last.last.type.should == :comment
      ast.first.last.last.docstring.should == "end comment"
    end
  end
end if HAVE_RIPPER


text:
The `Spree::PromotionAction` model defines an action that should occur if the
promotion is activated and eligible to be applied. There can be multiple
promotion actions on a promotion.

Typically, a promotion action could be free shipping or a fixed percentage
discount.

A promotion action calculates the discount amount and creates a
`Spree::Adjustment` for the promotion. The adjustment then adjusts the price of
an order, line item, or shipment.

Promotion actions have a configurable base calculator (except for
`Spree::Promotion::Actions::FreeShipping`). This gives you and store
administrators flexibility for choosing how a promotion amount is calculated.

<!-- TODO:
  Once calculator documentation exists, link to it in the above paragraph so
  there's more context for anyone wondering what a "base calculator" is in
  Solidus.

  Similarly, we should link to the adjustments documentation once it's merged.
-->

## Available promotion action types

The following classes are [subclasses of the `Spree::Promotion::Actions`
model][promotion-actions]:

- `CreateAdjustment`: Creates a single adjustment associated to the current
  `Spree::Order`.
- `CreateItemAdjustments`: Creates an adjustment for each applicable
  `Spree::LineItem` in the current order.
- `CreateQuantityAdjustments`: Creates per-quantity adjustments. For example,
  you could create an action that gives customers a discount on each group of
  three t-shirts that they order at once.
- `FreeShipping`: Creates an adjustment that negates all shipping charges.

We recommend using `CreateItemAdjustments`s over `CreateAdjustment`. Over-level
adjustments can make calculating accurate refunds and some regions' taxes more
difficult for administrators.

[promotion-actions]: https://github.com/solidusio/solidus/tree/master/core/app/models/spree/promotion/actions

## Eligibility

Note that whenever an order, line item, or shipment with a promotion adjustment
on it is updated, the [eligibility][eligibility] of the promotion is re-checked
and the promotion actions are re-applied.

[eligibility]: overview.html#eligibility

## Register a custom promotion action

You can create a new promotion action for Solidus by creating a new class that
inherits from `Spree::PromotionAction`:

```ruby
# app/models/spree/promotion/actions/my_promotion_action.rb
module Spree
  class Promotion
    module Actions
      class MyPromotionAction < Spree::PromotionAction
        def perform(options={})
          ...
        end

        def remove_from(order)
          ...
        end
```

Your promotion action must implement the `perform(options = {})` method. This
method should return a boolean that declares whether the action was applied
successfully. We also recommend that you define a `remove_from(order)` method.
See the
[`Spree::Promotion::Actions::CreateItemAdjustments`][create-item-adjustments]
class for an example of these method definitions.

You must then register the custom action in an initializer in your
`config/initializers/` directory:

```ruby
Rails.application.config.spree.promotions.actions << MyNamespace::MyPromotionAction
```

[create-item-adjustments]: https://github.com/solidusio/solidus/blob/master/core/app/models/spree/promotion/actions/create_item_adjustments.rb


text:
class RubyBuild < Formula
  desc "Install various Ruby versions and implementations"
  homepage "https://github.com/rbenv/ruby-build"
  url "https://github.com/rbenv/ruby-build/archive/v20151028.tar.gz"
  sha256 "3c83ae35c48869404884603b784927a8bd1d3e041c555996afb1286fc20aa708"

  bottle :unneeded

  head "https://github.com/rbenv/ruby-build.git"

  depends_on "autoconf" => [:recommended, :run]
  depends_on "pkg-config" => [:recommended, :run]
  depends_on "openssl" => :recommended

  def install
    ENV["PREFIX"] = prefix
    system "./install.sh"
  end

  test do
    system "#{bin}/ruby-build", "--definitions"
  end
end


text:
package npetzall.queue.object.codec;

import npetzall.queue.object.api.Encoder;

import java.nio.charset.Charset;

public class StringEncoder implements Encoder<String> {

    private final Charset charset;

    public StringEncoder(Charset charset) {
        this.charset = charset;
    }

    @Override
    public byte[] encode(String element) {
        return element.getBytes(charset);
    }
}


text:
using Ets.Mobile.Client.Contracts;
using System.Linq;
using System.Reactive.Linq;

namespace Ets.Mobile.Client.Extensions.Moodle
{
    public static class MoodleExceptionHandlerExtensions
    {
        public static void HandleError(this IMoodleService This, string exceptionMessage, params string[] strings)
        {
            strings?.Where(str => !string.IsNullOrEmpty(str)).ToObservable().Do(x =>
            {
                throw new MoodleException(exceptionMessage);
            });
        }

        public static void HandleError(this IMoodleService This, object[] objects, string exceptionMessage)
        {
            if (objects == null || objects.Length == 0)
            {
                throw new MoodleException(exceptionMessage);
            }
        }
    }
}


text:
package strategy;

public class SSDCach implements Cach {

	@Override
	public void cacheData(int location, byte[] data) {
		System.out.println("Caching not avaliable");
	}

}


text:
package com.google.gerrit.acceptance.rest.project;

import static com.google.common.truth.Truth.assertThat;
import static com.google.gerrit.acceptance.GitUtil.cloneProject;
import static com.google.gerrit.acceptance.GitUtil.fetch;

import com.google.gerrit.acceptance.AbstractDaemonTest;
import com.google.gerrit.acceptance.PushOneCommit;
import com.google.gerrit.reviewdb.client.RefNames;
import com.google.gerrit.server.project.ProjectState;

import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.junit.TestRepository;
import org.eclipse.jgit.lib.Config;
import org.junit.Before;
import org.junit.Test;

public class ProjectLevelConfigIT extends AbstractDaemonTest {
  @Before
  public void setUp() throws Exception {
    fetch(git, RefNames.REFS_CONFIG + ":refs/heads/config");
    testRepo.reset("refs/heads/config");
  }

  @Test
  public void accessProjectSpecificConfig() throws Exception {
    String configName = "test.config";
    Config cfg = new Config();
    cfg.setString("s1", null, "k1", "v1");
    cfg.setString("s2", "ss", "k2", "v2");
    PushOneCommit push =
        pushFactory.create(db, admin.getIdent(), testRepo, "Create Project Level Config",
            configName, cfg.toText());
    push.to(RefNames.REFS_CONFIG);

    ProjectState state = projectCache.get(project);
    assertThat(state.getConfig(configName).get().toText()).isEqualTo(
        cfg.toText());
  }

  @Test
  public void nonExistingConfig() {
    ProjectState state = projectCache.get(project);
    assertThat(state.getConfig("test.config").get().toText()).isEqualTo("");
  }

  @Test
  public void withInheritance() throws Exception {
    String configName = "test.config";

    Config parentCfg = new Config();
    parentCfg.setString("s1", null, "k1", "parentValue1");
    parentCfg.setString("s1", null, "k2", "parentValue2");
    parentCfg.setString("s2", "ss", "k3", "parentValue3");
    parentCfg.setString("s2", "ss", "k4", "parentValue4");

    Git parentGit =
        cloneProject(sshSession.getUrl() + "/" + allProjects.get(), false);
    TestRepository<?> parentTestRepo =
        new TestRepository<>(parentGit.getRepository());
    fetch(parentGit, RefNames.REFS_CONFIG + ":refs/heads/config");
    parentTestRepo.reset("refs/heads/config");
    PushOneCommit push =
        pushFactory.create(db, admin.getIdent(), parentTestRepo, "Create Project Level Config",
            configName, parentCfg.toText());
    push.to(RefNames.REFS_CONFIG);

    Config cfg = new Config();
    cfg.setString("s1", null, "k1", "childValue1");
    cfg.setString("s2", "ss", "k3", "childValue2");
    push = pushFactory.create(db, admin.getIdent(), testRepo, "Create Project Level Config",
        configName, cfg.toText());
    push.to(RefNames.REFS_CONFIG);

    ProjectState state = projectCache.get(project);

    Config expectedCfg = new Config();
    expectedCfg.setString("s1", null, "k1", "childValue1");
    expectedCfg.setString("s1", null, "k2", "parentValue2");
    expectedCfg.setString("s2", "ss", "k3", "childValue2");
    expectedCfg.setString("s2", "ss", "k4", "parentValue4");

    assertThat(state.getConfig(configName).getWithInheritance().toText())
        .isEqualTo(expectedCfg.toText());

    assertThat(state.getConfig(configName).get().toText()).isEqualTo(
        cfg.toText());
  }
}


text:
from __future__ import unicode_literals

from django.db import models, migrations
import datetime

class Migration(migrations.Migration):

    dependencies = [
        ('form_processor', '0024_rename_case_type'),
    ]

    operations = [
        migrations.AddField(
            model_name='caseforms',
            name='server_date',
            field=models.DateTimeField(default=datetime.datetime(2015, 11, 13, 9, 21, 40, 422766)),
            preserve_default=False,
        ),
    ]


text:
package de.beyondjava.bootsfaces.examples;

import java.util.Date;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;

@ViewScoped
@ManagedBean
public class Person {

    private String firstName;
    private String lastName;
    private Date birthdate;
    public Date getBirthdate() {
        return birthdate;
    }
    public void setBirthdate(Date birthdate) {
        this.birthdate = birthdate;
    }
    public String getLastName() {
        return lastName;
    }
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
    public String getFirstName() {
        return firstName;
    }
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

}


text:
/*****************************************************************************/
/**
 *  @file   PreIntegrationTable3D.h
 *  @author Naohisa Sakamoto
 */
/*----------------------------------------------------------------------------
 *
 * Acknowledgements:
 * Original source code was developped by University of Utah and can be
 * downloaded at http://havs.sourceforge.net/
 */
/*****************************************************************************/
#ifndef KVS__PRE_INTEGRATION_TABLE_3D_H_INCLUDE
#define KVS__PRE_INTEGRATION_TABLE_3D_H_INCLUDE

#include <kvs/Vector4>
#include <kvs/ValueArray>
#include <kvs/TransferFunction>

namespace kvs
{

/*===========================================================================*/
/**
 *  @brief  PreItegrationTable3D class.
 */
/*===========================================================================*/
class PreIntegrationTable3D
{
private:

    kvs::ValueArray<kvs::Real32> m_transfer_function; ///< serialized transfer function
    kvs::ValueArray<kvs::Real32> m_table; ///< 3D pre-integration table
    size_t m_scalar_resolution; ///< resolution of the scalar axis
    size_t m_depth_resolution; ///< resolution of the depth axis

public:

    PreIntegrationTable3D();
    PreIntegrationTable3D( const size_t scalar_resolution, const size_t depth_resolution );

    size_t scalarResolution() const { return m_scalar_resolution; }
    size_t depthResolution() const { return m_depth_resolution; }
    const kvs::Vector3ui resolution() const { return kvs::Vector3ui( m_scalar_resolution, m_scalar_resolution, m_depth_resolution); }
    const kvs::ValueArray<kvs::Real32>& table() const { return m_table; }

    void setScalarResolution( const size_t scalar_resolution ) { m_scalar_resolution = scalar_resolution; }
    void setDepthResolution( const size_t depth_resolution ) { m_depth_resolution = depth_resolution; }
    void setTransferFunction( const kvs::TransferFunction& transfer_function, const float min_scalar, const float max_scalar );

    void create( const float max_size_of_cell );

private:

    void compute_exact_level( float* slice0, const float dl );
    void compute_incremental_level( float* slice, const float* slicep, const float* slice0, const float l, const float dl );
};

} // end of namespace kvs

#endif // KVS__PRE_INTEGRATION_TABLE_3D_H_INCLUDE


text:
#Moose

##Overview

An ORM for node with these features:

* Migrations
* Associations
* Connection pooling
* Support for multiple databases
* A plugin api, e.g., from examples/plugins/ExpressPlugin.js

```javascript
/*
* Very simple express routing for a model
* */
var moose = require("../../lib"), comb = require("comb");
module.exports = exports = comb.define(null, {
   static : {
       route : function(app){
           app.get("/" + this.tableName + "/:id", comb.hitch(this, function(req, res){
               var id = req.params.id;
               this.findById(id).then(function(model){
                   var response;
                   if(model){
                       response = model.toObject();
                   }else{
                       response = {error : "Could not find a model with id " + id};
                   }
                   res.send(response);
               });
           }));
       }
   }
});
```

## Installation

    npm install moose

##Usage

* [Moose](http://pollenware.github.com/moose/symbols/moose.html)
* [Connecting to a database.](http://pollenware.github.com/moose/symbols/moose.html#createConnection)
* Models
  * [Define a model](http://pollenware.github.com/moose/symbols/moose.html#addModel)
     * [Model Class](http://pollenware.github.com/moose/symbols/Model.html) returned from defining a model
  * [Associations](http://pollenware.github.com/moose/symbols/moose.plugins.AssociationPlugin.html)
  * [Querying](http://pollenware.github.com/moose/symbols/moose.plugins.QueryPlugin.html)
  * [Caching](http://pollenware.github.com/moose/symbols/moose.plugins.CachePlugin.html)
  * [Timestamp](http://pollenware.github.com/moose/symbols/moose.plugins.TimeStampPlugin.html)
* [Migrations](http://pollenware.github.com/moose/symbols/Migrations.html)
* Adapters
  * [mysql](http://pollenware.github.com/moose/symbols/moose.adapters.mysql.html)
     * [Types](http://pollenware.github.com/moose/symbols/moose.adapters.mysql.types.html)

##License

MIT <https://github.com/Pollenware/moose/raw/master/LICENSE>

##Meta

* Code: `git clone git://github.com/pollenware/moose.git`
* JsDoc: <http://pollenware.github.com/moose>
* Website:  <http://pollenware.com> - Twitter: <http://twitter.com/pollenware> - 877.465.4045