text:
from pyzabbix import ZabbixAPI
import time as time_package
import structures	# sctript with structures
import sys
import getopt
import re

###### LOG CONFIG ######

# limit - maximal number of lines in single category
#LIMIT = 99
# threshold - minimal number of errors in category to be logged
#THRESHOLD = 0

# shortcut for retrieving current time
time = lambda :time_package.strftime('%Y%m%d:%H%M%S')
# shortcut for sorting dict
sort = lambda x: sorted(x.items(), key=lambda x: x[1], reverse=True)

# Function for connecting to zabbix server
def init(server, login, password, sessionVerify = False):
	zapi = ZabbixAPI(server)
	zapi.session.verify = sessionVerify
	zapi.login(login, password)
	return zapi

def getData(zapi):
	# retrieving all unsupported items
	items = zapi.item.get( output=['templateid', 'error', 'type', 'flags'], filter={'state':1,'status':0},selectHosts=['status'])
	# filter out unsupported items belongs to disabled hosts
	items = [ item for item in items if item['hosts'][0]['status'] == '0' ]
	return items

def getDataByAgentType(items):
	types = structures.XDict()
	# counting sum of types of unsuporrted items
	for item in items:
		types + structures.agentTypes[ int(item['type']) ]
	return types

def getDataByAgentTypeByError(items):
	errors = structures.XDict()
	for agentType in structures.agentTypes:
		errors[ agentType ] = structures.XDict()
	# counting the type of error per item type
	for item in items:
		matched = False
		for error, regex in structures.Error.regex.items():
			if re.match(regex, item['error']):
				errors[ structures.agentTypes[ int(item['type']) ]] + error
				matched = True
				break
		if not matched:
			errors[ structures.agentTypes[ int(item['type']) ]] + 'other'
			#pass
			#print(types.id[ int(item['type']) ], item['error'])
	return errors

def getDataByError(items):
	errors = structures.XDict()
	for item in items:
		for error, regex in structures.Error.regex.items():
			if re.match(regex, item['error']):
				errors + error
				break
	return errors

def getDataByTemplate(items, zapi):
	templates = structures.XDict()
	### Nondiscovered items ###
	# dictionary with structure:  templateItemId: templateName
	templateName = dict()

	# list with parent template itemids
	itemids = [ item['templateid'] for item in items if item['templateid'] != '0' and item['flags'] == '0' ]
	# list with parent template items extended by template name
	nonDiscoveryTemplateItems = zapi.item.get(itemids=itemids, output=['itemid'], selectHosts=['name'])

	# populating the templateName with values
	for item in nonDiscoveryTemplateItems:
		templateName[item['itemid']] = item['hosts'][0]['name']

	# Counting unsupported items by parent template
	for item in itemids:
		if templateName.has_key(item):
			templates + templateName[item]

	### Discovered items ###
	# list with itemids of discovered items
	itemids = [ item['itemid'] for item in items if item['flags'] == '4' ]
	# list with discovered items extended by itemid of parent prototype item
	discoveryItems = zapi.item.get( output=['itemid'], itemids=itemids, selectItemDiscovery=['parent_itemid'])
	# list with itemids of parent prototype items
	itemids = [x['itemDiscovery']['parent_itemid'] for x in discoveryItems]
	# list with prototype items extended by parent template itemids
	discoveryPrototypeItems = zapi.itemprototype.get(itemids=itemids, output=['templateid'])
	# list with parent prototype template itemids
	itemids = [ item['templateid'] for item in discoveryPrototypeItems ]
	# list with parent template prototype items extended by template name
	discoveryTemplateItems = zapi.itemprototype.get(itemids=itemids, output=['itemid'], selectHosts=['name'])

	# After all we have:
	# discoveryItems		 : all items created by discovery prototype items with their prototype item ids
	# discoveryPrototypeItems: all prototype items created by discovery in templates with their parent template item ids
	# discoveryTemplateItems : all discovery template prototype items with the template names
	##  so now we have to connect discoveryItems <throught discoveryPrototypeItems> to discoveryTemplateItems
	##  to find out, which discovery item(on host) belongs to which template

	# dictionary with structure:  discoveryItemId: prototypeItemId
	discoveryPrototype = dict()
	# dictionary with structure:  prototypeItemId: prototypeTemplateItemId
	discoveryTemplate = dict()
	# dictionary with structure:  templateItemId:  templateName
	discoveryTemplateName = dict()

	# populate the discoveryPrototype dict with values
	for item in discoveryItems:
		discoveryPrototype[item['itemid']] = item['itemDiscovery']['parent_itemid']
	# populate the discoveryTemplate dict with values
	for itemPrototype in discoveryPrototypeItems:
		discoveryTemplate[itemPrototype['itemid']] = itemPrototype['templateid'] # templateId is not the template id, it is the parent template item id
	# populate the discoveryTemplateName dict with values
	for templateItem in discoveryTemplateItems:
		discoveryTemplateName[templateItem['itemid']] = templateItem['hosts'][0]['name']

	# finally count unsupported items by template
	for item in discoveryItems:
		prototypeItemId = discoveryPrototype[item['itemid']]
		templateItemId = discoveryTemplate[prototypeItemId]
		templateName = discoveryTemplateName[templateItemId]
		templates + templateName  ### Here we are adding 1 <what is 1 unsupported item> to sum of unsupported items by template
	return templates

###### DEVEL LOGGING  ######
#def log():
#	for itemType, count in sort(types.count)[:LIMIT]:
#		if count < THRESHOLD:
#			break
#		print("{time} byType {itemType} {count}".format(time=time(), itemType=itemType, count=count))
#
#	for template, count in sort(templates.count)[:LIMIT]:
#		if count < THRESHOLD:
#			break
#		print("{time} byTemplate {template} {count}".format(time=time(), template=template.replace(,'_'), count=count))
#
#	for error, count in sort(byErrors)[:LIMIT]:
#		if count < THRESHOLD:
#			break;
#		print("{time} byError {error} {count}".format(time=time(), error=error, count=count))
#
#	for itemType, error in sorted(errors.count.items(), key=lambda x: len(x[1].values()), reverse=True): # Sorting by number of various errors in byItemType grouping
#		if len(error.items()) == 0:
#			continue
#		for errorType, count in sort(error):
#			print("{time} byErrorGroupType {itemType} {errorType} {count}".format(time=time(), itemType=itemType, errorType=errorType, count=count))

def log(table, *args):
	pass

def main(argv):
	server = ''
	login = ''
	password = ''
	msg = 'main.py -s|--server <url to api server> -l|--login <api login> -p|--password <api password>'
	try:
		opts, args = getopt.getopt(argv,"hs:l:p:",["server=","login=","password="])
	except getopt.GetoptError:
		print(msg)
		sys.exit(2)
	for opt, arg in opts:
		if opt == '-h':
			print(msg)
			sys.exit()
		elif opt in ("-s", "--server"):
			server = arg
		elif opt in ("-l", "--login"):
			login = arg
		elif opt in ("-p", "--password"):
			password = arg

	if not any([server, login, password]):
		print(msg)
		sys.exit()

	# zapi - Zabbix api connection object
	zapi = init(server=server, login=login, password=password)
	# list with unsupperd items which belongs to enabled hosts
	items = getData(zapi)

	#byAgentType = getDataByAgentType(items)
	#byError = getDataByError(items)
	byAgentTypeByError = getDataByAgentTypeByError(items)
	#byTemplate = getDataByTemplate(items, zapi)

	#print(byAgentType)
	#print(byError)
	#print(byAgentTypeByError)
	for x in sort(byAgentTypeByError):
		print(x)
	#for x in sort(byTemplate)[:20]:
	#	print(x)
	#log(byAgentType)
	#log(byAgentTypeByError)
	#log()

if __name__ == "__main__":
		main(sys.argv[1:])


text:
package h2;

import java.nio.charset.Charset;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

public class EchoServerHandler extends ChannelInboundHandlerAdapter {

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		// ctx.fireChannelRead(msg);
		String readMessage = ((ByteBuf) msg).toString(Charset.defaultCharset());
		System.out.println("¼ö½ÅÇÑ ¸Þ¼¼Áö : "+readMessage);
		ctx.write(msg);
	}

	@Override
	public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
		// ctx.fireChannelReadComplete();
	}

}

redpajama_set_name: RedPajamaGithub


text:
China, 2016-04-29

I hereby agree to the terms of the Odoo Individual Contributor License
Agreement v1.0.

I declare that I am authorized and able to make this agreement and sign this
declaration.

Signed,

Xudong Yang fanderous@gmail.com https://github.com/Wizr


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>TrackerPeerInfo class - hetimatorrent library - Dart API</title>

    <base href="..">

    <link href='https://fonts.googleapis.com/css?family=Source+Code+Pro|Roboto:500,400italic,300,400' rel='stylesheet' type='text/css'>
    <link rel="stylesheet" href="static-assets/prettify.css">
    <link rel="stylesheet" href="static-assets/css/bootstrap.min.css">
    <link rel="stylesheet" href="static-assets/styles.css">

    <meta name="description" content="API docs for the TrackerPeerInfo class from the hetimatorrent library, for the Dart programming language.">
    <link rel="icon" href="static-assets/favicon.png">

            <button id="sidenav-left-toggle" type="button"> </button>

hetimatorrent

hetimatorrent

TrackerPeerInfo

TrackerPeerInfo

hetimatorrent

hetimatorrent

TrackerPeerInfo

class
 TrackerPeerInfo

Properties

Constructors

Operators

Methods

hetimatorrent

hetimatorrent

Functions

objectToString

Classes

Bdecoder

BdecoderAsync

Bencode

BencodeAsync

Bencoder

Bitfield

BitfieldInter

BitfieldPlus

BlockData

CreatePieceHashResult

KBucket

KGetPeerNodes

KGetPeerValue

KId

KNode

KNodeSendInfo

KPeerInfo

KRootingTable

KrpcAnnounce

KrpcError

KrpcFindNode

KrpcGetPeers

KrpcMessage

KrpcPing

KrpcQuery

KrpcResponse

PeerIdCreator

PieceInfo

PieceInfoItem

RequestSingleWaitReturn

SHA1Iso

SHA1IsoInfo

SHA1IsoSub

ShuffleLinkedList

StartResult

StopResult

TMessageBitfield

TMessageCancel

TMessageChoke

TMessageHandshake

TMessageHave

TMessageInterested

TMessageKeepAlive

TMessageNotInterested

TMessageNull

TMessagePiece

TMessagePort

TMessageRequest

TMessageUnchoke

TorrenAIEmpty

TorrentAI

TorrentAIBasic

TorrentAIChokeTest

TorrentAIChokeTestResult

TorrentClient

TorrentClientFront

TorrentClientFrontNerve

TorrentClientManager

TorrentClientMessage

TorrentClientPeerInfo

TorrentClientPeerInfoBasic

TorrentClientPeerInfoEmpty

TorrentClientPeerInfos

TorrentClientSignal

TorrentClientSignalWithFront

TorrentClientSignalWithPeerInfo

TorrentEngine

TorrentEngineAI

TorrentEngineProgress

TorrentEngineTorrent

TorrentFile

TorrentFileCreator

TorrentFileCreatorResult

TorrentFileFile

TorrentFileFiles

TorrentFileInfo

TorrentInfoHashCreator

TorrentMessage

TorrentPieceHashCreator

TrackerClient

TrackerPeerInfo

TrackerPeerManager

TrackerRequest

TrackerRequestResult

TrackerResponse

TrackerServer

TrackerUrl

Exceptions

BencodeParseError

HetiBencodeParseError

Not documented.

Properties

                String
                address

        read / write

                List<int>
                ip

        read / write

                String
                ipAsString

        read-only

                List<int>
                optIp

        read-only

                String
                optIpAsString

        read / write

                List<int>
                peerId

        read / write

                String
                peerIdAsString

        read-only

                int
                port

        read / write

                String
                portdAsString

        read-only

                int
                time

        read-only

Constructors

                TrackerPeerInfo(List<int> _peerId, String _address, List<int> _ip, int _port, [String optIp = ""])

Operators

                  operator ==(<wbr>other)
                      →
                      bool

                  The equality operator.

Methods

                  update(<wbr>)
                      →
                      void

TrackerPeerInfo

Properties

address

ip

ipAsString

optIp

optIpAsString

peerId

peerIdAsString

port

portdAsString

time

Constructors

TrackerPeerInfo

Operators

operator ==

Methods

update

                  hetimatorrent 0.0.1 api docs

                •

                •

                  cc license


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

using System.Linq;
using Cassandra.IntegrationTests.SimulacronAPI.Models.Logs;
using Cassandra.IntegrationTests.TestClusterManagement;
using Cassandra.IntegrationTests.TestClusterManagement.Simulacron;
using Cassandra.Tests;
using NUnit.Framework;

namespace Cassandra.IntegrationTests.Core
{
    [TestFixture, Category(TestCategory.Short)]
    public class ClusterPeersV2SimulacronTests : SimulacronTest
    {
        public ClusterPeersV2SimulacronTests() : base(
            options: new SimulacronOptions { Nodes = "3" },
            simulacronManager: SimulacronManager.GetForPeersTests())
        {
        }

        [Test]
        public void Should_SendRequestsToAllHosts_When_PeersOnSameAddress()
        {
            const string query = "SELECT * FROM ks.table";

            Assert.AreEqual(3, Session.Cluster.AllHosts().Count);
            Assert.IsTrue(Session.Cluster.AllHosts().All(h => h.IsUp));
            Assert.AreEqual(1, Session.Cluster.AllHosts().Select(h => h.Address.Address).Distinct().Count());
            Assert.AreEqual(3, Session.Cluster.AllHosts().Select(h => h.Address.Port).Distinct().Count());

            foreach (var i in Enumerable.Range(0, 10))
            {
                // doesn't exist but doesn't matter
                Session.Execute(query);
            }

            Assert.AreEqual(3, Session.Cluster.AllHosts().Count);
            Assert.IsTrue(Session.Cluster.AllHosts().All(h => h.IsUp));

            var queriesByNode = TestCluster.GetNodes().Select(n => n.GetQueries(query, QueryType.Query));
            Assert.IsTrue(queriesByNode.All(queries => queries.Count >= 1));
        }
    }
}


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <artifactId>motech</artifactId>
        <groupId>org.motechproject</groupId>
        <version>0.18</version>
        <relativePath>../../../</relativePath>
    </parent>
    <groupId>org.motechproject</groupId>
    <artifactId>motech-ivr-verboice</artifactId>
    <version>0.18</version>
    <name>MOTECH IVR Verboice</name>
    <description>IVR over Nuntium's Verboice</description>
    <properties>
        <modules.root.dir>${basedir}/../../..</modules.root.dir>
    </properties>
    <dependencies>
        <dependency>
            <groupId>${project.groupId}</groupId>
            <artifactId>motech-ivr-api-bundle</artifactId>
            <version>${project.version}</version>
        </dependency>
        <dependency>
            <groupId>${project.groupId}</groupId>
            <artifactId>motech-decisiontree-server-bundle</artifactId>
            <version>${project.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>org.springframework.web.servlet</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>com.springsource.org.apache.commons.httpclient</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.velocity</groupId>
            <artifactId>com.springsource.org.apache.velocity</artifactId>
        </dependency>
        <!-- Test -->
        <dependency>
            <groupId>${project.groupId}</groupId>
            <artifactId>motech-testing-utils</artifactId>
            <version>${project.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.mortbay.jetty</groupId>
            <artifactId>com.springsource.org.mortbay.jetty.server</artifactId>
        </dependency>
        <dependency>
            <groupId>org.custommonkey.xmlunit</groupId>
            <artifactId>com.springsource.org.custommonkey.xmlunit</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test-mvc</artifactId>
        </dependency>
    </dependencies>
</project>


text:
<?php declare(strict_types = 1);

namespace JasonRoman\NbaApi\Params\Stats;

class PlayerScopeParam extends AbstractStatsParam
{
    const ALL_PLAYERS = 'All Players';
    const ROOKIES     = 'Rookies';

    const OPTIONS = [
        self::ALL_PLAYERS,
        self::ROOKIES,
    ];
}


text:
import { Request, Response } from "express";
import * as mung from "express-mung";

function redact(body: Object, req: Request, res: Response) {
    return body;
}
mung.json(redact);


text:
package link.ideas.easya.data;

/**
 * Created by Eman on 11/27/2017.
 */

import android.arch.lifecycle.LiveData;
import android.arch.lifecycle.MutableLiveData;
import android.support.annotation.Nullable;
import android.util.Log;

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

import link.ideas.easya.AppExecutors;
import link.ideas.easya.BuildConfig;
import link.ideas.easya.data.database.Course;
import link.ideas.easya.data.database.CourseDao;
import link.ideas.easya.data.database.Lesson;
import link.ideas.easya.data.database.LessonDao;
import link.ideas.easya.data.database.ListLesson;
import link.ideas.easya.data.network.ApiUtils;
import link.ideas.easya.models.Image;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Handled data operation in EasyA.
 */
public class EasyARepository {
    private static final String LOG_TAG = EasyARepository.class.getSimpleName();

    //for Singleton instantiation
    private static final Object LOCK = new Object();
    private static EasyARepository sInstance;
    private final CourseDao mCourseDao;
    private final LessonDao mLessonDao;
    private final AppExecutors mAppExecutors;

    private EasyARepository(CourseDao mCourseDao, LessonDao mLessonDao, AppExecutors mAppExecutors) {
        this.mCourseDao = mCourseDao;
        this.mLessonDao = mLessonDao;
        this.mAppExecutors = mAppExecutors;

        // As long as the repository exists, observe the network LiveData.
        // If that LiveData changes, update the database.
        //todo

    }

    public synchronized static EasyARepository getInstance(
            CourseDao mCourseDao, LessonDao mLessonDao, AppExecutors mAppExecutors) {
        Log.d(LOG_TAG, "Getting the repository");
        if (sInstance == null) {
            synchronized (LOCK) {
                sInstance = new EasyARepository(mCourseDao, mLessonDao,
                        mAppExecutors);
                Log.d(LOG_TAG, "Made new repository");
            }
        }
        return sInstance;
    }

    public LiveData<List<Course>> getUserCourses() {
        return mCourseDao.getCourses();
    }

    public void insertCourse(final Course course) {
        mAppExecutors.diskIO().execute(new Runnable() {
            @Override
            public void run() {
                mCourseDao.insertCourse(course);
            }
        });
    }

    public void updateCourse(final Course course) {
        mAppExecutors.diskIO().execute(new Runnable() {
            @Override
            public void run() {
                mCourseDao.updateCourse(course);
            }
        });
    }

    public void updateFirebaseId(final int id, final String pushId) {
        mAppExecutors.diskIO().execute(new Runnable() {
            @Override
            public void run() {
                mCourseDao.updateFirebaseId(id, pushId);
            }
        });
    }

    public void deleteCourse(final int courseId) {
        mAppExecutors.diskIO().execute(new Runnable() {
            @Override
            public void run() {
                mLessonDao.deleteCourseLessons(courseId);
                mCourseDao.deleteCourse(courseId);

            }
        });
    }

    public LiveData<Course> getUserCourse(int courseId) {
        return mCourseDao.getCourse(courseId);
    }

    public LiveData<List<ListLesson>> getUserLessons(int courseId) {
        return mLessonDao.getLessons(courseId);
    }

    public LiveData<Lesson> getUserLesson(int lessonId) {
        return mLessonDao.getLesson(lessonId);
    }

    public LiveData<List<ListLesson>> getUserFavLessons(int courseId, String fav) {
        return mLessonDao.getFavLessons(courseId, fav);
    }

    public void insertLesson(final Lesson lesson) {
        mAppExecutors.diskIO().execute(new Runnable() {
            @Override
            public void run() {
                mLessonDao.insertLesson(lesson);
            }
        });
    }

    public void updateFirebaseIdL(final int id, final String pushId) {
        mAppExecutors.diskIO().execute(new Runnable() {
            @Override
            public void run() {
                mLessonDao.updateFirebaseId(id, pushId);
            }
        });
    }

    public void updateFavorite(final int id, final String favoriteLesson) {
        mAppExecutors.diskIO().execute(new Runnable() {
            @Override
            public void run() {
                mLessonDao.updateFavorite(id, favoriteLesson);
            }
        });
    }

    public void udDateLesson(final Lesson lesson) {
        mAppExecutors.diskIO().execute(new Runnable() {
            @Override
            public void run() {
                mLessonDao.updateLesson(lesson);
            }
        });
    }

    public void deleteLesson(final int lessonId) {
        mAppExecutors.diskIO().execute(new Runnable() {
            @Override
            public void run() {
                mLessonDao.deleteLesson(lessonId);
            }
        });
    }

    public LiveData<Image> searchQuery(String query) {
        final MutableLiveData<Image> data = new MutableLiveData<>();

        String apiKey = BuildConfig.UNIQUE_FLICKR_KEY;
        ApiUtils.getAppService()
                .getImages(apiKey, query, "20", "json", "1").enqueue(new Callback<Image>() {
            @Override
            public void onResponse(@Nullable Call<Image> call,@Nullable Response<Image> response) {

                if(response.isSuccessful()){
                    data.setValue(response.body());
                }
            }

            @Override
            public void onFailure(@Nullable Call<Image> call,@Nullable Throwable t) {

            }
        });
        return data;
    }

}


text:
if [ -z "$1" ]; then
   echo "specify the file that contains a list of files"
   exit
fi

files=$(cat $1)

mkdir -p out

for item in $files ; do

  dn=$(dirname $item)
  mkdir -p out/$dn
  ~/bin/uncrustify -f $item -c ~/.uncrustify/xsupplicant.cfg > out/$item

done


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "DTD/xhtml1-transitional.dtd">

		<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
		<title>HBase 0.98.7-hadoop2 Reference Package org.apache.hadoop.hbase.regionserver.handler</title>
		<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="style" />

        	org.apache.hadoop.hbase.regionserver.handler

Classes

            	CloseMetaHandler

            	CloseRegionHandler

            	HLogSplitterHandler

            	OpenMetaHandler

            	OpenRegionHandler

            	ParallelSeekHandler

            	PostOpenDeployTasksThread


text:
const querystring = require('querystring');
const request = require('request');
const parse = require('xml2js').parseString;
const moment = require('moment-timezone');

const DATETIME_FORMAT = 'YYYY-MM-DDTHH:mm:ss';
const WS_URL = 'http://webservices.ingv.it/fdsnws/event/1/query';

class Ingv {
	constructor(options = {}) {
		if (!options.startDate) {
			// Get the earthquakes for the last 6 hours
			// Previously 24 hours, but useless
			// see https://github.com/botfactoryit/terremotibot/issues/6
			options.startDate = moment.utc().subtract(6, 'hours');
		}

		if (!options.endDate) {
			// Choose a endDate in the future for the query, in order
			// to be sure to get all the earthquakes
			options.endDate = moment.utc().add(6, 'hours');
		}

		this.startDate = options.startDate;
		this.endDate = options.endDate;

		this.minMagnitude = options.minMagnitude || 2;
		this.maxMagnitude = options.maxMagnitude || 10;

		this.minLatitude = options.minLatitude || 35;
		this.maxLatitude = options.maxLatitude || 49;
		this.minLongitude = options.minLongitude || 5;
		this.maxLongitude = options.maxLongitude || 20;

		this.timeout = options.timeout || 35000;
	}

	get(callback) {
		let qs = {
			starttime: this.startDate.format(DATETIME_FORMAT),
			endtime: this.endDate.format(DATETIME_FORMAT),
			minmag: this.minMagnitude,
			maxmag: this.maxMagnitude,
			minlat: this.minLatitude,
			maxlat: this.maxLatitude,
			minlon: this.minLongitude,
			maxlon: this.maxLongitude
		};

		let url = WS_URL + '?' + querystring.stringify(qs);

		let req = {
			url: url,
			timeout: this.timeout
		};

		let t1 = Date.now();

		// Request the INGV web service
		request(req, (err, response, body) => {
			let t2 = Date.now();
			let delta = t2 - t1;

			// Network error
			if (err) {
				callback({ type: 'networkError', err, time: delta, url });
				return;
			}
			// No events were returned
			else if (response.statusCode == 204) {
				callback(null, { time: delta, data: [] });
				return;
			}
			// Response status code is not positive
			else if (response.statusCode != 200) {
				callback({ type: 'responseError', statusCode: response.statusCode, body: body.replace(/\n/g, ' '), time: delta, url });
				return;
			}

			// Parse the XML response
			parse(body, { explicitArray: false }, (err, result) => {
				// If there was an error parsing the XML payload
				if (err) {
					callback({ type: 'parseError', body: body.replace(/\n/g, ' '), time: delta });
					return;
				}

				// Get the array of events from the QuakeML response
				let events = result['q:quakeml']['eventParameters']['event'];

				// WTF
				if (!events || typeof events != 'object') {
					callback({ type: 'contentError', body: body.replace(/\n/g, ' '), time: delta });
					return;
				}

				// If the response included a single event,
				// 'events' is an object and thus should be converted to an array
				if (!Array.isArray(events)) {
					events = [events];
				}

				let earthquakes = [];

				// Loop through events and extract data
				events.forEach((ev) => {
					// Earthquake ID
					// It will be extracted from the 'publicID' attributes which looks like
					// smi:webservices.ingv.it/fdsnws/event/1/query?eventId=8863681
					// The dollar sign in the expression below allows to access the attributes of an XML node
					let id = ev.$.publicID.split('=')[1];

					// Take out the origin (~hypocenter), and magnitude nodes
					let origin = ev['origin'];
					let magnitude = ev['magnitude'];

					// Extract and parse the datetime of the event
					let dateString = origin['time']['value'];
					let date = moment.utc(dateString).toDate();

					let earthquake = {
						id: id,
						zone: ev['description']['text'],
						date: date,
						origin: {
							lat: parseFloat(origin['latitude']['value']),
							lon: parseFloat(origin['longitude']['value']),
							depth: origin['depth']['value'] / 1000
						},
						stationsCount: parseInt(origin['quality']['associatedStationCount']),
						magnitude: {
							type: magnitude['type'], // ML or Mw
							value: parseFloat(magnitude['mag']['value']),
							uncertainty: parseFloat(magnitude['mag']['uncertainty']) || 0
						}
					};

					earthquakes.push(earthquake);
				});

				callback(null, { time: delta, data: earthquakes });
			});
		});
	}
}

module.exports = Ingv;


text:
<title>
Restricted Access
</title>

  <link href="dataurl.css" rel="stylesheet" />

Proceed


text:
Page Not Found

The page you are looking for could not be found.


text:
using log4net;
using Nini.Config;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using System;
using System.Reflection;

// You will need to uncomment these lines if you are adding a region module to some other assembly which does not already
// specify its assembly.  Otherwise, the region modules in the assembly will not be picked up when OpenSimulator scans
// the available DLLs
//[assembly: Addin("MyModule", "1.0")]
//[assembly: AddinDependency("OpenSim", "0.5")]
namespace OpenSim.Region.OptionalModules.Example.BareBonesShared
{
    /// <summary>
    /// Simplest possible example of a shared region module.
    /// </summary>
    /// <remarks>
    /// This module is the simplest possible example of a shared region module (a module which is shared by every
    /// scene/region running on the simulator).  If anybody wants to create a more complex example in the future then
    /// please create a separate class.
    ///
    /// This module is not active by default.  If you want to see it in action,
    /// then just uncomment the line below starting with [Extension(Path...
    ///
    /// When the module is enabled it will print messages when it receives certain events to the screen and the log
    /// file.
    /// </remarks>
    //[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "BareBonesSharedModule")]
    public class BareBonesSharedModule : ISharedRegionModule
    {
        private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

        public string Name { get { return "Bare Bones Shared Module"; } }

        public Type ReplaceableInterface { get { return null; } }

        public void AddRegion(Scene scene)
        {
            m_log.DebugFormat("[BARE BONES SHARED]: REGION {0} ADDED", scene.RegionInfo.RegionName);
        }

        public void Close()
        {
            m_log.DebugFormat("[BARE BONES SHARED]: CLOSED MODULE");
        }

        public void Initialise(IConfigSource source)
        {
            m_log.DebugFormat("[BARE BONES SHARED]: INITIALIZED MODULE");
        }

        public void PostInitialise()
        {
            m_log.DebugFormat("[BARE BONES SHARED]: POST INITIALIZED MODULE");
        }

        public void RegionLoaded(Scene scene)
        {
            m_log.DebugFormat("[BARE BONES SHARED]: REGION {0} LOADED", scene.RegionInfo.RegionName);
        }

        public void RemoveRegion(Scene scene)
        {
            m_log.DebugFormat("[BARE BONES SHARED]: REGION {0} REMOVED", scene.RegionInfo.RegionName);
        }
    }
}


text:
import threading, requests, time

class InternetConnection(threading.Thread):
    def __init__(self):
        super(InternetConnection, self).__init__()
        self.__connection = self.__checkConnection()
    @staticmethod
    def __checkConnection():
        try:
            requests.get("http://www.google.com", timeout = 5)
        except (requests.ConnectionError, requests.exceptions.ReadTimeout):
            return False
        return True
    def run(self):
        while True:
            self.__connection = self.__checkConnection()
            time.sleep(1)
    def get(self):
        return self.__connection


text:
<!doctype html>

		<meta charset='utf-8' />
		<meta name='viewport' content='width=device-width' />
		<meta http-equiv='X-UA-Compatible' content='ie=edge'>
		<title>Gitlab in your macOS menu bar</title>
		<link rel='stylesheet' href='/public/css/xbar.css?cb=08%20Mar%2021%2015%3a22%20GMT'>
		<link rel='preconnect' href='https://fonts.gstatic.com'>
		<link rel='preconnect' href='https://fonts.googleapis.com'>
		<link rel='stylesheet' href='https://fonts.googleapis.com/css2?family=Bodoni+Moda:wght@500&display=swap'>

	<meta name='description' content='Put Gitlab plugins into your macOS menu bar with xbar.'>
	<meta name='author' content='Mat Ryer + contributors'>
	<meta name='keywords' content='macos,menubar,xbar,bitbar'>
	<meta itemprop='image' content='https://xbarapp.com/public/img/xbar-menu-preview.png'>
	<meta itemprop='name' content='Gitlab in your macOS menu bar'>
	<meta itemprop='description' content='Put Gitlab plugins into your macOS menu bar with xbar.'>
	<meta name='twitter:card' content='summary_large_image'>
	<meta name='twitter:title' content='Gitlab in your macOS menu bar'>
	<meta name='twitter:description' content='Put Gitlab plugins into your macOS menu bar with xbar.'>
	<meta name='twitter:image' content='https://xbarapp.com/public/img/xbar-menu-preview.png'>
	<meta name='twitter:creator' content='matryer'>
	<meta property='og:title' content='Gitlab in your macOS menu bar'>
	<meta property='og:description' content='Put Gitlab plugins into your macOS menu bar with xbar.'>
	<meta property='og:url' content='https://xbarapp.com/plugins/Dev/Gitlab.html'>
	<meta property='og:site_name' content='xbar lets you put anything into your macOS menu bar'>
	<meta property='og:type' content='article'>
	<meta property='og:image' content='https://xbarapp.com/public/img/xbar-menu-preview.png'>
	<link rel='apple-touch-icon' sizes='180x180' href='/public/img/xbar-2048.png'>
	<link rel='icon' type='image/png' sizes='32x32' href='/public/img/xbar-2048.png'>
	<link rel='shortcut icon' href='/public/img/xbar-2048.png'>
	<meta name='msapplication-TileColor' content='#ffffff'>
	<meta name='msapplication-config' content='/public/browserconfig.xml'>
	<meta name='theme-color' content='#ffffff'>

						xbar

						💜 Sponsor

						Coming soon

					AWS

					Cryptocurrency

					Dev

					E-Commerce

					Email

					Environment

					Finance

					Games

					IoT

					Lifestyle

					Music

					Network

					Politics

					Science

					Sports

					System

					Time

					Tools

					Travel

					Weather

					Web

								Featured

									Gitlab status plugin

									Shows the current status of status.gitlab.com. Find out if Gitlab is having DDOS problems which will affect pushes/pulls.

													Brett Jones (@blockloop)

								Featured

									GitLab Merge Requests

													Simeon Cheeseman (@simeonc)

								Featured

									GitLab Projects

									List of your last active GitLab projects. Now supports API v4

													Eighty Grit (@eightygrit)

						Fancy having your plugin featured?

					Get in touch.

						Gitlab CI

									Shows currently running pipelines from your GitLab in your bar. Interested in more advanced GitLab bar integration? Let me know (martin@kluska.cz). This implementation is just quick solution.

										Martin Kluska

											(@pionl)

						Gitlab status plugin

									Shows the current status of status.gitlab.com. Find out if Gitlab is having DDOS problems which will affect pushes/pulls.

										Brett Jones

											(@blockloop)

						GitLab Merge Requests

										Simeon Cheeseman

											(@simeonc)

						GitLab Projects

									List of your last active GitLab projects. Now supports API v4

										Eighty Grit

											(@eightygrit)

						GitHub project
						•
						Writing plugins guide

						Copyright ©2021 Mat Ryer + contributors • @matryer

						Last updated on 08 Mar 21 15:22 GMT


text:
package eu.optique.r2rml.api.model.impl;

import eu.optique.r2rml.api.model.InverseExpression;
import eu.optique.r2rml.api.model.R2RMLVocabulary;
import eu.optique.r2rml.api.model.Template;
import eu.optique.r2rml.api.model.TermMap;
import org.apache.commons.rdf.api.BlankNode;
import org.apache.commons.rdf.api.IRI;
import org.apache.commons.rdf.api.RDF;
import org.apache.commons.rdf.api.RDFTerm;
import org.apache.commons.rdf.api.Triple;

import java.util.HashSet;
import java.util.Set;

import static java.util.Objects.requireNonNull;

/**
 * An implementation of a TermMap. A TermMap must either be a SubjectMap, a
 * PredicateMap, an ObjectMap or a GraphMap, and is therefore abstract.
 *
 * @author Marius Strandhaug
 */
public abstract class TermMapImpl extends MappingComponentImpl implements TermMap {

    TermMapType termMapType;

    IRI termTypeIRI;

    // Only one of these will be set.
    Template template;

    RDFTerm constVal;

    String columnName;

    InverseExpression inverseExp;

    TermMapImpl(RDF rdf, Template template) {
        super(rdf);
        this.template = requireNonNull(template);
        this.termMapType = TermMapType.TEMPLATE_VALUED;
        setDefaultTermType();
        setNode(getRDF().createBlankNode());
    }

    TermMapImpl(RDF rdf, String columnName) {
        super(rdf);
        this.columnName = requireNonNull(columnName);
        this.termMapType = TermMapType.COLUMN_VALUED;
        setDefaultTermType();
        setNode(getRDF().createBlankNode());
    }

    TermMapImpl(RDF rdf, RDFTerm constant) {
        super(rdf);
        this.constVal = requireNonNull(constant);
        if(constant instanceof BlankNode){
            throw new IllegalArgumentException("BlankNode cannot be used as constant");
        } else if (constant instanceof IRI){
            this.termTypeIRI = getRDF().createIRI(R2RMLVocabulary.TERM_IRI);
        } else {// if (constant instanceof Literal)
            this.termTypeIRI = getRDF().createIRI(R2RMLVocabulary.TERM_LITERAL);
        }

        this.termMapType = TermMapType.CONSTANT_VALUED;
        setNode(getRDF().createBlankNode());
    }

    // Is only used by unofficial RDF-star extension
    TermMapImpl(RDF rdf) {
        super(rdf);
        this.termMapType = TermMapType.RDF_STAR_VALUED;
        this.termTypeIRI = null;
        setNode(getRDF().createBlankNode());
    }

    @Override
    public TermMapType getTermMapType() {
        return termMapType;
    }

    @Override
    public void setTermType(IRI typeIRI) {
        if (!getValidTermTypes().contains(typeIRI)) {
            throw new IllegalArgumentException(
                    String.format("invalid term termMapType IRI: %s .", typeIRI));
        }

        switch (termMapType) {
            case TEMPLATE_VALUED:
            case COLUMN_VALUED:
            case RDF_STAR_VALUED:
                this.termTypeIRI = typeIRI;
                break;
            case CONSTANT_VALUED:
                 /*
                  * IGNORE: See R2RML Recommendation Section 7.4:
                  *
                  * NOTE. Constant-valued term maps are not considered as having a term termMapType, and
                  * specifying rr:termType on these term maps has no effect.
                  */
                break;
        }

    }

    @Override
    public void setTemplate(Template template) {
        this.termMapType = TermMapType.TEMPLATE_VALUED;
        this.template = requireNonNull(template);
    }

    @Override
    public void setConstant(RDFTerm constVal) {
        // termTypeIRI will be ignored
        this.termMapType = TermMapType.CONSTANT_VALUED;
        this.constVal = requireNonNull(constVal);
    }

    @Override
    public void setColumn(String columnName) {
        this.termMapType = TermMapType.COLUMN_VALUED;
        this.columnName = requireNonNull(columnName);
    }

    @Override
    public void setInverseExpression(InverseExpression invExp) {
        if (getTermMapType() == TermMapType.COLUMN_VALUED
                || getTermMapType() == TermMapType.TEMPLATE_VALUED) {
            inverseExp = invExp;
        } else {
            throw new IllegalStateException("Wrong TermMapType");
        }
    }

    @Override
    public void setDefaultTermType() {
        termTypeIRI = getRDF().createIRI(R2RMLVocabulary.TERM_IRI);
    }

    @Override
    public IRI getTermType() {
        return termTypeIRI;
    }

    @Override
    public Template getTemplate() {
        return template;
    }

    @Override
    public String getTemplateString() {
        return template.toString();
    }

    @Override
    public RDFTerm getConstant() {
        return constVal;
    }

    @Override
    public String getColumn() {
        return columnName;
    }

    @Override
    public InverseExpression getInverseExpression() {
        return inverseExp;
    }

    @Override
    public String getInverseExpressionString() {
        return inverseExp.toString();
    }

    @Override
    public void removeInverseExpression() {
        inverseExp = null;
    }

    @Override
    public Set<Triple> serialize() {
        Set<Triple> stmtSet = new HashSet<Triple>();

        stmtSet.add(getRDF().createTriple(getNode(), getRDF().createIRI("http://www.w3.org/1999/02/22-rdf-syntax-ns#type"), getRDF().createIRI(R2RMLVocabulary.TYPE_TERM_MAP)));

        if (termMapType == TermMapType.COLUMN_VALUED) {
            stmtSet.add(getRDF().createTriple(getNode(), getRDF().createIRI(R2RMLVocabulary.PROP_COLUMN),
                    getRDF().createLiteral(getColumn())));
        } else if (termMapType == TermMapType.CONSTANT_VALUED) {
            stmtSet.add(getRDF().createTriple(getNode(), getRDF().createIRI(R2RMLVocabulary.PROP_CONSTANT),
                    getConstant()));
        } else if (termMapType == TermMapType.TEMPLATE_VALUED) {
            stmtSet.add(getRDF().createTriple(getNode(), getRDF().createIRI(R2RMLVocabulary.PROP_TEMPLATE),
                    getRDF().createLiteral(getTemplateString())));
        }

        // Will always have the term termMapType explicitly listed.
        stmtSet.add(getRDF().createTriple(getNode(), getRDF().createIRI(R2RMLVocabulary.PROP_TERM_TYPE), termTypeIRI));

        if (getInverseExpression() != null) {

            stmtSet.add(getRDF().createTriple(getNode(), getRDF().createIRI(R2RMLVocabulary.PROP_INVERSE_EXPRESSION),
                    getRDF().createLiteral(getInverseExpressionString())));
        }

        return stmtSet;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result
                + ((columnName == null) ? 0 : columnName.hashCode());
        result = prime * result
                + ((constVal == null) ? 0 : constVal.hashCode());
        result = prime * result + ((getNode() == null) ? 0 : getNode().hashCode());
        result = prime * result
                + ((termTypeIRI == null) ? 0 : termTypeIRI.hashCode());
        result = prime * result + ((termMapType == null) ? 0 : termMapType.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;

        if (obj == null)
            return false;

        if (!(obj instanceof TermMapImpl))
            return false;

        TermMapImpl other = (TermMapImpl) obj;
        if (columnName == null) {
            if (other.columnName != null) {
                return false;
            }
        } else if (!columnName.equals(other.columnName)) {
            return false;
        }

        if (constVal == null) {
            if (other.constVal != null) {
                return false;
            }
        } else if (!constVal.equals(other.constVal)) {
            return false;
        }

        if (getNode() == null) {
            if (other.getNode() != null) {
                return false;
            }
        } else if (!getNode().equals(other.getNode())) {
            return false;
        }

        if (termTypeIRI == null) {
            if (other.termTypeIRI != null) {
                return false;
            }
        } else if (!termTypeIRI.equals(other.termTypeIRI)) {
            return false;
        }

        if (termMapType != other.termMapType) {
            return false;
        }

        return true;
    }

    @Override
    public String toString() {
        return "TermMapImpl [termMapType=" + termMapType + ", termTypeIRI=" + termTypeIRI
                + ", template=" + template + ", constVal=" + constVal
                + ", columnName=" + columnName + ", inverseExp=" + inverseExp
                + ", node=" + getNode() + "]";
    }

}


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package io.prestosql.sql.planner.iterative.rule;

import io.prestosql.matching.Capture;
import io.prestosql.matching.Captures;
import io.prestosql.matching.Pattern;
import io.prestosql.sql.planner.iterative.Rule;
import io.prestosql.sql.planner.plan.LimitNode;
import io.prestosql.sql.planner.plan.SemiJoinNode;

import static io.prestosql.matching.Capture.newCapture;
import static io.prestosql.sql.planner.iterative.rule.Util.transpose;
import static io.prestosql.sql.planner.plan.Patterns.limit;
import static io.prestosql.sql.planner.plan.Patterns.semiJoin;
import static io.prestosql.sql.planner.plan.Patterns.source;

public class PushLimitThroughSemiJoin
        implements Rule<LimitNode>
{
    private static final Capture<SemiJoinNode> CHILD = newCapture();

    // Applies to both limit with ties and limit without ties.
    private static final Pattern<LimitNode> PATTERN = limit()
            .with(source().matching(semiJoin().capturedAs(CHILD)));

    @Override
    public Pattern<LimitNode> getPattern()
    {
        return PATTERN;
    }

    @Override
    public Result apply(LimitNode parent, Captures captures, Context context)
    {
        SemiJoinNode semiJoinNode = captures.get(CHILD);

        if (parent.isWithTies()) {
            // do not push down Limit if ties depend on symbol produced by SemiJoin
            if (parent.getTiesResolvingScheme().get().getOrderBy().contains(semiJoinNode.getSemiJoinOutput())) {
                return Result.empty();
            }
        }
        return Result.ofPlanNode(transpose(parent, semiJoinNode));
    }
}


text:
import sys
import os
import glob
import time
basepath = os.path.abspath(os.path.dirname(__file__))
sys.path.insert(0, os.path.join(basepath, 'gen-py.twisted'))
sys.path.insert(0, glob.glob(os.path.join(basepath, '../../lib/py/build/lib.*'))[0])

from ThriftTest import ThriftTest
from ThriftTest.ttypes import Xception, Xtruct
from thrift.transport import TTwisted
from thrift.protocol import TBinaryProtocol

from twisted.trial import unittest
from twisted.internet import defer, reactor
from twisted.internet.protocol import ClientCreator

from zope.interface import implementer

@implementer(ThriftTest.Iface)
class TestHandler:
    def __init__(self):
        self.onewaysQueue = defer.DeferredQueue()

    def testVoid(self):
        pass

    def testString(self, s):
        return s

    def testByte(self, b):
        return b

    def testI16(self, i16):
        return i16

    def testI32(self, i32):
        return i32

    def testI64(self, i64):
        return i64

    def testDouble(self, dub):
        return dub

    def testBinary(self, thing):
        return thing

    def testStruct(self, thing):
        return thing

    def testException(self, s):
        if s == 'Xception':
            x = Xception()
            x.errorCode = 1001
            x.message = s
            raise x
        elif s == "throw_undeclared":
            raise ValueError("foo")

    def testOneway(self, seconds):
        def fireOneway(t):
            self.onewaysQueue.put((t, time.time(), seconds))
        reactor.callLater(seconds, fireOneway, time.time())

    def testNest(self, thing):
        return thing

    def testMap(self, thing):
        return thing

    def testSet(self, thing):
        return thing

    def testList(self, thing):
        return thing

    def testEnum(self, thing):
        return thing

    def testTypedef(self, thing):
        return thing

class ThriftTestCase(unittest.TestCase):

    @defer.inlineCallbacks
    def setUp(self):
        self.handler = TestHandler()
        self.processor = ThriftTest.Processor(self.handler)
        self.pfactory = TBinaryProtocol.TBinaryProtocolFactory()

        self.server = reactor.listenTCP(
            0, TTwisted.ThriftServerFactory(self.processor, self.pfactory), interface="127.0.0.1")

        self.portNo = self.server.getHost().port

        self.txclient = yield ClientCreator(reactor,
                                            TTwisted.ThriftClientProtocol,
                                            ThriftTest.Client,
                                            self.pfactory).connectTCP("127.0.0.1", self.portNo)
        self.client = self.txclient.client

    @defer.inlineCallbacks
    def tearDown(self):
        yield self.server.stopListening()
        self.txclient.transport.loseConnection()

    @defer.inlineCallbacks
    def testVoid(self):
        self.assertEquals((yield self.client.testVoid()), None)

    @defer.inlineCallbacks
    def testString(self):
        self.assertEquals((yield self.client.testString('Python')), 'Python')

    @defer.inlineCallbacks
    def testByte(self):
        self.assertEquals((yield self.client.testByte(63)), 63)

    @defer.inlineCallbacks
    def testI32(self):
        self.assertEquals((yield self.client.testI32(-1)), -1)
        self.assertEquals((yield self.client.testI32(0)), 0)

    @defer.inlineCallbacks
    def testI64(self):
        self.assertEquals((yield self.client.testI64(-34359738368)), -34359738368)

    @defer.inlineCallbacks
    def testDouble(self):
        self.assertEquals((yield self.client.testDouble(-5.235098235)), -5.235098235)

    # TODO: def testBinary(self) ...

    @defer.inlineCallbacks
    def testStruct(self):
        x = Xtruct()
        x.string_thing = "Zero"
        x.byte_thing = 1
        x.i32_thing = -3
        x.i64_thing = -5
        y = yield self.client.testStruct(x)

        self.assertEquals(y.string_thing, "Zero")
        self.assertEquals(y.byte_thing, 1)
        self.assertEquals(y.i32_thing, -3)
        self.assertEquals(y.i64_thing, -5)

    @defer.inlineCallbacks
    def testException(self):
        yield self.client.testException('Safe')
        try:
            yield self.client.testException('Xception')
            self.fail("should have gotten exception")
        except Xception as x:
            self.assertEquals(x.errorCode, 1001)
            self.assertEquals(x.message, 'Xception')

        try:
            yield self.client.testException("throw_undeclared")
            self.fail("should have thrown exception")
        except Exception:  # type is undefined
            pass

    @defer.inlineCallbacks
    def testOneway(self):
        yield self.client.testOneway(1)
        start, end, seconds = yield self.handler.onewaysQueue.get()
        self.assertAlmostEquals(seconds, (end - start), places=1)


text:
module.exports = function (fork) {
    var types = fork.use(require("./types"));
    var n = types.namedTypes;
    var b = types.builders;
    var isNumber = types.builtInTypes.number;
    var isArray = types.builtInTypes.array;
    var Path = fork.use(require("./path"));
    var Scope = fork.use(require("./scope"));

    function NodePath(value, parentPath, name) {
        if (!(this instanceof NodePath)) {
            throw new Error("NodePath constructor cannot be invoked without 'new'");
        }
        Path.call(this, value, parentPath, name);
    }

    var NPp = NodePath.prototype = Object.create(Path.prototype, {
        constructor: {
            value: NodePath,
            enumerable: false,
            writable: true,
            configurable: true
        }
    });

    Object.defineProperties(NPp, {
        node: {
            get: function () {
                Object.defineProperty(this, "node", {
                    configurable: true, // Enable deletion.
                    value: this._computeNode()
                });

                return this.node;
            }
        },

        parent: {
            get: function () {
                Object.defineProperty(this, "parent", {
                    configurable: true, // Enable deletion.
                    value: this._computeParent()
                });

                return this.parent;
            }
        },

        scope: {
            get: function () {
                Object.defineProperty(this, "scope", {
                    configurable: true, // Enable deletion.
                    value: this._computeScope()
                });

                return this.scope;
            }
        }
    });

    NPp.replace = function () {
        delete this.node;
        delete this.parent;
        delete this.scope;
        return Path.prototype.replace.apply(this, arguments);
    };

    NPp.prune = function () {
        var remainingNodePath = this.parent;

        this.replace();

        return cleanUpNodesAfterPrune(remainingNodePath);
    };

    // The value of the first ancestor Path whose value is a Node.
    NPp._computeNode = function () {
        var value = this.value;
        if (n.Node.check(value)) {
            return value;
        }

        var pp = this.parentPath;
        return pp && pp.node || null;
    };

    // The first ancestor Path whose value is a Node distinct from this.node.
    NPp._computeParent = function () {
        var value = this.value;
        var pp = this.parentPath;

        if (!n.Node.check(value)) {
            while (pp && !n.Node.check(pp.value)) {
                pp = pp.parentPath;
            }

            if (pp) {
                pp = pp.parentPath;
            }
        }

        while (pp && !n.Node.check(pp.value)) {
            pp = pp.parentPath;
        }

        return pp || null;
    };

    // The closest enclosing scope that governs this node.
    NPp._computeScope = function () {
        var value = this.value;
        var pp = this.parentPath;
        var scope = pp && pp.scope;

        if (n.Node.check(value) &&
          Scope.isEstablishedBy(value)) {
            scope = new Scope(this, scope);
        }

        return scope || null;
    };

    NPp.getValueProperty = function (name) {
        return types.getFieldValue(this.value, name);
    };

    /**
     * Determine whether this.node needs to be wrapped in parentheses in order
     * for a parser to reproduce the same local AST structure.
     *
     * For instance, in the expression `(1 + 2) * 3`, the BinaryExpression
     * whose operator is "+" needs parentheses, because `1 + 2 * 3` would
     * parse differently.
     *
     * If assumeExpressionContext === true, we don't worry about edge cases
     * like an anonymous FunctionExpression appearing lexically first in its
     * enclosing statement and thus needing parentheses to avoid being parsed
     * as a FunctionDeclaration with a missing name.
     */
    NPp.needsParens = function (assumeExpressionContext) {
        var pp = this.parentPath;
        if (!pp) {
            return false;
        }

        var node = this.value;

        // Only expressions need parentheses.
        if (!n.Expression.check(node)) {
            return false;
        }

        // Identifiers never need parentheses.
        if (node.type === "Identifier") {
            return false;
        }

        while (!n.Node.check(pp.value)) {
            pp = pp.parentPath;
            if (!pp) {
                return false;
            }
        }

        var parent = pp.value;

        switch (node.type) {
            case "UnaryExpression":
            case "SpreadElement":
            case "SpreadProperty":
                return parent.type === "MemberExpression"
                  && this.name === "object"
                  && parent.object === node;

            case "BinaryExpression":
            case "LogicalExpression":
                switch (parent.type) {
                    case "CallExpression":
                        return this.name === "callee"
                          && parent.callee === node;

                    case "UnaryExpression":
                    case "SpreadElement":
                    case "SpreadProperty":
                        return true;

                    case "MemberExpression":
                        return this.name === "object"
                          && parent.object === node;

                    case "BinaryExpression":
                    case "LogicalExpression":
                        var po = parent.operator;
                        var pp = PRECEDENCE[po];
                        var no = node.operator;
                        var np = PRECEDENCE[no];

                        if (pp > np) {
                            return true;
                        }

                        if (pp === np && this.name === "right") {
                            if (parent.right !== node) {
                                throw new Error("Nodes must be equal");
                            }
                            return true;
                        }

                    default:
                        return false;
                }

            case "SequenceExpression":
                switch (parent.type) {
                    case "ForStatement":
                        // Although parentheses wouldn't hurt around sequence
                        // expressions in the head of for loops, traditional style
                        // dictates that e.g. i++, j++ should not be wrapped with
                        // parentheses.
                        return false;

                    case "ExpressionStatement":
                        return this.name !== "expression";

                    default:
                        // Otherwise err on the side of overparenthesization, adding
                        // explicit exceptions above if this proves overzealous.
                        return true;
                }

            case "YieldExpression":
                switch (parent.type) {
                    case "BinaryExpression":
                    case "LogicalExpression":
                    case "UnaryExpression":
                    case "SpreadElement":
                    case "SpreadProperty":
                    case "CallExpression":
                    case "MemberExpression":
                    case "NewExpression":
                    case "ConditionalExpression":
                    case "YieldExpression":
                        return true;

                    default:
                        return false;
                }

            case "Literal":
                return parent.type === "MemberExpression"
                  && isNumber.check(node.value)
                  && this.name === "object"
                  && parent.object === node;

            case "AssignmentExpression":
            case "ConditionalExpression":
                switch (parent.type) {
                    case "UnaryExpression":
                    case "SpreadElement":
                    case "SpreadProperty":
                    case "BinaryExpression":
                    case "LogicalExpression":
                        return true;

                    case "CallExpression":
                        return this.name === "callee"
                          && parent.callee === node;

                    case "ConditionalExpression":
                        return this.name === "test"
                          && parent.test === node;

                    case "MemberExpression":
                        return this.name === "object"
                          && parent.object === node;

                    default:
                        return false;
                }

            default:
                if (parent.type === "NewExpression" &&
                  this.name === "callee" &&
                  parent.callee === node) {
                    return containsCallExpression(node);
                }
        }

        if (assumeExpressionContext !== true &&
          !this.canBeFirstInStatement() &&
          this.firstInStatement())
            return true;

        return false;
    };

    function isBinary(node) {
        return n.BinaryExpression.check(node)
          || n.LogicalExpression.check(node);
    }

    function isUnaryLike(node) {
        return n.UnaryExpression.check(node)
          // I considered making SpreadElement and SpreadProperty subtypes
          // of UnaryExpression, but they're not really Expression nodes.
          || (n.SpreadElement && n.SpreadElement.check(node))
          || (n.SpreadProperty && n.SpreadProperty.check(node));
    }

    var PRECEDENCE = {};
    [["||"],
        ["&&"],
        ["|"],
        ["^"],
        ["&"],
        ["==", "===", "!=", "!=="],
        ["<", ">", "<=", ">=", "in", "instanceof"],
        [">>", "<<", ">>>"],
        ["+", "-"],
        ["*", "/", "%"]
    ].forEach(function (tier, i) {
        tier.forEach(function (op) {
            PRECEDENCE[op] = i;
        });
    });

    function containsCallExpression(node) {
        if (n.CallExpression.check(node)) {
            return true;
        }

        if (isArray.check(node)) {
            return node.some(containsCallExpression);
        }

        if (n.Node.check(node)) {
            return types.someField(node, function (name, child) {
                return containsCallExpression(child);
            });
        }

        return false;
    }

    NPp.canBeFirstInStatement = function () {
        var node = this.node;
        return !n.FunctionExpression.check(node)
          && !n.ObjectExpression.check(node);
    };

    NPp.firstInStatement = function () {
        return firstInStatement(this);
    };

    function firstInStatement(path) {
        for (var node, parent; path.parent; path = path.parent) {
            node = path.node;
            parent = path.parent.node;

            if (n.BlockStatement.check(parent) &&
              path.parent.name === "body" &&
              path.name === 0) {
                if (parent.body[0] !== node) {
                    throw new Error("Nodes must be equal");
                }
                return true;
            }

            if (n.ExpressionStatement.check(parent) &&
              path.name === "expression") {
                if (parent.expression !== node) {
                    throw new Error("Nodes must be equal");
                }
                return true;
            }

            if (n.SequenceExpression.check(parent) &&
              path.parent.name === "expressions" &&
              path.name === 0) {
                if (parent.expressions[0] !== node) {
                    throw new Error("Nodes must be equal");
                }
                continue;
            }

            if (n.CallExpression.check(parent) &&
              path.name === "callee") {
                if (parent.callee !== node) {
                    throw new Error("Nodes must be equal");
                }
                continue;
            }

            if (n.MemberExpression.check(parent) &&
              path.name === "object") {
                if (parent.object !== node) {
                    throw new Error("Nodes must be equal");
                }
                continue;
            }

            if (n.ConditionalExpression.check(parent) &&
              path.name === "test") {
                if (parent.test !== node) {
                    throw new Error("Nodes must be equal");
                }
                continue;
            }

            if (isBinary(parent) &&
              path.name === "left") {
                if (parent.left !== node) {
                    throw new Error("Nodes must be equal");
                }
                continue;
            }

            if (n.UnaryExpression.check(parent) &&
              !parent.prefix &&
              path.name === "argument") {
                if (parent.argument !== node) {
                    throw new Error("Nodes must be equal");
                }
                continue;
            }

            return false;
        }

        return true;
    }

    /**
     * Pruning certain nodes will result in empty or incomplete nodes, here we clean those nodes up.
     */
    function cleanUpNodesAfterPrune(remainingNodePath) {
        if (n.VariableDeclaration.check(remainingNodePath.node)) {
            var declarations = remainingNodePath.get('declarations').value;
            if (!declarations || declarations.length === 0) {
                return remainingNodePath.prune();
            }
        } else if (n.ExpressionStatement.check(remainingNodePath.node)) {
            if (!remainingNodePath.get('expression').value) {
                return remainingNodePath.prune();
            }
        } else if (n.IfStatement.check(remainingNodePath.node)) {
            cleanUpIfStatementAfterPrune(remainingNodePath);
        }

        return remainingNodePath;
    }

    function cleanUpIfStatementAfterPrune(ifStatement) {
        var testExpression = ifStatement.get('test').value;
        var alternate = ifStatement.get('alternate').value;
        var consequent = ifStatement.get('consequent').value;

        if (!consequent && !alternate) {
            var testExpressionStatement = b.expressionStatement(testExpression);

            ifStatement.replace(testExpressionStatement);
        } else if (!consequent && alternate) {
            var negatedTestExpression = b.unaryExpression('!', testExpression, true);

            if (n.UnaryExpression.check(testExpression) && testExpression.operator === '!') {
                negatedTestExpression = testExpression.argument;
            }

            ifStatement.get("test").replace(negatedTestExpression);
            ifStatement.get("consequent").replace(alternate);
            ifStatement.get("alternate").replace();
        }
    }

    return NodePath;
};


text:
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------

using System;
using Microsoft.Azure.Batch;
using Microsoft.Azure.Batch.Protocol;
using Microsoft.Azure.Batch.Protocol.Models;
using Microsoft.WindowsAzure.Commands.ScenarioTest;
using Moq;
using System.Collections.Generic;
using System.Management.Automation;
using System.Threading.Tasks;
using Xunit;
using BatchClient = Microsoft.Azure.Commands.Batch.Models.BatchClient;

namespace Microsoft.Azure.Commands.Batch.Test.JobSchedules
{
    public class RemoveBatchJobScheduleCommandTests
    {
        private RemoveBatchJobScheduleCommand cmdlet;
        private Mock<BatchClient> batchClientMock;
        private Mock<ICommandRuntime> commandRuntimeMock;

        public RemoveBatchJobScheduleCommandTests()
        {
            batchClientMock = new Mock<BatchClient>();
            commandRuntimeMock = new Mock<ICommandRuntime>();
            cmdlet = new RemoveBatchJobScheduleCommand()
            {
                CommandRuntime = commandRuntimeMock.Object,
                BatchClient = batchClientMock.Object,
            };
        }

        [Fact]
        [Trait(Category.AcceptanceType, Category.CheckIn)]
        public void RemoveBatchJobScheduleParametersTest()
        {
            // Setup cmdlet without the required parameters
            BatchAccountContext context = BatchTestHelpers.CreateBatchContextWithKeys();
            cmdlet.BatchContext = context;

            // Setup cmdlet to skip confirmation popup
            cmdlet.Force = true;
            commandRuntimeMock.Setup(f => f.ShouldProcess(It.IsAny<string>(), It.IsAny<string>())).Returns(true);

            Assert.Throws<ArgumentNullException>(() => cmdlet.ExecuteCmdlet());

            cmdlet.Id = "testJobSchedule";

            // Don't go to the service on a Delete CloudJobSchedule call
            RequestInterceptor interceptor = new RequestInterceptor((baseRequest) =>
            {
                BatchRequest<CloudJobScheduleDeleteParameters, CloudJobScheduleDeleteResponse> request =
                (BatchRequest<CloudJobScheduleDeleteParameters, CloudJobScheduleDeleteResponse>)baseRequest;

                request.ServiceRequestFunc = (cancellationToken) =>
                {
                    CloudJobScheduleDeleteResponse response = new CloudJobScheduleDeleteResponse();
                    Task<CloudJobScheduleDeleteResponse> task = Task.FromResult(response);
                    return task;
                };
            });
            cmdlet.AdditionalBehaviors = new List<BatchClientBehavior>() { interceptor };

            // Verify no exceptions when required parameters are set
            cmdlet.ExecuteCmdlet();
        }
    }
}


text:
FROM nginx:1.11
MAINTAINER Andrew O'Neill <foolusion@gmail.com>
COPY build /usr/share/nginx/html
COPY nginx.conf /etc/nginx/nginx.conf


text:
import cgitb
cgitb.enable(format='text')


text:
@class DVTObservingToken;

@interface IDEIssueGroupNavigableItem : IDEKeyDrivenNavigableItem
{
    DVTObservingToken *_fileGroupsObservingToken;
    DVTObservingToken *_issuesWithoutFilesObservingToken;
    DVTObservingToken *_typeGroupsObservingToken;
}

+ (id)keyPathsForValuesAffectingSubtitle;
- (id)subtitle;
- (id)keyPathsAffectingValueForSubtitle;
- (id)childRepresentedObjects;
- (void)primitiveInvalidate;
- (BOOL)isLeaf;

@end


text:
<?php

defined ( 'BASEPATH' ) or exit ( 'No direct script access allowed' );

/**
 * Database Utility Class
 *
 * @category Database
 * @author EllisLab Dev Team
 * @link http://codeigniter.com/user_guide/database/
 */
abstract class CI_DB_utility {

	/**
	 * Database object
	 *
	 * @var object
	 */
	protected $db;

	// --------------------------------------------------------------------

	/**
	 * List databases statement
	 *
	 * @var string
	 */
	protected $_list_databases = FALSE;

	/**
	 * OPTIMIZE TABLE statement
	 *
	 * @var string
	 */
	protected $_optimize_table = FALSE;

	/**
	 * REPAIR TABLE statement
	 *
	 * @var string
	 */
	protected $_repair_table = FALSE;

	// --------------------------------------------------------------------

	/**
	 * Class constructor
	 *
	 * @param
	 *        	object &$db Database object
	 * @return void
	 */
	public function __construct(&$db) {
		$this->db = & $db;
		log_message ( 'info', 'Database Utility Class Initialized' );
	}

	// --------------------------------------------------------------------

	/**
	 * List databases
	 *
	 * @return array
	 */
	public function list_databases() {
		// Is there a cached result?
		if (isset ( $this->db->data_cache ['db_names'] )) {
			return $this->db->data_cache ['db_names'];
		} elseif ($this->_list_databases === FALSE) {
			return ($this->db->db_debug) ? $this->db->display_error ( 'db_unsupported_feature' ) : FALSE;
		}

		$this->db->data_cache ['db_names'] = array ();

		$query = $this->db->query ( $this->_list_databases );
		if ($query === FALSE) {
			return $this->db->data_cache ['db_names'];
		}

		for($i = 0, $query = $query->result_array (), $c = count ( $query ); $i < $c; $i ++) {
			$this->db->data_cache ['db_names'] [] = current ( $query [$i] );
		}

		return $this->db->data_cache ['db_names'];
	}

	// --------------------------------------------------------------------

	/**
	 * Determine if a particular database exists
	 *
	 * @param string $database_name
	 * @return bool
	 */
	public function database_exists($database_name) {
		return in_array ( $database_name, $this->list_databases () );
	}

	// --------------------------------------------------------------------

	/**
	 * Optimize Table
	 *
	 * @param string $table_name
	 * @return mixed
	 */
	public function optimize_table($table_name) {
		if ($this->_optimize_table === FALSE) {
			return ($this->db->db_debug) ? $this->db->display_error ( 'db_unsupported_feature' ) : FALSE;
		}

		$query = $this->db->query ( sprintf ( $this->_optimize_table, $this->db->escape_identifiers ( $table_name ) ) );
		if ($query !== FALSE) {
			$query = $query->result_array ();
			return current ( $query );
		}

		return FALSE;
	}

	// --------------------------------------------------------------------

	/**
	 * Optimize Database
	 *
	 * @return mixed
	 */
	public function optimize_database() {
		if ($this->_optimize_table === FALSE) {
			return ($this->db->db_debug) ? $this->db->display_error ( 'db_unsupported_feature' ) : FALSE;
		}

		$result = array ();
		foreach ( $this->db->list_tables () as $table_name ) {
			$res = $this->db->query ( sprintf ( $this->_optimize_table, $this->db->escape_identifiers ( $table_name ) ) );
			if (is_bool ( $res )) {
				return $res;
			}

			// Build the result array...
			$res = $res->result_array ();
			$res = current ( $res );
			$key = str_replace ( $this->db->database . '.', '', current ( $res ) );
			$keys = array_keys ( $res );
			unset ( $res [$keys [0]] );

			$result [$key] = $res;
		}

		return $result;
	}

	// --------------------------------------------------------------------

	/**
	 * Repair Table
	 *
	 * @param string $table_name
	 * @return mixed
	 */
	public function repair_table($table_name) {
		if ($this->_repair_table === FALSE) {
			return ($this->db->db_debug) ? $this->db->display_error ( 'db_unsupported_feature' ) : FALSE;
		}

		$query = $this->db->query ( sprintf ( $this->_repair_table, $this->db->escape_identifiers ( $table_name ) ) );
		if (is_bool ( $query )) {
			return $query;
		}

		$query = $query->result_array ();
		return current ( $query );
	}

	// --------------------------------------------------------------------

	/**
	 * Generate CSV from a query result object
	 *
	 * @param object $query
	 *        	object
	 * @param string $delim
	 *        	,)
	 * @param string $newline
	 *        	(default: \n)
	 * @param string $enclosure
	 *        	")
	 * @return string
	 */
	public function csv_from_result($query, $delim = ',', $newline = "\n", $enclosure = '"') {
		if (! is_object ( $query ) or ! method_exists ( $query, 'list_fields' )) {
			show_error ( 'You must submit a valid result object' );
		}

		$out = '';
		// First generate the headings from the table column names
		foreach ( $query->list_fields () as $name ) {
			$out .= $enclosure . str_replace ( $enclosure, $enclosure . $enclosure, $name ) . $enclosure . $delim;
		}

		$out = substr ( rtrim ( $out ), 0, - strlen ( $delim ) ) . $newline;

		// Next blast through the result array and build out the rows
		while ( $row = $query->unbuffered_row ( 'array' ) ) {
			foreach ( $row as $item ) {
				$out .= $enclosure . str_replace ( $enclosure, $enclosure . $enclosure, $item ) . $enclosure . $delim;
			}
			$out = substr ( rtrim ( $out ), 0, - strlen ( $delim ) ) . $newline;
		}

		return $out;
	}

	// --------------------------------------------------------------------

	/**
	 * Generate XML data from a query result object
	 *
	 * @param object $query
	 *        	object
	 * @param array $params
	 * @return string
	 */
	public function xml_from_result($query, $params = array()) {
		if (! is_object ( $query ) or ! method_exists ( $query, 'list_fields' )) {
			show_error ( 'You must submit a valid result object' );
		}

		// Set our default values
		foreach ( array (
				'root' => 'root',
				'element' => 'element',
				'newline' => "\n",
				'tab' => "\t"
		) as $key => $val ) {
			if (! isset ( $params [$key] )) {
				$params [$key] = $val;
			}
		}

		// Create variables for convenience
		extract ( $params );

		// Load the xml helper
		get_instance ()->load->helper ( 'xml' );

		// Generate the result
		$xml = '<' . $root . '>' . $newline;
		while ( $row = $query->unbuffered_row () ) {
			$xml .= $tab . '<' . $element . '>' . $newline;
			foreach ( $row as $key => $val ) {
				$xml .= $tab . $tab . '<' . $key . '>' . xml_convert ( $val ) . '</' . $key . '>' . $newline;
			}
			$xml .= $tab . '</' . $element . '>' . $newline;
		}

		return $xml . '</' . $root . '>' . $newline;
	}

	// --------------------------------------------------------------------

	/**
	 * Database Backup
	 *
	 * @param array $params
	 * @return string
	 */
	public function backup($params = array()) {
		// If the parameters have not been submitted as an
		// array then we know that it is simply the table
		// name, which is a valid short cut.
		if (is_string ( $params )) {
			$params = array (
					'tables' => $params
			);
		}

		// Set up our default preferences
		$prefs = array (
				'tables' => array (),
				'ignore' => array (),
				'filename' => '',
				'format' => 'gzip', // gzip, zip, txt
				'add_drop' => TRUE,
				'add_insert' => TRUE,
				'newline' => "\n",
				'foreign_key_checks' => TRUE
		);

		// Did the user submit any preferences? If so set them....
		if (count ( $params ) > 0) {
			foreach ( $prefs as $key => $val ) {
				if (isset ( $params [$key] )) {
					$prefs [$key] = $params [$key];
				}
			}
		}

		// Are we backing up a complete database or individual tables?
		// If no table names were submitted we'll fetch the entire table list
		if (count ( $prefs ['tables'] ) === 0) {
			$prefs ['tables'] = $this->db->list_tables ();
		}

		// Validate the format
		if (! in_array ( $prefs ['format'], array (
				'gzip',
				'zip',
				'txt'
		), TRUE )) {
			$prefs ['format'] = 'txt';
		}

		// Is the encoder supported? If not, we'll either issue an
		// error or use plain text depending on the debug settings
		if (($prefs ['format'] === 'gzip' && ! function_exists ( 'gzencode' )) or ($prefs ['format'] === 'zip' && ! function_exists ( 'gzcompress' ))) {
			if ($this->db->db_debug) {
				return $this->db->display_error ( 'db_unsupported_compression' );
			}

			$prefs ['format'] = 'txt';
		}

		// Was a Zip file requested?
		if ($prefs ['format'] === 'zip') {
			// Set the filename if not provided (only needed with Zip files)
			if ($prefs ['filename'] === '') {
				$prefs ['filename'] = (count ( $prefs ['tables'] ) === 1 ? $prefs ['tables'] : $this->db->database) . date ( 'Y-m-d_H-i', time () ) . '.sql';
			} else {
				// If they included the .zip file extension we'll remove it
				if (preg_match ( '|.+?\.zip$|', $prefs ['filename'] )) {
					$prefs ['filename'] = str_replace ( '.zip', '', $prefs ['filename'] );
				}

				// Tack on the ".sql" file extension if needed
				if (! preg_match ( '|.+?\.sql$|', $prefs ['filename'] )) {
					$prefs ['filename'] .= '.sql';
				}
			}

			// Load the Zip class and output it
			$CI = & get_instance ();
			$CI->load->library ( 'zip' );
			$CI->zip->add_data ( $prefs ['filename'], $this->_backup ( $prefs ) );
			return $CI->zip->get_zip ();
		} elseif ($prefs ['format'] === 'txt') // Was a text file requested?
{
			return $this->_backup ( $prefs );
		} elseif ($prefs ['format'] === 'gzip') // Was a Gzip file requested?
{
			return gzencode ( $this->_backup ( $prefs ) );
		}

		return;
	}
}


text:
package com.asi.service.product.client.vo.parser;

import java.util.LinkedList;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.web.client.RestTemplate;

import com.asi.ext.api.integration.lookup.parser.UpchargePricesParser;
import com.asi.ext.api.util.RestAPIProperties;

public class UpChargeLookup {
    private final static Logger                      _LOGGER       = Logger.getLogger(UpChargeLookup.class.getName());
    public static RestTemplate lookupRestTemplate;
    private String                                   usageLevelLookupAPI;
    private String                                   upchargeTypelookupAPI;

    private static ConcurrentHashMap<String, String> upchargeTypes = new ConcurrentHashMap<String, String>();
    private static ConcurrentHashMap<String, String> upchargeLevel = new ConcurrentHashMap<String, String>();

    private UpchargePricesParser                     upchargePricesParser  = new UpchargePricesParser();

    public String getUpChargeType(String upChargeType) {
        String temp = getUpChargeTypeByCode(upChargeType);

        if (temp != null) {
            return temp;
        } else {
            return "";
        }
    }

    private String getUpChargeTypeByCode(String code) {

        if (upchargeTypes == null || upchargeTypes.isEmpty()) {
            loadUpchargeTypes(upchargeTypelookupAPI);
        }
        if (upchargeTypes != null) {
            return upchargeTypes.get(code);
        } else {
            return null;
        }
    }

    public ConcurrentHashMap<String, String> getUpchargeTypes(String upchargeTypeAPI){
    	if(upchargeTypes.isEmpty()){
    		loadUpchargeTypes(upchargeTypeAPI);
    	}
    	return upchargeTypes;
    }

    private void loadUpchargeTypes(final String upchargeTypelookupAPI) {
        try {
        	LinkedList<?> criteriaCodesResponse = lookupRestTemplate.getForObject(
		            upchargeTypelookupAPI, LinkedList.class);
            upchargeTypes = upchargePricesParser.getUpchargeTypeCollectionFromJSON(criteriaCodesResponse);

            if (upchargeTypes != null && !upchargeTypes.isEmpty()) {
                _LOGGER.info("Building of Upcharge Types collection completed successfuly");
            } else {
                _LOGGER.info("Failed to build Upcharge Types collection");
            }
        } catch (Exception e) {
            _LOGGER.error("Exception while trying load Upcharge Types collection", e);
        }
    }

    public String getUpchargeLevel(String upchargeLevel) {
        String temp = getUpchargeLevelByCode(upchargeLevel);
        if (temp != null) {
            return temp;
        } else {
            return "";
        }
    }

    private String getUpchargeLevelByCode(String code) {
        if (upchargeLevel == null || upchargeLevel.isEmpty()) {
            loadUsageLevels(usageLevelLookupAPI);
        }
        if (upchargeLevel != null) {
            return upchargeLevel.get(code);
        } else {
            return null;
        }
    }

    private void loadUsageLevels(final String usageLevelLookupAPI) {
        try {
        	LinkedList<?> usageLevelsResponse = lookupRestTemplate.getForObject(
		            usageLevelLookupAPI, LinkedList.class);

            upchargeLevel = upchargePricesParser.getUsageLevelCollectionFromJSON(usageLevelsResponse);

            if (upchargeLevel != null && !upchargeLevel.isEmpty()) {
                _LOGGER.info("Building of UsageLevel collection completed successfuly");
            } else {
                _LOGGER.info("Failed to build UsageLevel collection");
            }
        } catch (Exception e) {
            _LOGGER.error("Exception while trying load UsageLevel collection", e);
        }
    }

    /**
     * @return the usageLevelLookupAPI
     */
    public String getUsageLevelLookupAPI() {
        return usageLevelLookupAPI;
    }

    /**
     * @param usageLevelLookupAPI the usageLevelLookupAPI to set
     */
    @Required
    public void setUsageLevelLookupAPI(String usageLevelLookupAPI) {
        this.usageLevelLookupAPI = usageLevelLookupAPI;
    }

    /**
     * @return the upchargeTypelookupAPI
     */
    public String getUpchargeTypelookupAPI() {
        return upchargeTypelookupAPI;
    }

    /**
     * @param upchargeTypelookupAPI the upchargeTypelookupAPI to set
     */
    @Required
    public void setUpchargeTypelookupAPI(String upchargeTypelookupAPI) {
        this.upchargeTypelookupAPI = upchargeTypelookupAPI;
    }

	public ConcurrentHashMap<String, String> getUpchargeLevels(
			String pricingUsagelevelLookup) {
    	if(upchargeLevel.isEmpty()){
    		loadUsageLevels(pricingUsagelevelLookup);
    	}
    	return upchargeLevel;
	}

}


text:
#include <aws/ram/model/ResourceRegionScopeFilter.h>
#include <aws/core/utils/HashingUtils.h>
#include <aws/core/Globals.h>
#include <aws/core/utils/EnumParseOverflowContainer.h>

using namespace Aws::Utils;

namespace Aws
{
  namespace RAM
  {
    namespace Model
    {
      namespace ResourceRegionScopeFilterMapper
      {

        static const int ALL_HASH = HashingUtils::HashString("ALL");
        static const int REGIONAL_HASH = HashingUtils::HashString("REGIONAL");
        static const int GLOBAL_HASH = HashingUtils::HashString("GLOBAL");

        ResourceRegionScopeFilter GetResourceRegionScopeFilterForName(const Aws::String& name)
        {
          int hashCode = HashingUtils::HashString(name.c_str());
          if (hashCode == ALL_HASH)
          {
            return ResourceRegionScopeFilter::ALL;
          }
          else if (hashCode == REGIONAL_HASH)
          {
            return ResourceRegionScopeFilter::REGIONAL;
          }
          else if (hashCode == GLOBAL_HASH)
          {
            return ResourceRegionScopeFilter::GLOBAL;
          }
          EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
          if(overflowContainer)
          {
            overflowContainer->StoreOverflow(hashCode, name);
            return static_cast<ResourceRegionScopeFilter>(hashCode);
          }

          return ResourceRegionScopeFilter::NOT_SET;
        }

        Aws::String GetNameForResourceRegionScopeFilter(ResourceRegionScopeFilter enumValue)
        {
          switch(enumValue)
          {
          case ResourceRegionScopeFilter::ALL:
            return "ALL";
          case ResourceRegionScopeFilter::REGIONAL:
            return "REGIONAL";
          case ResourceRegionScopeFilter::GLOBAL:
            return "GLOBAL";
          default:
            EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
            if(overflowContainer)
            {
              return overflowContainer->RetrieveOverflow(static_cast<int>(enumValue));
            }

            return {};
          }
        }

      } // namespace ResourceRegionScopeFilterMapper
    } // namespace Model
  } // namespace RAM
} // namespace Aws


text:
package rs.fon.eklubmobile.entities;

import android.os.Parcel;
import android.os.Parcelable;

import com.google.gson.annotations.SerializedName;

import java.io.Serializable;

/**
 * Created by milos on 6/13/16.
 */
public class Attendance implements Parcelable, Serializable {

    @SerializedName("id")
    private long id;
    @SerializedName("member")
    private Member member;
    @SerializedName("isAttendant")
    private boolean isAttendant;
    @SerializedName("lateMin")
    private int lateMin;

    public Attendance() {
    }

    public Attendance(long id, Member member, boolean isAttendant, int lateMin) {
        this.id = id;
        this.member = member;
        this.isAttendant = isAttendant;
        this.lateMin = lateMin;
    }

    protected Attendance(Parcel in) {
        id = in.readLong();
        member = in.readParcelable(Member.class.getClassLoader());
        isAttendant = in.readByte() != 0;
        lateMin = in.readInt();
    }

    public static final Creator<Attendance> CREATOR = new Creator<Attendance>() {
        @Override
        public Attendance createFromParcel(Parcel in) {
            return new Attendance(in);
        }

        @Override
        public Attendance[] newArray(int size) {
            return new Attendance[size];
        }
    };

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public Member getMember() {
        return member;
    }

    public void setMember(Member member) {
        this.member = member;
    }

    public boolean isIsAttendant() {
        return isAttendant;
    }

    public void setIsAttendant(boolean isAttendant) {
        this.isAttendant = isAttendant;
    }

    public int getLateMin() {
        return lateMin;
    }

    public void setLateMin(int lateMin) {
        this.lateMin = lateMin;
    }

    @Override
    public int hashCode() {
        int hash = 7;
        hash = 23 * hash + (int) (this.id ^ (this.id >>> 32));
        return hash;
    }

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

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel parcel, int i) {
        parcel.writeLong(id);
        parcel.writeParcelable(member, i);
        parcel.writeByte((byte) (isAttendant ? 1 : 0));
        parcel.writeInt(lateMin);
    }
}


text:
===============
Flask-FlatPages
===============

.. image:: https://secure.travis-ci.org/SimonSapin/Flask-FlatPages.png?branch=master&style=flat
    :target: https://travis-ci.org/SimonSapin/Flask-FlatPages

.. image:: https://img.shields.io/pypi/v/Flask-FlatPages.svg
    :target: https://pypi.python.org/pypi/Flask-FlatPages

Provides flat static pages to a Flask_ application, based on text files
as opposed to a relational database.

* Works on Python 2.6, 2.7 and 3.3+
* BSD licensed
* Latest documentation `on Read the Docs`_
* Source, issues and pull requests `on Github`_
* Releases `on PyPI`_
* Install with ``pip install Flask-FlatPages``

.. _Flask: http://flask.pocoo.org/
.. _on Read the Docs: http://flask-flatpages.readthedocs.org/
.. _on Github: https://github.com/SimonSapin/Flask-FlatPages/
.. _on PyPI: http://pypi.python.org/pypi/Flask-FlatPages


text:
import React from 'react';
import PropTypes from 'prop-types';

import ReactionPickerView from '../views/reaction-picker-view';
import {RefHolderPropType} from '../prop-types';
import {addEvent} from '../reporter-proxy';

export default class ReactionPickerController extends React.Component {
  static propTypes = {
    addReaction: PropTypes.func.isRequired,
    removeReaction: PropTypes.func.isRequired,

    tooltipHolder: RefHolderPropType.isRequired,
  }

  render() {
    return (
      <ReactionPickerView
        addReactionAndClose={this.addReactionAndClose}
        removeReactionAndClose={this.removeReactionAndClose}
        {...this.props}
      />
    );
  }

  addReactionAndClose = async content => {
    await this.props.addReaction(content);
    addEvent('add-emoji-reaction', {package: 'github'});
    this.props.tooltipHolder.map(tooltip => tooltip.dispose());
  }

  removeReactionAndClose = async content => {
    await this.props.removeReaction(content);
    addEvent('remove-emoji-reaction', {package: 'github'});
    this.props.tooltipHolder.map(tooltip => tooltip.dispose());
  }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>eu.matejkormuth</groupId>
    <artifactId>bmboot</artifactId>
    <version>1.0.1</version>

    <packaging>jar</packaging>

    <name>bmboot</name>
    <description>Boot system and dependency injection for modular Bukkit plugins.</description>
    <inceptionYear>2015</inceptionYear>

    <developers>
        <developer>
            <name>Matej Kormuth</name>
            <email>dobrakmato@gmail.com</email>
            <url>https://github.com/dobrakmato</url>
        </developer>
    </developers>

    <properties>
        <!-- Main class of plugin -->
        <project.mainClass>eu.matejkormuth.bmboot.internal.BukkitPlugin</project.mainClass>

        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

        <!-- Build properties. -->
        <build.unknown>UNKNOWN</build.unknown>
        <build.number>${build.unknown}</build.number>
        <build.revision>${build.unknown}</build.revision>

        <!-- License stuff. -->
        <license.owner>Matej Kormuth</license.owner>
        <license.web>http://github.com/dobrakmato</license.web>

        <!-- These are customizable! -->
        <plugin.author>Matej Kormuth</plugin.author>
        <plugin.name>bmboot</plugin.name>
        <plugin.version>bmboot</plugin.version>
        <plugin.description>empty project</plugin.description>

    </properties>

    <dependencies>
        <!-- Logging dependency. -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.10</version>
        </dependency>

        <!-- Null checks. -->
        <dependency>
            <groupId>com.google.code.findbugs</groupId>
            <artifactId>jsr305</artifactId>
            <version>2.0.1</version>
        </dependency>

        <!-- JSONs -->
        <dependency>
            <groupId>org.json</groupId>
            <artifactId>json</artifactId>
            <version>20150729</version>
        </dependency>

        <!-- Spigot API -->
        <dependency>
            <groupId>org.spigotmc</groupId>
            <artifactId>spigot-api</artifactId>
            <version>1.8.8-R0.1-SNAPSHOT</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>

    <repositories>
        <repository>
            <id>spigot-repo</id>
            <url>https://hub.spigotmc.org/nexus/content/groups/public/</url>
        </repository>
    </repositories>

    <build>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.*</include>
                </includes>
                <filtering>true</filtering>
            </resource>
        </resources>

        <plugins>
            <!-- Use Java 1.8 -->
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.2</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>

            <!-- License plugin. -->
            <plugin>
                <groupId>com.mycila</groupId>
                <artifactId>license-maven-plugin</artifactId>
                <version>2.10</version>
                <configuration>
                    <header>LICENSE-HEADER.txt</header>
                    <properties>
                        <license.owner>Matej Kormuth</license.owner>
                        <license.web>http://www.github.com/dobrakmato</license.web>
                    </properties>
                    <excludes>
                        <exclude>**/README</exclude>
                        <exclude>**/plugin.yml</exclude>
                        <exclude>**/LICENSE.txt</exclude>
                        <exclude>**/pom.xml</exclude>
                        <exclude>src/test/resources/**</exclude>
                        <exclude>src/main/resources/**</exclude>
                    </excludes>
                </configuration>
                <executions>
                    <execution>
                        <goals>
                            <goal>format</goal>
                        </goals>
                        <phase>validate</phase>
                    </execution>
                </executions>
                <inherited>false</inherited>
            </plugin>

            <!-- Shade plugin to provide uber jar -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-shade-plugin</artifactId>
                <version>1.7</version>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>shade</goal>
                        </goals>
                        <configuration>
                            <shadedArtifactAttached>true</shadedArtifactAttached>
                            <shadedClassifierName>jar-with-dependencies</shadedClassifierName>
                            <transformers>
                                <transformer
                                        implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                                    <manifestEntries>
                                        <Implementation-Title>${project.name}</Implementation-Title>
                                        <Implementation-Version>${project.version}</Implementation-Version>
                                        <Implementation-Build-Number>${build.number}</Implementation-Build-Number>
                                        <Implementation-SCM-Revision>${build.revision}</Implementation-SCM-Revision>
                                    </manifestEntries>
                                </transformer>
                            </transformers>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>