text:
'use strict';

var Event = require('./Event');
var Database = require('./Database');
var FDBOpenDBRequest = require('./FDBOpenDBRequest');
var FDBDatabase = require('./FDBDatabase');
var FDBVersionChangeEvent = require('./FDBVersionChangeEvent');
var AbortError = require('./errors/AbortError');
var VersionError = require('./errors/VersionError');
var cmp = require('./cmp');

// http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#dfn-steps-for-deleting-a-database
function deleteDatabase(databases, name, request, cb) {
    try {
        var db;
        if (databases.hasOwnProperty(name)) {
            db = databases[name];
        } else {
            cb();
            return;
        }

        db.deletePending = true;

        var openDatabases = db.connections.filter(function (connection) {
            return !connection._closed;
        });

        openDatabases.forEach(function (openDatabase) {
            if (!openDatabase._closePending) {
                var event = new FDBVersionChangeEvent('versionchange', {
                    oldVersion: db.version,
                    newVersion: null
                });
                openDatabase.dispatchEvent(event);
            }
        });

        var anyOpen = openDatabases.some(function (openDatabase) {
            return !openDatabase._closed;
        });

        if (request && anyOpen) {
            var event = new FDBVersionChangeEvent('blocked', {
                oldVersion: db.version,
                newVersion: null
            });
            request.dispatchEvent(event);
        }
    } catch (err) {
        cb(err);
    }

    var waitForOthersClosed = function () {
        var anyOpen = openDatabases.some(function (openDatabase) {
            return !openDatabase._closed;
        });

        if (anyOpen) {
            setImmediate(waitForOthersClosed);
            return;
        }

        delete databases[name];

        cb();
    };

    waitForOthersClosed();
}

// http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#dfn-steps-for-running-a-versionchange-transaction
function runVersionchangeTransaction(connection, version, request, cb) {
    connection._runningVersionchangeTransaction = true;

    var oldVersion = connection.version;

    var openDatabases = connection._rawDatabase.connections.filter(function (otherDatabase) {
        return connection !== otherDatabase;
    });

    openDatabases.forEach(function (openDatabase) {
        if (!openDatabase._closed) {
            var event = new FDBVersionChangeEvent('versionchange', {
                oldVersion: oldVersion,
                newVersion: version
            });
            openDatabase.dispatchEvent(event);
        }
    });

    var anyOpen = openDatabases.some(function (openDatabase) {
        return !openDatabase._closed;
    });

    if (anyOpen) {
        var event = new FDBVersionChangeEvent('blocked', {
            oldVersion: oldVersion,
            newVersion: version
        });
        request.dispatchEvent(event);
    }

    var waitForOthersClosed = function () {
        var anyOpen = openDatabases.some(function (openDatabase) {
            return !openDatabase._closed;
        });

        if (anyOpen) {
            setImmediate(waitForOthersClosed);
            return;
        }

//  Set the version of database to version. This change is considered part of the transaction, and so if the transaction is aborted, this change is reverted.
        connection._rawDatabase.version = version;
        connection.version = version;

// Get rid of this setImmediate?
        var transaction = connection.transaction(connection.objectStoreNames, 'versionchange');
        request.result = connection;
        request.transaction = transaction;

        transaction._rollbackLog.push(function () {
            connection._rawDatabase.version = oldVersion;
            connection.version = oldVersion;
        });

        var event = new FDBVersionChangeEvent('upgradeneeded', {
            oldVersion: oldVersion,
            newVersion: version
        });
        request.dispatchEvent(event);

        request.readyState = 'done';

        transaction.addEventListener('error', function () {
            connection._runningVersionchangeTransaction = false;
//throw arguments[0].target.error;
//console.log('error in versionchange transaction - not sure if anything needs to be done here', e.target.error.name);
        });
        transaction.addEventListener('abort', function () {
            connection._runningVersionchangeTransaction = false;
            request.transaction = null;
            setImmediate(function () {
                cb(new AbortError());
            });
        });
        transaction.addEventListener('complete', function () {
            connection._runningVersionchangeTransaction = false;
            request.transaction = null;
            // Let other complete event handlers run before continuing
            setImmediate(function () {
                if (connection._closePending) {
                    cb(new AbortError());
                } else {
                    cb(null);
                }
            });
        });
    };

    waitForOthersClosed();
}

// http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#dfn-steps-for-opening-a-database
function openDatabase(databases, name, version, request, cb) {
    var db;
    if (databases.hasOwnProperty(name)) {
        db = databases[name];
    } else {
        db = new Database(name, 0);
        databases[name] = db;
    }

    if (version === undefined) {
        version = db.version !== 0 ? db.version : 1;
    }

    if (db.version > version) {
        return cb(new VersionError());
    }

    var connection = new FDBDatabase(databases[name]);

    if (db.version < version) {
        runVersionchangeTransaction(connection, version, request, function (err) {
            if (err) {
// DO THIS HERE: ensure that connection is closed by running the steps for closing a database connection before these steps are aborted.
                return cb(err);
            }

            cb(null, connection);
        });
    } else {
        cb(null, connection);
    }
}

module.exports = function () {
    this._databases = {};

    this.cmp = cmp;

    // http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#widl-IDBFactory-deleteDatabase-IDBOpenDBRequest-DOMString-name
    this.deleteDatabase = function (name) {
        var request = new FDBOpenDBRequest();
        request.source = null;

        setImmediate(function () {
            var version = this._databases.hasOwnProperty(name) ? this._databases[name].version : null;
            deleteDatabase(this._databases, name, request, function (err) {
                var event;

                if (err) {
                    request.error = new Error();
                    request.error.name = err.name;

                    event = new Event('error', {
                        bubbles: true,
                        cancelable: false
                    });
                    event._eventPath = [];
                    request.dispatchEvent(event);

                    return;
                }

                request.result = undefined;

                event = new FDBVersionChangeEvent('success', {
                    oldVersion: version,
                    newVersion: null
                });
                request.dispatchEvent(event);
            });
        }.bind(this));

        return request;
    };

    // http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#widl-IDBFactory-open-IDBOpenDBRequest-DOMString-name-unsigned-long-long-version
    this.open = function (name, version) {
        if (arguments.length > 1 && (isNaN(version) || version < 1 || version >= 9007199254740992)) {
            throw new TypeError();
        }

        var request = new FDBOpenDBRequest();
        request.source = null;

        setImmediate(function () {
            openDatabase(this._databases, name, version, request, function (err, connection) {
                var event;

                if (err) {
                    request.result = undefined;

                    request.error = new Error();
                    request.error.name = err.name;

                    event = new Event('error', {
                        bubbles: true,
                        cancelable: false
                    });
                    event._eventPath = [];
                    request.dispatchEvent(event);

                    return;
                }

                request.result = connection;

                event = new Event('success');
                event._eventPath = [];
                request.dispatchEvent(event);
            });
        }.bind(this));

        return request;
    };

    this.toString = function () {
        return '[object IDBFactory]';
    };
};


text:
package org.eclipse.cdt.core.parser.tests.rewrite.astwriter;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import junit.framework.Test;
import junit.framework.TestSuite;

import org.eclipse.cdt.core.parser.ParserLanguage;
import org.eclipse.cdt.core.parser.tests.rewrite.RewriteBaseTest;
import org.eclipse.cdt.core.testplugin.CTestPlugin;
import org.eclipse.core.runtime.FileLocator;
import org.eclipse.core.runtime.Path;
import org.eclipse.jface.text.TextSelection;
import org.osgi.framework.Bundle;

public class SourceRewriteTester extends TestSuite {
	private static final String testRegexp = "//!(.*)\\s*(\\w*)*$"; //$NON-NLS-1$
	private static final String codeTypeRegexp = "//%(C|CPP)( GNU)?$"; //$NON-NLS-1$
	private static final String resultRegexp = "//=.*$"; //$NON-NLS-1$

	enum MatcherState { skip, inTest, inSource, inExpectedResult }

	protected static BufferedReader createReader(String file) throws IOException {
		Bundle bundle = CTestPlugin.getDefault().getBundle();
		Path path = new Path(file);
		file = FileLocator.toFileURL(FileLocator.find(bundle, path, null)).getFile();
		return new BufferedReader(new FileReader(file));
	}

	public static Test suite(String name, String file)throws Exception {
		BufferedReader in = createReader(file);
		ArrayList<RewriteBaseTest> testCases = createTests(in);
		in.close();
		return createSuite(testCases, name);
	}

	private static TestSuite createSuite(ArrayList<RewriteBaseTest> testCases, String name) {
		TestSuite suite = new TestSuite(name);
		for (RewriteBaseTest subject : testCases) {
			suite.addTest(subject);
		}
		return suite;
	}

	protected static boolean lineMatchesBeginOfTest(String line) {
		return createMatcherFromString(testRegexp, line).find();
	}

	protected static boolean lineMatchesCodeType(String line) {
		return createMatcherFromString(codeTypeRegexp, line).find();
	}

	protected static Matcher createMatcherFromString(String pattern, String line) {
		return Pattern.compile(pattern).matcher(line);
	}

	protected static String getNameOfTest(String line) {
		Matcher matcherBeginOfTest = createMatcherFromString(testRegexp, line);
		if (matcherBeginOfTest.find()) {
			return matcherBeginOfTest.group(1);
		} else {
			return "Not Named";
		}
	}

	protected static boolean lineMatchesBeginOfResult(String line) {
		return createMatcherFromString(resultRegexp, line).find();
	}

	private static ArrayList<RewriteBaseTest> createTests(BufferedReader inputReader) throws Exception {
		ASTWriterTestSourceFile file = null;
		MatcherState matcherState = MatcherState.skip;
		ArrayList<RewriteBaseTest> testCases = new ArrayList<RewriteBaseTest>();

		String line;
		while ((line = inputReader.readLine()) != null) {
			if (lineMatchesBeginOfTest(line)) {
				matcherState = MatcherState.inTest;
				file = new ASTWriterTestSourceFile("ASTWritterTest.h"); //$NON-NLS-1$
				testCases.add(createTestClass(getNameOfTest(line), file));
				continue;
			} else if (lineMatchesBeginOfResult(line)) {
				matcherState = MatcherState.inExpectedResult;
				continue;
			} else if (lineMatchesCodeType(line)) {
				matcherState = MatcherState.inSource;
				if (file != null) {
					file.setParserLanguage(getParserLanguage(line));
					file.setUseGNUExtensions(useGNUExtensions(line));
				}
				continue;
			}

			switch (matcherState) {
			case inSource:
				if (file != null) {
					file.addLineToSource(line);
				}
				break;
			case inExpectedResult:
				if (file != null) {
					file.addLineToExpectedSource(line);
				}
				break;
			default:
				break;
			}
		}
		return testCases;
	}

	protected static boolean useGNUExtensions(String line) {
		Matcher matcherBeginOfTest = createMatcherFromString(codeTypeRegexp, line);
		if (matcherBeginOfTest.find()) {
			String codeType = matcherBeginOfTest.group(2);
			if (codeType == null) {
				return false;
			} else {
				return true;
			}
		}
		return false;
	}

	protected static ParserLanguage getParserLanguage(String line) {
		Matcher matcherBeginOfTest = createMatcherFromString(codeTypeRegexp, line);
		if (matcherBeginOfTest.find()) {
			String codeType = matcherBeginOfTest.group(1);
			if (codeType.equalsIgnoreCase("CPP")) { //$NON-NLS-1$
				return ParserLanguage.CPP;
			} else {
				return ParserLanguage.C;
			}
		}
		return ParserLanguage.C;
	}

	private static RewriteBaseTest createTestClass(String testName, ASTWriterTestSourceFile file)
			throws Exception {
		ASTWriterTest test = new ASTWriterTest(testName, file);
		TextSelection sel = file.getSelection();
		if (sel != null) {
			test.setFileWithSelection(file.getName());
			test.setSelection(sel);
		}
		return test;
	}
}

redpajama_set_name: RedPajamaGithub


text:
package org.apache.geode.management.api;

import java.util.List;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;

import org.apache.geode.annotations.Experimental;
import org.apache.geode.management.runtime.OperationResult;

/**
 * returned from {@link ClusterManagementService#list(ClusterManagementOperation)}
 *
 * @param <V> the result type associated with the operation type being listed
 */
@Experimental
public class ClusterManagementListOperationsResult<A extends ClusterManagementOperation<V>, V extends OperationResult>
    extends ClusterManagementResult {
  // Override the mapper setting so that we always show result
  @JsonInclude
  @JsonProperty
  private final List<ClusterManagementOperationResult<A, V>> result;

  /**
   * for internal use only
   *
   * @param result the result to set
   */
  @JsonCreator(mode = JsonCreator.Mode.PROPERTIES)
  public ClusterManagementListOperationsResult(
      @JsonProperty("result") List<ClusterManagementOperationResult<A, V>> result) {
    this.result = result;
  }

  /**
   * Returns the payload of the list call
   *
   * @return the payload of the list call
   */
  public List<ClusterManagementOperationResult<A, V>> getResult() {
    return result;
  }
}


text:
/*
* Modified by Henry Rawas (henryr@schakra.com)
*  - make it compatible with Visual Studio builds
*  - added wstrtod to handle INF, NAN
*  - added support for using IOCP with sockets
*/

#ifndef WIN32FIXES_H
#define WIN32FIXES_H

#ifdef WIN32
#ifndef _WIN32
#define _WIN32
#endif
#endif

#ifdef _WIN32
#define WIN32_LEAN_AND_MEAN
#include <assert.h>
#define NOGDI
#define __USE_W32_SOCKETS

#include "fmacros.h"
#include <stdlib.h>
#include <stdio.h>
#include <io.h>
#include <signal.h>
#include <sys/types.h>
#ifndef FD_SETSIZE
#define FD_SETSIZE 16000
#endif
#include "os.h"
#include <float.h>
#include <fcntl.h>    /* _O_BINARY */
#include <limits.h>  /* INT_MAX */
#include <process.h>
#include <sys/types.h>

#define fseeko fseeko64
#define ftello ftello64

#define inline __inline

#undef ftruncate
#define ftruncate replace_ftruncate
#ifndef off64_t
#define off64_t off_t
#endif

int replace_ftruncate(int fd, off64_t length);

#define snprintf _snprintf
#define ftello64 _ftelli64
#define fseeko64 _fseeki64
#define strcasecmp _stricmp
#define strtoll _strtoi64
#define lseek64 lseek
/* following defined to choose little endian byte order */
#define __i386__ 1
#if !defined(va_copy)
#define va_copy(d,s)  d = (s)
#endif

#define sleep(x) Sleep((x)*1000)

#ifndef __RTL_GENRANDOM
#define __RTL_GENRANDOM 1
typedef BOOLEAN (_stdcall* RtlGenRandomFunc)(void * RandomBuffer, ULONG RandomBufferLength);
#endif
RtlGenRandomFunc RtlGenRandom;

#define random() (long)replace_random()
#define rand() replace_random()
int replace_random();

#if !defined(ssize_t)
typedef int ssize_t;
#endif

#if !defined(mode_t)
#define mode_t long
#endif

#if !defined(u_int32_t)
/* sha1 */
typedef unsigned __int32 u_int32_t;
#endif

/* Redis calls usleep(1) to give thread some time
* Sleep(0) should do the same on windows
* In other cases, usleep is called with milisec resolution,
* which can be directly translated to winapi Sleep() */
#undef usleep
#define usleep(x) (x == 1) ? Sleep(0) : Sleep((int)((x)/1000))

#define pipe(fds) _pipe(fds, 8192, _O_BINARY|_O_NOINHERIT)

/* Processes */
#define waitpid(pid,statusp,options) _cwait (statusp, pid, WAIT_CHILD)

#define WAIT_T int
#define WTERMSIG(x) ((x) & 0xff) /* or: SIGABRT ?? */
#define WCOREDUMP(x) 0
#define WEXITSTATUS(x) (((x) >> 8) & 0xff) /* or: (x) ?? */
#define WIFSIGNALED(x) (WTERMSIG (x) != 0) /* or: ((x) == 3) ?? */
#define WIFEXITED(x) (WTERMSIG (x) == 0) /* or: ((x) != 3) ?? */
#define WIFSTOPPED(x) 0

#define WNOHANG 1

/* file mapping */
#define PROT_READ 1
#define PROT_WRITE 2

#define MAP_FAILED   (void *) -1

#define MAP_SHARED 1
#define MAP_PRIVATE 2

/* rusage */
#define RUSAGE_SELF     0
#define RUSAGE_CHILDREN (-1)

#ifndef _RUSAGE_T_
#define _RUSAGE_T_
struct rusage {
    struct timeval ru_utime;    /* user time used */
    struct timeval ru_stime;    /* system time used */
};
#endif

int getrusage(int who, struct rusage * rusage);

/* Signals */
#define SIGNULL  0 /* Null	Check access to pid*/
#define SIGHUP	 1 /* Hangup	Terminate; can be trapped*/
#define SIGINT	 2 /* Interrupt	Terminate; can be trapped */
#define SIGQUIT	 3 /* Quit	Terminate with core dump; can be trapped */
#define SIGTRAP  5
#define SIGBUS   7
#define SIGKILL	 9 /* Kill	Forced termination; cannot be trapped */
#define SIGPIPE 13
#define SIGALRM 14
#define SIGTERM	15 /* Terminate	Terminate; can be trapped  */
#define SIGSTOP 17
#define SIGTSTP 18
#define SIGCONT 19
#define SIGCHLD 20
#define SIGTTIN 21
#define SIGTTOU 22
#define SIGABRT 22
/* #define SIGSTOP	24 // Pause the process; cannot be trapped*/
/* #define SIGTSTP	25 // Terminal stop	Pause the process; can be trapped*/
/* #define SIGCONT	26 */
#define SIGWINCH 28
#define SIGUSR1  30
#define SIGUSR2  31

#define ucontext_t void*

#define SA_NOCLDSTOP    0x00000001u
#define SA_NOCLDWAIT    0x00000002u
#define SA_SIGINFO      0x00000004u
#define SA_ONSTACK      0x08000000u
#define SA_RESTART      0x10000000u
#define SA_NODEFER      0x40000000u
#define SA_RESETHAND    0x80000000u
#define SA_NOMASK       SA_NODEFER
#define SA_ONESHOT      SA_RESETHAND
#define SA_RESTORER     0x04000000

#define sigemptyset(pset)    (*(pset) = 0)
#define sigfillset(pset)     (*(pset) = (unsigned int)-1)
#define sigaddset(pset, num) (*(pset) |= (1L<<(num)))
#define sigdelset(pset, num) (*(pset) &= ~(1L<<(num)))
#define sigismember(pset, num) (*(pset) & (1L<<(num)))

#ifndef SIG_SETMASK
#define SIG_SETMASK (0)
#define SIG_BLOCK   (1)
#define SIG_UNBLOCK (2)
#endif /*SIG_SETMASK*/

typedef	void (*__p_sig_fn_t)(int);
typedef int pid_t;

#ifndef _SIGSET_T_
#define _SIGSET_T_
#ifdef _WIN64
typedef unsigned long long _sigset_t;
#else
typedef unsigned long _sigset_t;
#endif
# define sigset_t _sigset_t
#endif /* _SIGSET_T_ */

struct sigaction {
    int          sa_flags;
    sigset_t     sa_mask;
    __p_sig_fn_t sa_handler;
    __p_sig_fn_t sa_sigaction;
};

int sigaction(int sig, struct sigaction *in, struct sigaction *out);

/* Sockets */

//#ifndef ECONNRESET
//#define ECONNRESET WSAECONNRESET
//#endif
//
//#ifndef EINPROGRESS
//#define EINPROGRESS WSAEINPROGRESS
//#endif
//
//#ifndef ETIMEDOUT
//#define ETIMEDOUT WSAETIMEDOUT
//#endif

#define setsockopt(a,b,c,d,e) replace_setsockopt(a,b,c,d,e)

int replace_setsockopt(socket_t socket, int level, int optname,
                     const void *optval, socklen_t optlen);

#define rename(a,b) replace_rename(a,b)
int replace_rename(const char *src, const char *dest);

//threads avoiding pthread.h

#define pthread_mutex_t CRITICAL_SECTION
#define pthread_attr_t ssize_t

#define pthread_mutex_init(a,b) (InitializeCriticalSectionAndSpinCount((a), 0x80000400),0)
#define pthread_mutex_destroy(a) DeleteCriticalSection((a))
#define pthread_mutex_lock EnterCriticalSection
#define pthread_mutex_unlock LeaveCriticalSection

#define pthread_equal(t1, t2) ((t1) == (t2))

#define pthread_attr_init(x) (*(x) = 0)
#define pthread_attr_getstacksize(x, y) (*(y) = *(x))
#define pthread_attr_setstacksize(x, y) (*(x) = y)

#define pthread_t u_int

int pthread_create(pthread_t *thread, const void *unused,
                    void *(*start_routine)(void*), void *arg);

pthread_t pthread_self(void);

typedef struct {
    CRITICAL_SECTION waiters_lock;
    LONG waiters;
    int was_broadcast;
    HANDLE sema;
    HANDLE continue_broadcast;
} pthread_cond_t;

//typedef CONDITION_VARIABLE pthread_cond_t;

int pthread_cond_init(pthread_cond_t *cond, const void *unused);
int pthread_cond_destroy(pthread_cond_t *cond);
int pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex);
int pthread_cond_timedwait(pthread_cond_t *cond, pthread_mutex_t *mutex, const struct timespec * abstime);
int pthread_cond_signal(pthread_cond_t *cond);

int pthread_detach (pthread_t thread);
int pthread_sigmask(int how, const sigset_t *set, sigset_t *oldset);
int pthread_join(pthread_t thread, void **value_ptr);

/* Misc Unix -> Win32 */
#define PATH_MAX MAX_PATH

struct timespec {
        long long tv_sec;
        long long tv_nsec;
};

int kill(pid_t pid, int sig);
int fsync (int fd);
pid_t wait3(int *stat_loc, int options, void *rusage);

/* redis-check-dump  */
void *mmap(void *start, size_t length, int prot, int flags, int fd, off offset);
int munmap(void *start, size_t length);

int fork(void);
int gettimeofday(struct timeval *tv, struct timezone *tz);
time_t gettimeofdaysecs(unsigned int *usec);

/* strtod does not handle Inf and Nan
We need to do the check before calling strtod */
#undef strtod
#define strtod(nptr, eptr) wstrtod((nptr), (eptr))

double wstrtod(const char *nptr, char **eptr);

/* structs and functions for using IOCP with windows sockets */

/* need callback on write complete. aeWinSendReq is used to pass parameters */
typedef struct aeWinSendReq {
    void *data;
    char *buf;
    int len;
} aeWinSendReq;

int aeWinPipeAttach(pipe_t fd);
int aeWinSocketAttach(socket_t fd);
int aeWinCloseComm(socket_t fd);
int aeWinReceiveDone(socket_t fd);
int aeWinReceiveDone_Pipe(pipe_t fd);
int aeWinSocketSend(socket_t fd, char *buf, int len, int flags,
                    void *eventLoop, void *data, void *proc);
int aeWinListen(socket_t sock, int backlog);
socket_t aeWinAccept(socket_t fd, struct sockaddr *sa, socklen_t *len);
int aeWinSocketConnect(socket_t fd, const struct sockaddr *sa, int len);

HANDLE aeWinGetIOCP();
void aeWinSetIOCP(HANDLE iocph);
void *aeWinGetIOCPState();
void aeWinSetIOCPState(void *iocp_state);

int strerror_r(int err, char* buf, size_t buflen);
char *wsa_strerror(int err);

// access check for executable uses X_OK. For Windows use READ access.
#ifndef X_OK
#define X_OK 4
#endif

#ifndef STDOUT_FILENO
#define STDOUT_FILENO 1
#endif

#ifndef siginfo_t
typedef struct {
    int si_signo;
    int si_code;
    int si_value;
    int si_errno;
    pid_t si_pid;
    int si_uid;
    void *si_addr;
    int si_status;
    int si_band;
} siginfo_t;
#endif

#endif /* WIN32 */
#endif /* WIN32FIXES_H */


text:
<?php

/**
 * This is a thin script that shows how to use the Packal class to submit things to Packal.org using
 * through the Packal API. If you want a simple solution, then use the Packal Workflow. If you use your
 * own scripts to build clean versions of your workflows and want to implement automatic submissions to
 * Packal, then adapt this code for your build script.
 */

// Require the Packal file that contains the Packal class
require_once( 'packal.php' );

// You should probably never hardcode your username and password into the file. But we'll reuse these, so
// you need to set them. If you don't have a packal account, then go onto Packal.org and register one.
$username = 'my_packal_username';
$password = 'my_packal_password';

/**
 * Submit a Workflow Example
 *
 * If you adapt this for a custom build script, you'll probably want to have a dynamic way to pass the
 * filename and the version, but these are hardcoded here as a simple usage example. The each workflow
 * must have a workflow.ini in its root directory, and if you want to include screenshots, then they
 * must be in a folder in the root directory called 'screenshots' within the Alfredworkflow file. If
 * you want to include a "long description" (recommended), then you must have a `README.md` file in
 * the workflow root. You can override the location of the `README.md` file in your `workflow.ini` file,
 * and you can also override the location of the screenshots directory in your `workflow.ini` file.
 *
 * Upload a new version will fail if you try to upload a copy with the same version number. The version
 * passed in the params is for a quick rejection. If you pass the correct version in the params but
 * an old version in the `workflow.ini` file, then the submission will be accepted, but it will fail
 * later when the workflow submission is fully processed.
 */

// Full path to workflow file
$workflow_path = '/path/to/workflow.alfredworkflow';
// Needs to be a Semantic Version
$workflow_version = '1.0.0';

// Create an array for the workflow; each workflow needs the 'file' and 'version' params
$workflow = [
	'file' => $workflow_path,
	'version' => $workflow_version
];

// Instantiate a new Packal object of type 'workflow', next is the params, and the last two are the username and password
$packal = new Packal( 'workflow', $workflow, $username, $password );
// Execute the submission. The result is returned as JSON, so decode that and print it to the console
print_r( json_decode( $packal->execute(), true ) );

/**
 * Submit a Theme Example
 *
 * Screenshots of the theme will be generated automatically on the website
 */

// Get this by going to Alfred Preferences -> Appearance, and ctrl+click a theme, and Copy Theme URL.
$theme_uri = 'alfred://theme/searchForegroundColor=rgba(0,0,0,1.00)&resultSubtextFontSize=1&searchSelectionForegroundColor=rgba(0,0,0,1.00)&separatorColor=rgba(87,60,70,0.49)&resultSelectedBackgroundColor=rgba(0,0,0,0.06)&shortcutColor=rgba(179,179,179,1.00)&scrollbarColor=rgba(0,0,0,0.10)&imageStyle=0&resultSubtextFont=Geneva&background=rgba(147,255,255,0.98)&shortcutFontSize=2&searchFontSize=3&resultSubtextColor=rgba(208,153,153,1.00)&searchBackgroundColor=rgba(127,170,0,0.47)&name=Example%20Theme&resultTextFontSize=4&resultSelectedSubtextColor=rgba(224,57,65,1.00)&shortcutSelectedColor=rgba(166,166,166,1.00)&widthSize=4&border=rgba(0,166,0,1.00)&resultTextFont=Baskerville&resultTextColor=rgba(53,53,53,1.00)&cornerRoundness=0&searchFont=Helvetica%20Neue%20Light&searchPaddingSize=1&credits=Shawn%20Patrick%20Rice&searchSelectionBackgroundColor=rgba(178,215,255,1.00)&resultSelectedTextColor=rgba(0,0,0,1.00)&resultPaddingSize=3&shortcutFont=Menlo';
// This should be a string; markdown is accepted, but do not get too crazy
$theme_description = 'Just an example theme.';
// Comma separated values
$theme_tags = 'example theme,example,nothing to see here,ugly';
// This should match the theme name from the URI
$theme_name = 'Example Theme';

// Create an array that is the theme parameters. The four keys used here are necessary
$theme = [
	'uri' => $theme_uri,
	'description' => $theme_description,
	'tags' => $theme_tags,
	'name' = $theme_name
];

// Instantiate a new Packal object of type 'theme', next is the params, and the last two are the username and password
$packal = new Packal( 'theme', $theme, $username, $password );
// Execute the submission. The result is returned as JSON, so decode that and print it to the console
print_r( json_decode( $packal->execute(), true ) );

/**
 * Submit a Report Example
 *
 * Reports are for workflows and should not be bug reports (direct those to the workflow's author). Instead,
 * reports should be identify a version of a workflow that has things like a virus (while Packal.org runs
 * a virus scan on each uploaded workflow file, there is always the possibility of it missing a virus), malicious
 * code (i.e. `rm -fR /`) or other bits that are damaging. Basically, if the workflow causes harm to a user's
 * system, then it should be reported. Reports will be reviewed, and workflows that are deemed malicious
 * (intentionally or not) will be removed from Packal.org.
 *
 * You will probably never use this part of the Packal class, but it's there.
 */

// Find this on Packal.org as the revision id of the workflow
$report_workflow_revision_id = 589;
// Think of this as a subject header. Try to use 'Malicious Code' or 'Virus Detected'
$report_type = 'Malicious Code';
// Please be specific so we know what to look for
$report_message = 'This is a simple message that explains the problem with the stated workflow revision';

// Create an array that is the report parameters. The three keys used here are necessary
$report = [
	'workflow_revision_id' => $report_workflow_revision_id,
	'type' => $report_type,
	'message' => $report_message
];

// Instantiate a new Packal object of type 'report', next is the params, and the last two are the username and password
$packal = new Packal( 'report', $report, $username, $password );
// Execute the submission. The result is returned as JSON, so decode that and print it to the console
print_r( json_decode( $packal->execute(), true ) );


text:
var request = require("request");
var $ = require("jquery")
var express = require('express');
module.exports = function(app, passport) {

// normal routes ===============================================================
app.use(express.static(__dirname + '/public'))
    // show the home page (will also have our login links)
    app.get('/', function(req, res) {
        res.render('index.ejs');
    });
    app.get('/appointment', function(req, res) {
        res.render('appointment.ejs');
    });
    app.get('/forms', function(req, res) {
        res.render('forms.ejs');
    });
    app.post('/report', function(req,res){
        console.log(req.body.patientid);
       request("http://localhost:3000/data_analytics/get_analytics_data?user_id="+req.body.patientid, function(err, resp, body) {
       data = JSON.parse(body);

    console.log(data);

        res.render('report.ejs',{data :data});
              });

    });
    // PROFILE SECTION =========================
    app.get('/profile', isLoggedIn, function(req, res) {
        res.render('profile.ejs', {
            user : req.user
        });
    });
    app.get('/input', isLoggedIn, function(req, res) {
        res.render('fuzzy.ejs')

    });

    // LOGOUT ==============================
    app.get('/logout', function(req, res) {
        req.logout();
        res.redirect('/');
    });
    app.post('/fuzzy', function(req, res) {
      console.log(req.body.cholestrol);
      var inp = [
        req.body.cholestrol,
        req.body.obesity
      ];
      var fuzzyis = require('fuzzyis');
      var system = new fuzzyis.FIS('Cancer system');
      var LV = fuzzyis.LinguisticVariable;
       var Term = fuzzyis.Term;
        var Rule = fuzzyis.Rule;
      var outputs = [
    new LV('chance of cancer', [0, 100])
    ];
    var inputs = [
    new LV('obesity', [0, 10]),
    new LV('cholestrol', [0, 10])
];
// take some shortcuts
var CANCER = outputs[0];
var OBESITY = inputs[0];
var CHOLESTROL = inputs[1];

OBESITY.addTerm(new Term('normal', 'gauss', [0, 2.123]));
OBESITY.addTerm(new Term('high', 'gauss', [2.123, 5]));
OBESITY.addTerm(new Term('very high', 'gauss', [5, 10]));

CHOLESTROL.addTerm(new Term('normal', 'gauss', [0,2.123]));
CHOLESTROL.addTerm(new Term('high', 'gauss', [2.123, 5]));
CHOLESTROL.addTerm(new Term('very high', 'gauss', [5, 10]));
CANCER.addTerm(new Term('low', 'triangle', [0, 15, 30]));
CANCER.addTerm(new Term('medium', 'triangle', [30, 45, 60]));
CANCER.addTerm(new Term('high', 'triangle', [60, 75, 90]));

system.inputs = inputs;
system.outputs = outputs;
system.rules = [
    new Rule(
        ['normal', 'normal'],
        ['low'],
        'and'
    ),
    new Rule(
        ['high', 'high'],
        ['medium'],
        'and'
    ),
    new Rule(
        ['very high', 'very high'],
        ['high'],
        'and'
    )
];
var output = system.getPreciseOutput([inp[0],inp[1]]);
res.render('tables.ejs', { output:output})
    });

// =============================================================================
// AUTHENTICATE (FIRST LOGIN) ==================================================
// =============================================================================

    // locally --------------------------------
        // LOGIN ===============================
        // show the login form
        app.get('/login', function(req, res) {
            res.render('login.ejs', { message: req.flash('loginMessage') });
        });

        // process the login form
        app.post('/login', passport.authenticate('local-login', {
            successRedirect : '/profile', // redirect to the secure profile section
            failureRedirect : '/login', // redirect back to the signup page if there is an error
            failureFlash : true // allow flash messages
        }));

        // SIGNUP =================================
        // show the signup form
        app.get('/signup', function(req, res) {
            res.render('signup.ejs', { message: req.flash('signupMessage') });
        });

        // process the signup form
        app.post('/signup', passport.authenticate('local-signup', {
            successRedirect : '/profile', // redirect to the secure profile section
            failureRedirect : '/signup', // redirect back to the signup page if there is an error
            failureFlash : true // allow flash messages
        }));

    // facebook -------------------------------

        // send to facebook to do the authentication
        app.get('/auth/facebook', passport.authenticate('facebook', { scope : 'email' }));

        // handle the callback after facebook has authenticated the user
        app.get('/auth/facebook/callback',
            passport.authenticate('facebook', {
                successRedirect : '/profile',
                failureRedirect : '/'
            }));

    // twitter --------------------------------

        // send to twitter to do the authentication
        app.get('/auth/twitter', passport.authenticate('twitter', { scope : 'email' }));

        // handle the callback after twitter has authenticated the user
        app.get('/auth/twitter/callback',
            passport.authenticate('twitter', {
                successRedirect : '/profile',
                failureRedirect : '/'
            }));

    // google ---------------------------------

        // send to google to do the authentication
        app.get('/auth/google', passport.authenticate('google', { scope : ['profile', 'email'] }));

        // the callback after google has authenticated the user
        app.get('/auth/google/callback',
            passport.authenticate('google', {
                successRedirect : '/profile',
                failureRedirect : '/'
            }));

// =============================================================================
// AUTHORIZE (ALREADY LOGGED IN / CONNECTING OTHER SOCIAL ACCOUNT) =============
// =============================================================================

    // locally --------------------------------
        app.get('/connect/local', function(req, res) {
            res.render('connect-local.ejs', { message: req.flash('loginMessage') });
        });
        app.post('/connect/local', passport.authenticate('local-signup', {
            successRedirect : '/profile', // redirect to the secure profile section
            failureRedirect : '/connect/local', // redirect back to the signup page if there is an error
            failureFlash : true // allow flash messages
        }));

    // facebook -------------------------------

        // send to facebook to do the authentication
        app.get('/connect/facebook', passport.authorize('facebook', { scope : 'email' }));

        // handle the callback after facebook has authorized the user
        app.get('/connect/facebook/callback',
            passport.authorize('facebook', {
                successRedirect : '/profile',
                failureRedirect : '/'
            }));

    // twitter --------------------------------

        // send to twitter to do the authentication
        app.get('/connect/twitter', passport.authorize('twitter', { scope : 'email' }));

        // handle the callback after twitter has authorized the user
        app.get('/connect/twitter/callback',
            passport.authorize('twitter', {
                successRedirect : '/profile',
                failureRedirect : '/'
            }));

    // google ---------------------------------

        // send to google to do the authentication
        app.get('/connect/google', passport.authorize('google', { scope : ['profile', 'email'] }));

        // the callback after google has authorized the user
        app.get('/connect/google/callback',
            passport.authorize('google', {
                successRedirect : '/profile',
                failureRedirect : '/'
            }));

// =============================================================================
// UNLINK ACCOUNTS =============================================================
// =============================================================================
// used to unlink accounts. for social accounts, just remove the token
// for local account, remove email and password
// user account will stay active in case they want to reconnect in the future

    // local -----------------------------------
    app.get('/unlink/local', isLoggedIn, function(req, res) {
        var user            = req.user;
        user.local.email    = undefined;
        user.local.password = undefined;
        user.save(function(err) {
            res.redirect('/profile');
        });
    });

    // facebook -------------------------------
    app.get('/unlink/facebook', isLoggedIn, function(req, res) {
        var user            = req.user;
        user.facebook.token = undefined;
        user.save(function(err) {
            res.redirect('/profile');
        });
    });

    // twitter --------------------------------
    app.get('/unlink/twitter', isLoggedIn, function(req, res) {
        var user           = req.user;
        user.twitter.token = undefined;
        user.save(function(err) {
            res.redirect('/profile');
        });
    });

    // google ---------------------------------
    app.get('/unlink/google', isLoggedIn, function(req, res) {
        var user          = req.user;
        user.google.token = undefined;
        user.save(function(err) {
            res.redirect('/profile');
        });
    });

};

// route middleware to ensure user is logged in
function isLoggedIn(req, res, next) {
    if (req.isAuthenticated())
        return next();

    res.redirect('/');
}


text:
import socket
import sys

class Client:

    def __init__(self):
        self.client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_IP)
        self.client_socket.connect(('127.0.0.1', 3046))
        self.buffer_size = 32

    def send(self, message):
        if isinstance(message, unicode):
            message = message.encode('utf-8')
        done = False
        while not done:
            self.client_socket.send(message[:self.buffer_size])
            message = message[self.buffer_size:]
            # print message

            if len(message) == 0:
                self.client_socket.shutdown(socket.SHUT_WR)
                done = True

    def receive(self):
        received_message = []
        done = False
        while not done:
            returned_message = self.client_socket.recv(self.buffer_size)

            if not returned_message:
                 done = True

            received_message.append(returned_message)

        self.client_socket.close()

        return ''.join(received_message)

if __name__ == "__main__":
    _client = Client()
    _client.send(sys.argv[1])
    print "-"*20
    print _client.receive()


text:
#ifndef APP_USBD_CDC_DESC_H__
#define APP_USBD_CDC_DESC_H__

#ifdef __cplusplus
extern "C" {
#endif

#include <stdint.h>
#include <stdbool.h>

#include "app_usbd_descriptor.h"
#include "app_usbd_cdc_types.h"

/**
 * @defgroup app_usbd_cdc_desc CDC class descriptors
 * @brief @tagAPI52840 Descriptors used in the USB CDC class implementation.
 * @ingroup app_usbd_cdc_acm
 *
 * A group of macros used to initialize CDC descriptors
 * @{
 */

/**
 * @brief Initializer of IAD descriptor for CDC class.
 *
 * @param interface_number Interface number.
 * @param subclass         Subclass, @ref app_usbd_cdc_subclass_t.
 * @param protocol         Protocol, @ref app_usbd_cdc_comm_protocol_t.
 */
#define APP_USBD_CDC_IAD_DSC(interface_number, subclass, protocol)        \
    /*.bLength =           */ sizeof(app_usbd_descriptor_iad_t),          \
    /*.bDescriptorType =   */ APP_USBD_DESCRIPTOR_INTERFACE_ASSOCIATION,  \
    /*.bFirstInterface =   */ interface_number,                           \
    /*.bInterfaceCount =   */ 2,                                          \
    /*.bFunctionClass =    */ APP_USBD_CDC_COMM_CLASS,                    \
    /*.bFunctionSubClass = */ subclass,                                   \
    /*.bFunctionProtocol = */ protocol,                                   \
    /*.iFunction =         */ 0,                                          \

/**
 * @brief Initializer of interface descriptor for CDC COMM class.
 *
 * @param interface_number Interface number.
 * @param subclass         Subclass, @ref app_usbd_cdc_subclass_t.
 * @param protocol         Protocol, @ref app_usbd_cdc_comm_protocol_t.
 */
#define APP_USBD_CDC_COMM_INTERFACE_DSC(interface_number, subclass, protocol)  \
    /*.bLength =            */ sizeof(app_usbd_descriptor_iface_t),            \
    /*.bDescriptorType =    */ APP_USBD_DESCRIPTOR_INTERFACE,                  \
    /*.bInterfaceNumber =   */ interface_number,                               \
    /*.bAlternateSetting =  */ 0x00,                                           \
    /*.bNumEndpoints =      */ 1,                                              \
    /*.bInterfaceClass =    */ APP_USBD_CDC_COMM_CLASS,                        \
    /*.bInterfaceSubClass = */ subclass,                                       \
    /*.bInterfaceProtocol = */ protocol,                                       \
    /*.iInterface = 0,      */ 0x00,                                           \

/**
 * @brief Initializer of interface descriptor for CDC DATA class.
 *
 * @param interface_number Interface number.
 * @param subclass         Subclass, @ref app_usbd_cdc_subclass_t.
 * @param protocol         Protocol, @ref app_usbd_cdc_data_protocol_t.
 */
#define APP_USBD_CDC_DATA_INTERFACE_DSC(interface_number, subclass, protocol) \
    /*.bLength =            */ sizeof(app_usbd_descriptor_iface_t),           \
    /*.bDescriptorType =    */ APP_USBD_DESCRIPTOR_INTERFACE,                 \
    /*.bInterfaceNumber =   */ interface_number,                              \
    /*.bAlternateSetting =  */ 0x00,                                          \
    /*.bNumEndpoints =      */ 2,                                             \
    /*.bInterfaceClass =    */ APP_USBD_CDC_DATA_CLASS,                       \
    /*.bInterfaceSubClass = */ subclass,                                      \
    /*.bInterfaceProtocol = */ protocol,                                      \
    /*.iInterface = 0,      */ 0x00,                                          \

/**
 * @brief Initializer of endpoint descriptor for CDC COM class.
 *
 * @param endpoint_in   IN endpoint.
 * @param ep_size       Endpoint size.
 */
#define APP_USBD_CDC_COM_EP_DSC(endpoint_in, ep_size)                     \
    /*.bLength =          */ sizeof(app_usbd_descriptor_ep_t),            \
    /*.bDescriptorType =  */ APP_USBD_DESCRIPTOR_ENDPOINT,                \
    /*.bEndpointAddress = */ endpoint_in,                                 \
    /*.bmAttributes =     */ APP_USBD_DESCRIPTOR_EP_ATTR_TYPE_INTERRUPT,  \
    /*.wMaxPacketSize =   */ APP_USBD_U16_TO_RAW_DSC(ep_size),            \
    /*.bInterval =        */ 16,                                          \

/**
 * @brief Initializer of endpoint descriptors for CDC DATA class.
 *
 * @param endpoint_in   IN endpoint.
 * @param endpoint_out  OUT endpoint.
 * @param ep_size       Endpoint size.
 */
#define APP_USBD_CDC_DATA_EP_DSC(endpoint_in, endpoint_out, ep_size) \
    /*.bLength =          */ sizeof(app_usbd_descriptor_ep_t),       \
    /*.bDescriptorType =  */ APP_USBD_DESCRIPTOR_ENDPOINT,           \
    /*.bEndpointAddress = */ endpoint_in,                            \
    /*.bmAttributes =     */ APP_USBD_DESCRIPTOR_EP_ATTR_TYPE_BULK,  \
    /*.wMaxPacketSize =   */ APP_USBD_U16_TO_RAW_DSC(ep_size),       \
    /*.bInterval =        */ 0,                                      \
    /*.bLength =          */ sizeof(app_usbd_descriptor_ep_t),       \
    /*.bDescriptorType =  */ APP_USBD_DESCRIPTOR_ENDPOINT,           \
    /*.bEndpointAddress = */ endpoint_out,                           \
    /*.bmAttributes =     */ APP_USBD_DESCRIPTOR_EP_ATTR_TYPE_BULK,  \
    /*.wMaxPacketSize =   */ APP_USBD_U16_TO_RAW_DSC(ep_size),       \
    /*.bInterval =        */ 0,                                      \

/**
 * @brief Initializer of endpoint descriptors for CDC header descriptor.
 *
 * @param bcd_cdc   BCD CDC version.
 */
#define APP_USBD_CDC_HEADER_DSC(bcd_cdc)                           \
    /*.bLength =            */ sizeof(app_usbd_cdc_desc_header_t), \
    /*.bDescriptorType =    */ APP_USBD_CDC_CS_INTERFACE,          \
    /*.bDescriptorSubtype = */ APP_USBD_CDC_SCS_HEADER,            \
    /*.bcdCDC =             */ APP_USBD_U16_TO_RAW_DSC(bcd_cdc),   \

/**
 * @brief Initializer of endpoint descriptors for CDC call management descriptor.
 *
 * @param capabilities   Capabilities.
 * @param data_interface Data interface.
 */
#define APP_USBD_CDC_CALL_MGMT_DSC(capabilities, data_interface)      \
    /*.bLength =            */ sizeof(app_usbd_cdc_desc_call_mgmt_t), \
    /*.bDescriptorType =    */ APP_USBD_CDC_CS_INTERFACE,             \
    /*.bDescriptorSubtype = */ APP_USBD_CDC_SCS_CALL_MGMT,            \
    /*.bmCapabilities =     */ capabilities,                          \
    /*.bDataInterface =     */ data_interface,                        \

/**
 * @brief Initializer of endpoint descriptors for CDC DATA class.
 *
 * @param capabilities   Capabilities.
 */
#define APP_USBD_CDC_ACM_DSC(capabilities)                      \
    /*.bLength =            */ sizeof(app_usbd_cdc_desc_acm_t), \
    /*.bDescriptorType =    */ APP_USBD_CDC_CS_INTERFACE,       \
    /*.bDescriptorSubtype = */ APP_USBD_CDC_SCS_ACM,            \
    /*.bmCapabilities =     */ capabilities,                    \

/**
 * @brief Initializer of endpoint descriptors for CDC DATA class.
 *
 * @param control_interface   Control interface.
 * @param ...                 Subordinate interfaces list.
 */
#define APP_USBD_CDC_UNION_DSC(control_interface, ...)                                            \
    /*.bLength =               */ sizeof(app_usbd_cdc_desc_union_t) + (NUM_VA_ARGS(__VA_ARGS__)), \
    /*.bDescriptorType =       */ APP_USBD_CDC_CS_INTERFACE,                                      \
    /*.bDescriptorSubtype =    */ APP_USBD_CDC_SCS_UNION,                                         \
    /*.bControlInterface =     */ control_interface,                                              \
    /*.bSubordinateInterface = */ __VA_ARGS__,                                                    \

/** @} */

#ifdef __cplusplus
}
#endif

#endif /* APP_USBD_CDC_H__ */


text:
void compile_and_link_test()
{
   TEST_DIST_FUNC(inverse_gamma)
}

template class boost::math::inverse_gamma_distribution<float, boost::math::policies::policy<> >;
template class boost::math::inverse_gamma_distribution<double, boost::math::policies::policy<> >;
#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS
template class boost::math::inverse_gamma_distribution<long double, boost::math::policies::policy<> >;
#endif


text:
package io.github.redpanda4552.DubzHud.toggles;

public abstract class AbstractToggle {

    private String name;
    private boolean enabled;

    public AbstractToggle(String name) {
        this.name = name;
        enabled = false;
    }

    public String getName() {
        return name;
    }

    public boolean enabled() {
        return enabled;
    }

    public void toggle() {
        enabled = !enabled;
    }

    public abstract String getText();

}


text:
package com.gitblit.sysinfo;

import java.io.Serializable;
import java.lang.management.ManagementFactory;
import java.lang.management.OperatingSystemMXBean;
import java.lang.management.ThreadMXBean;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Locale;

/**
 * This code was extracted from JavaMelody and refactored.
 *
 * @author Emeric Vernat
 * @author James Moger
 */
public class SysInfo implements Serializable {

    private static final long serialVersionUID = 1L;
    private static final Date START_DATE = new Date();
    private final MemoryInfo memoryInfo;
    private final long processCpuTimeMillis;
    private final double systemLoadAverage;
    private final long unixOpenFileDescriptorCount;
    private final long unixMaxFileDescriptorCount;
    private final String host;
    private final String os;
    private final int availableProcessors;
    private final String javaVersion;
    private final String jvmVersion;
    private final String pid;
    private final Date startDate;
    private final String jvmArguments;
    private final long freeDiskSpaceInTemp;
    private final int threadCount;
    private final int peakThreadCount;
    private final long totalStartedThreadCount;
    private final List<ThreadInfo> threadInfoList;
    private final List<ProcessInfo> processInfoList;

    public SysInfo() {
        this(true, true);
    }

    public SysInfo(boolean collectThreadInfo, boolean collectProcessInfo) {
        startDate = START_DATE;
        host = Parameters.getHostName() + '@' + Parameters.getHostAddress();
        os = buildOS();
        availableProcessors = Runtime.getRuntime().availableProcessors();
        javaVersion = System.getProperty("java.runtime.name") + ", " + System.getProperty("java.runtime.version");
        jvmVersion = System.getProperty("java.vm.name") + ", " + System.getProperty("java.vm.version") + ", " + System.getProperty("java.vm.info");
        jvmArguments = buildJvmArguments();

        pid = PID.getPID();

        ThreadMXBean threadBean = ManagementFactory.getThreadMXBean();
        threadCount = threadBean.getThreadCount();
        peakThreadCount = threadBean.getPeakThreadCount();
        totalStartedThreadCount = threadBean.getTotalStartedThreadCount();

        threadInfoList = collectThreadInfo ? ThreadInfo.buildThreadInfoList() : Collections.emptyList();
        processInfoList = collectProcessInfo ? ProcessInfo.buildProcessInfoList() : Collections.emptyList();

        memoryInfo = new MemoryInfo();
        systemLoadAverage = buildSystemLoadAverage();
        processCpuTimeMillis = buildProcessCpuTimeMillis();

        unixOpenFileDescriptorCount = buildOpenFileDescriptorCount();
        unixMaxFileDescriptorCount = buildMaxFileDescriptorCount();
        freeDiskSpaceInTemp = Parameters.TEMPORARY_DIRECTORY.getFreeSpace();
    }

    private static String buildOS() {
        String name = System.getProperty("os.name");
        String version = System.getProperty("os.version");
        String patchLevel = System.getProperty("sun.os.patch.level");
        String arch = System.getProperty("os.arch");
        String bits = System.getProperty("sun.arch.data.model");

        StringBuilder sb = new StringBuilder();
        sb.append(name).append(", ");
        if (!name.toLowerCase(Locale.ENGLISH).contains("windows")) {
            // version is "6.1" and useless for os.name "Windows 7",
            // and can be "2.6.32-358.23.2.el6.x86_64" for os.name "Linux"
            sb.append(version).append(' ');
        }
        if (!"unknown".equals(patchLevel)) {
            // patchLevel is "unknown" and useless on Linux,
            // and can be "Service Pack 1" on Windows
            sb.append(patchLevel);
        }
        sb.append(", ").append(arch).append('/').append(bits);
        return sb.toString();
    }

    private long buildProcessCpuTimeMillis() {
        OperatingSystemMXBean operatingSystem = ManagementFactory.getOperatingSystemMXBean();
        if (isSunOsMBean(operatingSystem)) {
            // nanoseconds to milliseconds
            return MemoryInfo.getLongFromOperatingSystem(operatingSystem, "getProcessCpuTime") / 1000000;
        }
        return -1;
    }

    private long buildOpenFileDescriptorCount() {
        OperatingSystemMXBean operatingSystem = ManagementFactory.getOperatingSystemMXBean();
        if (isSunOsMBean(operatingSystem) && isSunUnixMBean(operatingSystem)) {
            try {
                return MemoryInfo.getLongFromOperatingSystem(operatingSystem, "getOpenFileDescriptorCount");
            } catch (Error e) {
                // pour issue 16 (using jsvc on ubuntu or debian)
                return -1;
            }
        }
        return -1;
    }

    private long buildMaxFileDescriptorCount() {
        OperatingSystemMXBean operatingSystem = ManagementFactory.getOperatingSystemMXBean();
        if (isSunOsMBean(operatingSystem) && isSunUnixMBean(operatingSystem)) {
            try {
                return MemoryInfo.getLongFromOperatingSystem(operatingSystem, "getMaxFileDescriptorCount");
            } catch (Error e) {
                // pour issue 16 (using jsvc on ubuntu or debian)
                return -1;
            }
        }
        return -1;
    }

    private double buildSystemLoadAverage() {
        // System load average for the last minute.
        // The system load average is the sum of
        // the number of runnable entities queued to the available processors
        // and the number of runnable entities running on the available processors
        // averaged over a period of time.
        OperatingSystemMXBean operatingSystem = ManagementFactory.getOperatingSystemMXBean();
        if (operatingSystem.getSystemLoadAverage() >= 0) {
            return operatingSystem.getSystemLoadAverage();
        }
        return -1;
    }

    private static String buildJvmArguments() {
        StringBuilder jvmArgs = new StringBuilder();
        for (String jvmArg : ManagementFactory.getRuntimeMXBean().getInputArguments()) {
            jvmArgs.append(jvmArg).append('\n');
        }
        if (jvmArgs.length() > 0) {
            jvmArgs.deleteCharAt(jvmArgs.length() - 1);
        }
        return jvmArgs.toString();
    }

    boolean isSunOsMBean(OperatingSystemMXBean operatingSystem) {
        // on ne teste pas operatingSystem instanceof com.sun.management.OperatingSystemMXBean
        // car le package com.sun n'existe à priori pas sur une jvm tierce
        String className = operatingSystem.getClass().getName();
        return "com.sun.management.OperatingSystem".equals(className)
                || "com.sun.management.UnixOperatingSystem".equals(className)
                // sun.management.OperatingSystemImpl pour java 8
                || "sun.management.OperatingSystemImpl".equals(className);
    }

    boolean isSunUnixMBean(OperatingSystemMXBean operatingSystem) {
        for (Class<?> inter : operatingSystem.getClass().getInterfaces()) {
            if ("com.sun.management.UnixOperatingSystemMXBean".equals(inter.getName())) {
                return true;
            }
        }
        return false;
    }

    public MemoryInfo getMemoryInfo() {
        return memoryInfo;
    }

    public long getProcessCpuTimeMillis() {
        return processCpuTimeMillis;
    }

    public double getSystemLoadAverage() {
        return systemLoadAverage;
    }

    public long getUnixOpenFileDescriptorCount() {
        return unixOpenFileDescriptorCount;
    }

    public long getUnixMaxFileDescriptorCount() {
        return unixMaxFileDescriptorCount;
    }

    public double getUnixOpenFileDescriptorPercentage() {
        if (unixOpenFileDescriptorCount >= 0) {
            return 100d * unixOpenFileDescriptorCount / unixMaxFileDescriptorCount;
        }
        return -1d;
    }

    public String getHost() {
        return host;
    }

    public String getOs() {
        return os;
    }

    public int getAvailableProcessors() {
        return availableProcessors;
    }

    public String getJavaVersion() {
        return javaVersion;
    }

    public String getJvmVersion() {
        return jvmVersion;
    }

    public String getPid() {
        return pid;
    }

    public Date getStartDate() {
        return startDate;
    }

    public String getJvmArguments() {
        return jvmArguments;
    }

    public long getFreeDiskSpaceInTemp() {
        return freeDiskSpaceInTemp;
    }

    public int getThreadCount() {
        return threadCount;
    }

    public int getPeakThreadCount() {
        return peakThreadCount;
    }

    public long getTotalStartedThreadCount() {
        return totalStartedThreadCount;
    }

    public List<ThreadInfo> getThreadInfoList() {
        // on trie sur demande (si affichage)
        List<ThreadInfo> result = new ArrayList<>(threadInfoList);
        Collections.sort(result);
        return Collections.unmodifiableList(result);
    }

    public List<ProcessInfo> getProcessInfoList() {
        // on trie sur demande (si affichage)
        List<ProcessInfo> result = new ArrayList<>(processInfoList);
        Collections.sort(result);
        return Collections.unmodifiableList(result);
    }

    public boolean isStackTraceEnabled() {
        for (ThreadInfo threadInformations : threadInfoList) {
            List<StackTraceElement> stackTrace = threadInformations.getStackTrace();
            if (stackTrace != null && !stackTrace.isEmpty()) {
                return true;
            }
        }
        return false;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public String toString() {
        return getClass().getSimpleName() + "[pid=" + getPid() + ", host=" + getHost()
                + ", javaVersion=" + getJavaVersion() + ']';
    }
}


text:
piccolodb
=========

Very simple embed nosql database to store and retrive data in JSON format, it is built on top of google's Json library (gson). It's recommended for simple data storage and retrive.

## Basic Features

### Load the database

In PiccoloDB the database is a simple folder with files in it, so basically any folder can be used, here is an example of how load a database in a random selected folder:

```java
String basePath = System.getProperty("java.io.tmpdir") + "TESTDB\\";
PiccoloDB db = new PiccoloDB();
db.load(basePath);
```

### Save a Json
```java
JsonObject o = new JsonObject();
o.addProperty("field1", "Bla");
//          Entity/Table Identifier
db.save(o, "entitytest", 1l);
```
### Retrieve a Json
```java
JsonObject jsonObject = db.get("entitytest", 1l);
```

### List all jsons from an entity
```java
List<JsonObject> result = db.listAll("entitytest");
```

More features comming out soon!


text:
import string, time

from dbobj.dbexceptions import dbRecordNotFoundException
from dbobj.dbobj import dbRecord, dbTable

import docbook;

class lng_lex(dbRecord):

  def __init__(self, app, **args):
    if args.has_key("fields"):
      dbRecord.__init__(self, app, "lng_lex", args["fields"])
    else:
      dbRecord.__init__(self, app, "lng_lex", args)

  def __len__(self):
    return len(self.form)

  def __cmp__(self, other):
    if other == None:
      return -1
    if self.form < other.form:
      return -1
    elif self.form == other.form:
      return 0
    else:
      return 1

  def __hash__(self):
    return id(self)

  def getTag(self, tag):
    try:
      tagRecord=self.app.getObject("lng_lex_tag", lexnr=self.lexnr, tag=tag)
    except dbRecordNotFoundException, error:
      tagRecord=error.queryRec
    return tagRecord

  def getLink(self):
    return docbook.lexemelink() % (self.lexnr,
                                   docbook.filter(self.form),
                                   docbook.filter(self.glosse))

  def asDocbook(self):
    return docbook.glossentry() % (self.lexnr,
                                   docbook.filter(self.form),
                                   docbook.filter(self.phonetic_form),
                                   docbook.filter(self.glosse),
                                   docbook.filter(self.description),
                                   docbook.filter(self.alternative_form))
class lng_lexemes(dbTable):
  """
    Collection class for all lexeme data.
  """

  def __init__(self, app):
    dbTable.__init__(self, app=app
                         , table="lng_lex"
                         , recObj=lng_lex
                    )

  def select(self, queryRec, orderBy = None):
    dbTable.select(self, queryRec, orderBy = None)
    self.rows.sort()

  def export(self, query, format, *args):
    """
    Returns a unicode object containing the selected data
    in the specified format. Valid formats are:
    * docbook

    XXX: move formats to constants
    """
    doc = []
    if format == "docbook":
      doc.append(docbook.xmlHeader("appendix"))
      doc.append("<appendix><title>Lexicon</title>")
      self.select(query, "order by language, form, glosse")
      languagenr = -1
      section = -1
      for r in self.rows:
        if languagenr != r.languagenr:
          if languagenr != -1:
            doc.append('</glossdiv>')
            doc.append('</glossary>')
            doc.append('
')
            section = -1
          doc.append('
<title>%s</title>\n<glossary>' %
                     (r.languagenr, r.language))
          languagenr = r.languagenr
        if section != r.form[:1]:
          if section != -1:
            doc.append('</glossdiv>')
          doc.append('<glossdiv id="lang_%i_%s"><title>%s</title>' %
                     (r.languagenr, r.form[:1], r.form[:1]))
          section = r.form[:1]
        doc.append(r.asDocbook())
      doc.append("</glossdiv>\n</glossary>")
      doc.append("
")
      doc.append("</appendix>")
      return u"\n".join(doc)

    else:
      raise NotImplementedError("Export in format %s not yet implemented" % format)

__copyright__="""
    copyright            : (C) 2002 by Boudewijn Rempt
                           see copyright notice for license
    email                : boud@valdyas.org
"""

__revision__="""$Revision: 1.16 $"""[11:-2]


text:
package com.paessler.prtg.util.concurrency;

import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Map;

/**
 * CLASS: ThreadUtility - Thread utility functions
 *
 */
public abstract class ThreadUtility
{

	////////////////////////////////////////////////////////////////////
	/**
	 * Print all Current Threads
	 * @param ps	PrintStream to print data to
	 */
	public static void printThreads(PrintStream ps)
	{
		ArrayList<Thread> vect = getAllThreads();
		int i = 0;
		for( Thread t : vect)
		{
			ps.println("Thread[" + i + "] " + t.toString());
			i++;
		}
	}	// printThreads

	////////////////////////////////////////////////////////////////////
	/**
	 * returns a summary string with the thread name/id and stack dump of each active thread
	 */
	public static StringBuilder getAllStackDumps(StringBuilder sb)
	{
		Map<Thread,StackTraceElement[]> allThreads = Thread.getAllStackTraces();
		for( Thread t : allThreads.keySet() )
		{
			sb.append("@@@@@@@@@@@@@@@@@@@@@@\n");
			sb.append("Thead t->" + t.getId() + " " + t.getName() + "\n");
			StackTraceElement[] steArray = allThreads.get(t);
			for( StackTraceElement ste : steArray )
			{
				sb.append("\t");
				sb.append(ste.toString());
				sb.append("\n");
			}
		}
		return sb;
	}//method
	////////////////////////////////////////////////////////////////////
	/**
	 * returns a summary string with the thread name/id and stack dump of each active thread
	 */
	public static String getAllStackDumps()
	{
		StringBuilder sb = new StringBuilder();
		getAllStackDumps(sb);
		return sb.toString();
	}//method

	////////////////////////////////////////////////////////////////////
	/**
	 * Return all Current Threads as a vector
	 * @return Vector Vector of Threads
	 */
	public static ArrayList<Thread> getAllThreads()
	{
		ThreadGroup tg = getRootThreadGroup();
		int totthr = tg.activeCount();
		Thread[] threadList = new Thread[totthr * 2];
		totthr = tg.enumerate(threadList, true);
		ArrayList<Thread> retVal = new ArrayList<Thread>();
		//Log.printDebug("Root="+tg.toString()+",  Thead Count="+totthr);
		for (int i = 0; i < totthr; i++)
		{
			retVal.add(threadList[i]);
		}
		return retVal;
	}	// getAllThreads

	////////////////////////////////////////////////////////////////////
	/**
	 * Set the name of the threads for readability
	 */
	public static void setThreadName(String name)
	{
		Thread thisthread = Thread.currentThread();
		setThreadName(thisthread, name);
	}

	////////////////////////////////////////////////////////////////////
	/**
	 * Set the name of the threads for readability
	 */
	public static void setThreadName(Thread thisthread, String name)
	{
		String thname = thisthread.getName();
		//		System.out.println("setMsgHandlerThreadName() Changing Task name from =>" + thname);
		if (thname.startsWith("Thread"))
		{
			thname = thname.substring(6);
		}
		thname = name + thname;
		thisthread.setName(thname);
		//		System.out.println("setMsgHandlerThreadName() Changed Task name to =>" + thisthread.getName());
	}

	////////////////////////////////////////////////////////////////////
	/**
	 * Sleep for a while
	 * @param millis 	How lng to sleep
	 * @reurn boolean If interrupted true, otherwise false.
	 */
	public static boolean sleep(long millis)
	{
		boolean retVal = false;
		if (millis > 0)
		{
			try
			{
				Thread.sleep(millis);
			} catch (InterruptedException e)
			{
				retVal = true;
				System.err.println("InterruptedException ->" + e);
				e.printStackTrace();
			}
		}
		return retVal;
	}

	////////////////////////////////////////////////////////////////////
	/**
	 * Print all Current Threads
	 * @param ps	PrintStream to print data to
	 */
	public static ThreadGroup getRootThreadGroup()
	{
		ThreadGroup retVal = null;
		ThreadGroup tmp = Thread.currentThread().getThreadGroup();
		while (tmp != null)
		{
			retVal = tmp;
			tmp = retVal.getParent();
		}
		return retVal;
	}

	////////////////////////////////////////////////////////////////////
	/**
	 *
	 */
	public static String getThreadIDString(Thread t, boolean printtname)
	{
		if (t == null)
			return "NULL THREAD";

		String retVal = t.getId() +(printtname ? ":" + t.getName() : "");
		return retVal;
	}//method
	////////////////////////////////////////////////////////////////////
	/**
	 *
	 */
	public static String getThreadIDString(Thread t)
	{
		return getThreadIDString(t, false);
	}//method

	public static String getThreadIDString(boolean printtname)
	{
		return getThreadIDString(Thread.currentThread(), printtname);
	}//method
	public static String getThreadIDString()
	{
		return getThreadIDString(Thread.currentThread(), false);
	}//method

	////////////////////////////////////////////////////////////////////
	////////////////////////////////////////////////////////////////////
	/*public static void main(String[] arg)
	{

	}*/
}//class


text:
package org.recap.util;

import org.junit.Test;
import org.recap.ReCAPConstants;
import org.recap.model.csv.FailureReportReCAPCSVRecord;
import org.recap.model.jpa.ReportDataEntity;
import org.recap.model.jpa.ReportEntity;

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

import static org.junit.Assert.*;

/**
 * Created by peris on 8/16/16.
 */
public class CSVReportHelperUtil_UT {

    @Test
    public void generateCSVRecord() throws Exception {
        ReCAPCSVFailureRecordGenerator reCAPCSVRecordGenerator = new ReCAPCSVFailureRecordGenerator();

        ReportEntity reportEntity = new ReportEntity();
        List dataEntities = new ArrayList<>();

        ReportDataEntity barcodeReportDataEntity = new ReportDataEntity();
        barcodeReportDataEntity.setHeaderName(ReCAPConstants.ITEM_BARCODE);
        barcodeReportDataEntity.setHeaderValue("1231");
        dataEntities.add(barcodeReportDataEntity);

        ReportDataEntity callNumberReportDataEntity = new ReportDataEntity();
        callNumberReportDataEntity.setHeaderName(ReCAPConstants.LOCAL_ITEM_ID);
        callNumberReportDataEntity.setHeaderValue("1231");
        dataEntities.add(callNumberReportDataEntity);

        ReportDataEntity errrorDescriptionDataEntity = new ReportDataEntity();
        errrorDescriptionDataEntity.setHeaderName(ReCAPConstants.ERROR_DESCRIPTION);
        errrorDescriptionDataEntity.setHeaderValue("At least on subfield should be there for $245");
        dataEntities.add(errrorDescriptionDataEntity);

        reportEntity.setReportDataEntities(dataEntities);

        FailureReportReCAPCSVRecord failureReportReCAPCSVRecord =
                reCAPCSVRecordGenerator.prepareFailureReportReCAPCSVRecord(reportEntity);

        assertNotNull(failureReportReCAPCSVRecord);

    }

}


text:
/*
AUTHORS: Tuan Anh Nguyen

DESCRIPTION: include file used by the POP-C++ compiler
*/

#ifndef _POPC_SYSTEM_HEADERS_
#define _POPC_SYSTEM_HEADERS_
#include <paroc_base.h>

#include <paroc_mutex.h>
#include <paroc_interface.h>

#include <paroc_broker.h>
#include <paroc_broker_factory.h>

#include <paroc_buffer.h>
#include <paroc_buffer_utils.h>
#include <paroc_system.h>
#include <paroc_utils.h>

#endif


text:
import numpy as np

def subtract_nonzero_elements(arr,minuend):
    newarr = arr
    np.putmask(newarr,newarr != 0, minuend-newarr)
    return(newarr)

def replace_zero_elements(arr,replacement):
    newarr = np.copy(arr)
    newarr[newarr == 0] = replacement

    return(newarr)

def num_nonzero_elements(arr):
   return(len(arr[ arr != 0 ]))


text:
<?xml version="1.0" encoding="utf-8"?><!--
  ~ Copyright (c) 2017 Dewin J. Martínez.
  ~
  ~ 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.
  -->

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"
    tools:context="com.github.dewinjm.textclock.demo.MainActivity">

    <com.github.dewinjm.textclock.TextClock
        android:id="@+id/textclock"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="center_vertical"
        app:color="@color/colorPrimary"
        app:format24Hour="false"
        app:showSecond="true" />
</LinearLayout>


text:
/* Decimal floating point is one of the extension to IEEE 754, which is
   described in http://grouper.ieee.org/groups/754/revision.html and
   http://www2.hursley.ibm.com/decimal/.  It completes binary floating
   point by representing floating point more exactly.  */

#ifndef DFP_H
#define DFP_H

/* When using decimal128, this is the maximum string length + 1
 * (value comes from libdecnumber's DECIMAL128_String constant).  */
#define MAX_DECIMAL_STRING  43

extern void decimal_to_string (const gdb_byte *, int, enum bfd_endian, char *);
extern int decimal_from_string (gdb_byte *, int, enum bfd_endian,
				const char *);
extern void decimal_from_integral (struct value *from, gdb_byte *to,
				   int len, enum bfd_endian byte_order);
extern void decimal_from_floating (struct value *from, gdb_byte *to,
				   int len, enum bfd_endian byte_order);
extern DOUBLEST decimal_to_doublest (const gdb_byte *from, int len,
				     enum bfd_endian byte_order);
extern void decimal_binop (enum exp_opcode,
			   const gdb_byte *, int, enum bfd_endian,
			   const gdb_byte *, int, enum bfd_endian,
			   gdb_byte *, int, enum bfd_endian);
extern int decimal_is_zero (const gdb_byte *, int, enum bfd_endian);
extern int decimal_compare (const gdb_byte *, int, enum bfd_endian,
			    const gdb_byte *, int, enum bfd_endian);
extern void decimal_convert (const gdb_byte *, int, enum bfd_endian,
			     gdb_byte *, int, enum bfd_endian);

#endif


text:
// coding: utf-8
// ----------------------------------------------------------------------------

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

#ifndef XPCC_LPC__GPIO_HPP
#define XPCC_LPC__GPIO_HPP

#include <xpcc/architecture/driver/gpio.hpp>
#include "../lpc.hpp"

namespace xpcc
{
	namespace gpio
	{
		/**
		 * \ingroup	lpc2000
		 */
		enum Configuration
		{
			NORMAL,		///< standard operation (floating input, external signal needed!)
		};
	}
}

/**
 * \brief	Create a input/output pin type
 *
 * TODO No internal pullup, reentrant only on set/reset, not on output/input
 *
 * All I/O functions are reentrant and therefore may be used from within
 * an interrupt and the normal program. To achieve this every function has to
 * operate on read/write-only registers, so the Output Data Status
 * Register (ODSR) had to be disabled for write access.
 *
 * Operations take between 1 and 6 cycles depending how much information is
 * already present in the registers (PIO base register and Pin mask may be loaded).
 *
 * Example:
 * \code
 * GPIO__OUTPUT(Led1, 0, 12);
 * GPIO__OUTPUT(Led2, 0, 13);
 * ...
 *
 * Led1::setOutput();
 * Led2::setOutput();
 *
 * Led1::toggle();
 * Led2::set();
 * \endcode
 *
 * This generates:
 * \verbatim
mvn     r3, #0xb00      ; Initialize registers
mov     r2, #0x40000
mov     r1, #0x20000

str     r2, [r3, #-255] ; Led1.setOutput();
str     r2, [r3, #-239]

str     r1, [r3, #-255] ; Led2.setOutput();
str     r1, [r3, #-239]

ldr     r0, [r3, #-199] ; Led1::toggle()
tst     r0, #0x40000
strne   r2, [r3, #-207]
streq   r2, [r3, #-203]

str     r1, [r3, #-207] ; Led2::set()
\endverbatim
 *
 * Here you can see that the set() functions takes only one operation because
 * r1 and r3 are already initialized. If we call the same function out of context
 * it needs three operations:
 *
 * \verbatim
mov     r2, #0x20000    ; Initialize registers
mvn     r3, #0xb00
str     r2, [r3, #-207] ; Led2::set()
\verbatim
 *
 * Notes:
 * - In most LPC2000 devices, P0.14 is used for entering ISP mode (when being
 *   held low during reset). In the LPC23xx and LPC24xx, however, P2.10 is used
 *   to enter ISP mode.
 * - All LPC2000 microcontroller port 0 pins are true bi-directional GPIOs.
 *   The only minor exception is that the two I2C pins have an open drain
 *   output structure. With external pull-up resistors, they can also be used
 *   as true GPIOs.
 * - There are no programmable pull-up resistors. But some pins have internal
 *   pull-ups. These pull-ups are always active and can not be disabled.
 *   Set those pins high or keep them floating before entering power down mode.
 *   If set low, they will consume around 50 μA (typical) on each pin.
 *   Port 0 does not have any internal pull-ups. These pins can be set low.
 * - The GPIO pins can source or sink 4mA maximum.
 * - The toggling speed on the standard GPIO pins is system_clock/14.
 *   If 72MHz operation is used, then the toggling speed is around 5MHz.
 *   The toggling speed on the Fast GPIO pins is system clock/4. If 72MHz
 *   operation is used, then the toggling speed is around 18MHz.
 * - In LPC23xx new accelerated GPIO functions were introduced.
 *   Only Ports 0 and 1 are accessible by the legacy group of registers.
 *   See UM10211, p170
 *
 * External Interrupts:
 * - In some devices (like the LPC23xx and LPC24xx series), all pins on
 *   ports 0 and 2 plus EXTINTx pins can be used for external interrupts.
 *   However, in other devices, only dedicated EXTINTx pins could be used as
 *   external interrupts. Please note that only the dedicated EXTINTx pins
 *   can wake the chip from power down mode.
 *
 * \hideinitializer
 * \ingroup	lpc2000
 */

#ifdef __ARM_LPC23_24__
#include "gpio/gpio_lpc23_24xx.hpp"
#else
#include "gpio/gpio_lpc21xx.hpp"
#endif

#endif // XPCC_LPC__GPIO_HPP


text:
require "spec_helper"

describe BitPlayer::ContentProviders::ViewProvider do
  class S; include BitPlayer::ContentProviders::ViewProvider; end

  describe ".source_class" do
    it "should raise an exception when no source class has been defined" do
      expect { S.source_class }.to raise_error(RuntimeError)
    end
  end
end


text:
package org.kie.workbench.common.stunner.bpmn.backend.workitem.service;

import java.util.Collection;
import java.util.HashMap;
import java.util.function.Function;

import org.jbpm.process.workitem.WorkDefinitionImpl;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.kie.workbench.common.stunner.bpmn.backend.workitem.service.WorkItemDefinitionRemoteService.WorkItemsHolder;
import org.kie.workbench.common.stunner.bpmn.workitem.WorkItemDefinition;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.when;

@RunWith(MockitoJUnitRunner.class)
public class WorkItemDefinitionRemoteServiceTest {

    private static final String URL = "http://url";
    private static final String WD1_NAME = "wd1Name";
    private static final String WD2_NAME = "wd2Name";

    @Mock
    private Function<String, WorkItemsHolder> lookupService;

    private WorkItemDefinitionRemoteService tested;
    private WorkDefinitionImpl wd1;
    private WorkDefinitionImpl wd2;

    @Before
    public void init() {
        wd1 = new WorkDefinitionImpl();
        wd1.setName(WD1_NAME);
        wd2 = new WorkDefinitionImpl();
        wd2.setName(WD2_NAME);
        when(lookupService.apply(eq(URL)))
                .thenReturn(new WorkItemsHolder(new HashMap<String, WorkDefinitionImpl>(2) {{
                    put(WD1_NAME, wd1);
                    put(WD2_NAME, wd2);
                }}));
        tested = new WorkItemDefinitionRemoteService(lookupService);
    }

    @Test
    public void testExecute() {
        Collection<WorkItemDefinition> result =
                tested.execute(WorkItemDefinitionRemoteRequest.build(URL,
                                                                     new String[]{WD1_NAME, WD2_NAME}));

        assertFalse(result.isEmpty());
        assertEquals(2, result.size());
        assertTrue(result.stream().anyMatch(w -> WD1_NAME.equals(w.getName())));
        assertTrue(result.stream().anyMatch(w -> WD2_NAME.equals(w.getName())));
    }

    @Test
    public void testExecuteFiltered1() {
        Collection<WorkItemDefinition> result =
                tested.execute(WorkItemDefinitionRemoteRequest.build(URL,
                                                                     new String[]{WD1_NAME}));

        assertFalse(result.isEmpty());
        assertEquals(1, result.size());
        assertTrue(result.stream().anyMatch(w -> WD1_NAME.equals(w.getName())));
    }

    @Test
    public void testExecuteFiltered2() {
        Collection<WorkItemDefinition> result =
                tested.execute(WorkItemDefinitionRemoteRequest.build(URL,
                                                                     new String[]{WD2_NAME}));

        assertFalse(result.isEmpty());
        assertEquals(1, result.size());
        assertTrue(result.stream().anyMatch(w -> WD2_NAME.equals(w.getName())));
    }
}


text:
package org.apache.zookeeper.server.quorum;

import java.util.Collections;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.server.SessionTracker;
import org.apache.zookeeper.server.ZooKeeperServerListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * A session tracker that supports upgradeable local sessions.
 */
public abstract class UpgradeableSessionTracker implements SessionTracker {

    private static final Logger LOG = LoggerFactory.getLogger(UpgradeableSessionTracker.class);

    private ConcurrentMap<Long, Integer> localSessionsWithTimeouts;
    private ConcurrentMap<Long, Integer> upgradingSessions;
    protected LocalSessionTracker localSessionTracker;
    protected boolean localSessionsEnabled;

    public void start() {
    }

    public void createLocalSessionTracker(SessionExpirer expirer, int tickTime, long id, ZooKeeperServerListener listener) {
        this.localSessionsWithTimeouts = new ConcurrentHashMap<Long, Integer>();
        this.localSessionTracker = new LocalSessionTracker(expirer, this.localSessionsWithTimeouts, tickTime, id, listener);
        this.upgradingSessions = new ConcurrentHashMap<Long, Integer>();
    }

    public boolean isTrackingSession(long sessionId) {
        return isLocalSession(sessionId) || isGlobalSession(sessionId);
    }

    public boolean isLocalSession(long sessionId) {
        return localSessionTracker != null && localSessionTracker.isTrackingSession(sessionId);
    }

    @Override
    public boolean isLocalSessionsEnabled() {
        return localSessionsEnabled;
    }

    public boolean isUpgradingSession(long sessionId) {
        return upgradingSessions != null && upgradingSessions.containsKey(sessionId);
    }

    public void finishedUpgrading(long sessionId) {
        if (upgradingSessions != null) {
            upgradingSessions.remove(sessionId);
        }
    }

    public abstract boolean isGlobalSession(long sessionId);

    /**
     * Upgrades the session to a global session.
     * This simply removes the session from the local tracker and marks
     * it as global.  It is up to the caller to actually
     * queue up a transaction for the session.
     *
     * @param sessionId
     * @return session timeout (-1 if not a local session)
     */
    public int upgradeSession(long sessionId) {
        if (localSessionsWithTimeouts == null) {
            return -1;
        }
        // We won't race another upgrade attempt because only one thread
        // will get the timeout from the map
        Integer timeout = localSessionsWithTimeouts.remove(sessionId);
        if (timeout != null) {
            LOG.info("Upgrading session 0x{}", Long.toHexString(sessionId));
            // Track global session, which will add to global session tracker
            // on leader and do nothing on learner. Need to start track global
            // session in leader now to update the session expire between
            // LeaderRequestProcessor and PrepRequestProcessor.
            trackSession(sessionId, timeout);
            // Track ongoing upgrading sessions, learner will use it to find
            // other sessions it has which are not in local and global sessions
            upgradingSessions.put(sessionId, timeout);
            localSessionTracker.removeSession(sessionId);
            return timeout;
        }
        return -1;
    }

    protected void removeLocalSession(long sessionId) {
        if (localSessionTracker == null) {
            return;
        }
        localSessionTracker.removeSession(sessionId);
    }

    public void checkGlobalSession(long sessionId, Object owner)
        throws KeeperException.SessionExpiredException, KeeperException.SessionMovedException {
        throw new UnsupportedOperationException();
    }

    public long getLocalSessionCount() {
        if (localSessionsWithTimeouts == null) {
            return 0;
        }
        return localSessionsWithTimeouts.size();
    }

    public Set<Long> localSessions() {
        return (localSessionTracker == null) ? Collections.<Long>emptySet()
            : localSessionTracker.localSessions();
    }
}


text:
layout: post
title: 'Take the Railo 4k Challenge and win a ticket to cf.Objective()!'
date: 2010-3-12
wordpress-id: take-the-railo-4k-challenge-and-win-a-ticket-to-cf-objective
comments: true
---

If you are interested in Railo and you are thinking to take part of cf.Objective() you cannot loose this. Write 4k of amazing Railo code and win a ticket.


text:
#ifndef LLGL_DBG_BUFFER_H
#define LLGL_DBG_BUFFER_H

#include <LLGL/Buffer.h>
#include <string>

namespace LLGL
{

class DbgBuffer final : public Buffer
{

    public:

        void SetName(const char* name) override;

        BufferDescriptor GetDesc() const override;

    public:

        DbgBuffer(Buffer& instance, const BufferDescriptor& desc);

    public:

        Buffer&                 instance;
        const BufferDescriptor  desc;
        std::string             label;
        std::uint64_t           elements    = 0;
        bool                    initialized = false;
        bool                    mapped      = false;

};

} // /namespace LLGL

#endif

// ================================================================================


text:
LIBINT_VERSION = "2.2.0-beta1"
lib_path = joinpath(dirname(@__FILE__),"usr","lib")

@static if Sys.islinux()
	try begin
			run(`grep --ignore-case --silent 'avx' /proc/cpuinfo`)
			SIMD = "avx"
			cd(joinpath(dirname(@__FILE__),"usr","lib"))
			run(`ln -sf libint2jl-$LIBINT_VERSION-$SIMD.so libint2jl.so`)
			run(`ln -sf libint2-$LIBINT_VERSION-$SIMD.so libint2-QuantumLab.so`)
		end
	catch
		warn("Your system (CPU) does not support AVX.\n
							The Libint2 Library for Linux is only provided as AVX enabled version.\n
							Therefore a Libint2 stub is used.\n
							You should be able to start QuantumLab and perform calculation but
							with a drastically decreased performance.\n
							You can try to build your own version of libint2.so and libint2jl.so.
							As a reference take a look at the Makefile in QuantumLab/deps/usr/src.")
	end
end

@static if Sys.isapple()
	try begin
			run(pipeline(`sysctl machdep.cpu.features`,`grep --ignore-case  --silent 'avx\|sse'`))
			SIMD = "avx"
			try run(pipeline(`sysctl machdep.cpu.features`,`grep --ignore-case --silent 'avx'`))
			catch
				SIMD = "sse"
			end
			cd(joinpath(dirname(@__FILE__),"usr","lib"))
			run(`ln -sf libint2jl-$LIBINT_VERSION-$SIMD.dylib libint2jl.so`)
			run(`ln -sf libint2-$LIBINT_VERSION-$SIMD.dylib libint2-QuantumLab.so`)
		end
	catch
		warn("Your CPU does support neither SSE nor AVX
							The Libint2 Library for Linux is only provided as AVX enabled version.\n
							Therefore a Libint2 stub is used.\n
							You should be able to start QuantumLab and perform calculation but
							with a drastically decreased performance.\n
							You can try to build your own version of libint2.dylib and libint2jl.dylib.
							As a reference take a look at the Makefile in QuantumLab/deps/usr/src.")
	end
end


text:
FROM postgres:VERSION
RUN mkdir -p /tmp/optimizations
ADD optimizations.conf /tmp/optimizations/0.conf
ADD 9.6/optimizations.conf /tmp/optimizations/1.conf
RUN cat /tmp/optimizations/* >> /usr/share/postgresql/postgresql.conf.sample


text:
#include "Selection2DMask.hpp"

#include <QtCore/QDebug>
#include <QtCore/QJsonArray>
#include <QtCore/QJsonObject>

using namespace vx::filter;
using namespace vx::opencl;

//----------------DELETE-MASKS------------------------------------
void Selection2DMask::clearMask() {
  mutex.lock();
  if (ellipses.size() != 0) {
    this->ellipses.clear();
  }
  if (rectangles.size() != 0) {
    this->rectangles.clear();
  }
  if (polygons.size() != 0) {
    this->polygons.clear();
  }
  mutex.unlock();
  Q_EMIT this->changed();
}

void Selection2DMask::addMaskFromJson(const QJsonObject& json) {
  {
    QMutexLocker locker(&mutex);

    for (const auto& shapeJson : json["Shapes"].toArray()) {
      auto shape = Shape::fromJson(shapeJson.toObject());

      auto shapeRectangle = dynamic_cast<Rectangle*>(shape);
      if (shapeRectangle) {
        this->rectangles.append(shapeRectangle);
        continue;
      }

      auto shapeEllipse = dynamic_cast<Ellipse*>(shape);
      if (shapeEllipse) {
        this->ellipses.append(shapeEllipse);
        continue;
      }

      auto shapePolygon = dynamic_cast<Polygon*>(shape);
      if (shapePolygon) {
        this->polygons.append(shapePolygon);
        continue;
      }

      // TODO: there should be only one list of shapes
      qCritical() << "Unknown shape:" << shape;
      delete shape;
    }

  }  // release lock
  Q_EMIT this->changed();
}
QJsonObject Selection2DMask::getMaskJson() {
  QMutexLocker locker(&mutex);

  QJsonObject result;

  QJsonArray array;
  for (const auto& shape : rectangles) array << shape->getJsonFull();
  for (const auto& shape : ellipses) array << shape->getJsonFull();
  for (const auto& shape : polygons) array << shape->getJsonFull();
  result["Shapes"] = array;

  return result;
}

//---------------ADD-MASKS-----------------------------------------
void Selection2DMask::addEllipse(qreal midPointX, qreal midPointY,
                                 qreal radiusX, qreal radiusY) {
  mutex.lock();
  this->ellipses.append(new Ellipse(midPointX, midPointY, radiusX, radiusY));
  mutex.unlock();
  Q_EMIT this->changed();
}

void Selection2DMask::addRectangle(qreal startX, qreal startY, qreal endX,
                                   qreal endY) {
  mutex.lock();
  this->rectangles.append(new Rectangle(startX, startY, endX, endY));
  mutex.unlock();
  Q_EMIT this->changed();
}

void Selection2DMask::addPolygon(QVector<QPointF> polygonCoords) {
  mutex.lock();
  this->polygons.append(new Polygon(polygonCoords));
  mutex.unlock();
  Q_EMIT this->changed();
}

//----------------CPU-MASKS------------------------------------------

QVector<rectangleData> Selection2DMask::getRectangleCoords() {
  QVector<rectangleData> returnData;
  mutex.lock();
  for (int i = 0; i < this->rectangles.size(); i++) {
    returnData.append(this->rectangles.at(i)->getTransformationMatrix());
  }
  mutex.unlock();
  return returnData;
}

QVector<ellipseData> Selection2DMask::getEllipseCoords() {
  QVector<ellipseData> returnData;
  mutex.lock();
  for (int i = 0; i < this->ellipses.size(); i++) {
    returnData.append(this->ellipses.at(i)->getTransformationMatrix());
  }
  mutex.unlock();
  return returnData;
}

QVector<polygonData> Selection2DMask::getPolygonCoords() {
  QVector<polygonData> returnData;
  mutex.lock();
  for (int i = 0; i < this->polygons.size(); i++) {
    returnData.append(this->polygons.at(i)->getTransformatedPolyCoords());
  }
  mutex.unlock();
  return returnData;
}

//-----------------------POINT-CHECK-CPU-----------------------------------

bool Selection2DMask::isPointIn(QPointF coords) {
  bool result = false;
  /*
   *  Checks every single shape, if one shape contains the point the result
   * turns to true.
   *
   */

  // checks if a rectangle shape contains the coordinate
  QRectF identityRect = QRectF(0, 0, 1, 1);
  auto rectangleCoords = this->getRectangleCoords();
  for (int i = 0; (i < rectangleCoords.size() && !result); i++) {
    rectangleData rect = rectangleCoords.at(i);
    QTransform matrixRect(rect.scaleX, rect.angleY, rect.angleX, rect.scaleY,
                          rect.dx, rect.dy);
    QPointF translatedCoords = matrixRect.map(coords);
    QPainterPath check;
    check.addRect(identityRect);
    if (check.contains(translatedCoords)) {
      result = true;
    }
  }

  // checks if a ellipse shape contains the coordinate
  auto ellipseCoords = this->getEllipseCoords();
  for (int i = 0; (i < ellipseCoords.size() && !result); i++) {
    ellipseData ellipse = ellipseCoords.at(i);
    QTransform matrixEllipse(ellipse.scaleX, ellipse.angleY, ellipse.angleX,
                             ellipse.scaleY, ellipse.dx, ellipse.dy);
    QPointF translatedCoords = matrixEllipse.map(coords);
    QPainterPath check;
    check.addEllipse(QPointF(0, 0), 1, 1);
    if (check.contains(translatedCoords)) {
      result = true;
    }
  }

  // checks if a polygon shape contains the coordinate
  auto polygonCoords = this->getPolygonCoords();
  for (int i = 0; (i < polygonCoords.size() && !result); i++) {
    polygonData polygon = polygonCoords.at(i);
    QPolygonF createdPoly(polygon.cpuCoords);
    QPainterPath check;
    check.addPolygon(createdPoly);
    if (check.contains(coords)) {
      result = true;
    }
  }

  return result;
}

//-------------------GPU-MASKS--------------------------------------

cl::Buffer Selection2DMask::getRectangleBuffer(CLInstance* instance) {
  auto rectangleCoords = this->getRectangleCoords();
  if (rectangleCoords.isEmpty()) {
    // buffer with one element since no elements are not allowed
    return instance->createBuffer(sizeof(rectangleData));
  }

  size_t size = (sizeof(rectangleData) * rectangleCoords.size());
  cl::Buffer buffer = instance->createBuffer(size, rectangleCoords.data());
  return buffer;
}

cl::Buffer Selection2DMask::getEllipseBuffer(CLInstance* instance) {
  auto ellipseCoords = this->getEllipseCoords();
  if (ellipseCoords.isEmpty()) {
    // buffer with one element since no elements are not allowed
    return instance->createBuffer(sizeof(ellipseData));
  }

  size_t size = (sizeof(ellipseData) * ellipseCoords.size());
  cl::Buffer buffer = instance->createBuffer(size, ellipseCoords.data());
  return buffer;
}

cl::Buffer Selection2DMask::getPolygonBufferOffset(CLInstance* instance) {
  auto polygonCoords = this->getPolygonCoords();
  if (polygonCoords.isEmpty()) {
    // buffer with one element since no elements are not allowed
    return instance->createBuffer(sizeof(cl_int));
  }
  cl::Buffer offsetBuffer;
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored \
    "-Wignored-attributes"  // cl_int has the aligned(4) attribute under Linux
                            // which has no effect (because int32_t is already
                            // 4-byte aligned) and can be ignored
  QVector<cl_int> offset;
#pragma GCC diagnostic pop
  offset.append(0);
  for (int i = 0; i < polygonCoords.size(); i++) {
    offset.append(polygonCoords.at(i).gpuCoords.size() + offset.at(i));
  }
  size_t size = sizeof(cl_int) * offset.size();
  offsetBuffer = instance->createBuffer(size, offset.data());
  return offsetBuffer;
}

cl::Buffer Selection2DMask::getPolygonBuffer(CLInstance* instance) {
  auto polygonCoords = this->getPolygonCoords();
  if (polygonCoords.isEmpty()) {
    // buffer with one element since no elements are not allowed
    return instance->createBuffer(sizeof(polygonPoint));
  }
  QVector<polygonPoint> coords;
  for (int i = 0; i < polygonCoords.size(); i++) {
    for (int j = 0; j < polygonCoords.at(i).gpuCoords.size(); j++) {
      coords.append(polygonCoords.at(i).gpuCoords.at(j));
    }
  }
  size_t size = sizeof(polygonPoint) * coords.size();
  cl::Buffer polygons = instance->createBuffer(size, coords.data());
  return polygons;
}

void Selection2DMask::translateOrigin(qreal x, qreal y) {
  this->mutex.lock();
  for (int i = 0; i < rectangles.size(); i++) {
    rectangles.at(i)->translateOrigin(x, y);
  }

  for (int i = 0; i < ellipses.size(); i++) {
    ellipses.at(i)->translateOrigin(x, y);
  }

  for (int i = 0; i < polygons.size(); i++) {
    polygons.at(i)->translateOrigin(x, y);
  }
  this->mutex.unlock();
}

void Selection2DMask::rotate(qreal angel) {
  this->mutex.lock();
  for (int i = 0; i < rectangles.size(); i++) {
    rectangles.at(i)->rotate(angel);
  }

  for (int i = 0; i < ellipses.size(); i++) {
    ellipses.at(i)->rotate(angel);
  }

  for (int i = 0; i < polygons.size(); i++) {
    polygons.at(i)->rotate(angel);
  }
  this->mutex.unlock();
}

//----------------PAINTER-PATH----------------------------------
QPainterPath Selection2DMask::getPath() {
  QPainterPath result;
  mutex.lock();
  for (int i = 0; i < rectangles.size(); i++) {
    result = result.united(rectangles.at(i)->path());
  }

  for (int i = 0; i < ellipses.size(); i++) {
    result = result.united(ellipses.at(i)->path());
  }

  for (int i = 0; i < polygons.size(); i++) {
    result = result.united(polygons.at(i)->path());
  }
  mutex.unlock();
  return result.simplified();
}


text:
require_relative 'base_message'

module Easemob
  class FileoperationMessage < Easemob::BaseMessage
  end
end


text:
var reallybigfile = {};
var fred
var bert
var ernie

if(  fred){ /*FIXME on the same line*/

}

if(  wow){ /*FIXME on the same line*/

}

var endoffile = true


text:
    <meta charset="utf-8">

Welcome to the Continuous Delivery training!

<form action="/" method="post">
    <input name="user" type="text" width="20" placeholder="Pick a Username">
    <input name="start" type="submit" value="Login">
</form>

Version: {{version}} - Server: {{server}}


text:
package com.netflix.loadbalancer;

import rx.Observable;

public interface LoadBalancerObservableCommand<T> {
    /**
     * @return The {@link Observable} for the server. It is expected
     * that the actual execution is not started until the returned {@link Observable} is subscribed to.
     */
    public Observable<T> run(Server server);
}


text:
int
check_x25519_base_cb(char *parts[MAX_LINE_LENGTH])
{
    unsigned char *out;
    unsigned char *out2;
    unsigned char *scalar;
    int            ret;

    out = sodium_malloc(crypto_scalarmult_BYTES);
    out2 = sodium_malloc(crypto_scalarmult_BYTES);
    scalar = sodium_malloc(crypto_scalarmult_SCALARBYTES);
    sodium_hex2bin(scalar, crypto_scalarmult_SCALARBYTES,
                   parts[0], strlen(parts[0]), NULL, NULL, NULL);
    sodium_hex2bin(out, crypto_scalarmult_BYTES,
                   parts[1], strlen(parts[1]), NULL, NULL, NULL);
    crypto_scalarmult_base(out2, scalar);
    ret = memcmp(out, out2, crypto_scalarmult_BYTES);
    sodium_free(out2);
    sodium_free(out);
    sodium_free(scalar);

    return ret;
}

int
check_x25519_base(void)
{
    parse_stdin(check_x25519_base_cb, 2);

    return 0;
}

int
main(void)
{
    if (sodium_init() != 0) {
        return -1;
    }
    check_x25519_base();

    return 0;
}