text:
var register_win = Ti.UI.currentWindow;
//var self = Ti.UI.createView();
var Cloud = require('ti.cloud');
Cloud.debug = true;

// User Name
var userNameField = Ti.UI.createTextField({
	height : 35,
	top : 10,
	left : 40,
	width : 240,
	hintText : 'Username',
	keyboardType : Ti.UI.KEYBOARD_DEFAULT,
	returnKeyType : Ti.UI.RETURNKEY_DEFAULT,
	borderStyle : Ti.UI.INPUT_BORDERSTYLE_ROUNDED
});

// Listen for return events.
userNameField.addEventListener('return', function(e) {
	userNameField.blur();
	//alert('Input was: ' + userNameField.value);
});

// Add to the parent view.
register_win.add(userNameField);

// Password
var passwordField = Ti.UI.createTextField({
	height : 35,
	top : 50,
	left : 40,
	width : 240,
	hintText : 'password',
	keyboardType : Ti.UI.KEYBOARD_DEFAULT,
	returnKeyType : Ti.UI.RETURNKEY_DEFAULT,
	borderStyle : Ti.UI.INPUT_BORDERSTYLE_ROUNDED,
	passwordMask: true
});

// Listen for return events.
passwordField.addEventListener('return', function(e) {
	passwordField.blur();
	//alert('Input was: ' + passwordField.value);
});

// Add to the parent view.
register_win.add(passwordField);

// Create a TextField.
var passwordConfirmation = Ti.UI.createTextField({
	height : 35,
	top : 90,
	left : 40,
	width : 240,
	hintText : 'confirm password',
	keyboardType : Ti.UI.KEYBOARD_DEFAULT,
	returnKeyType : Ti.UI.RETURNKEY_DEFAULT,
	borderStyle : Ti.UI.INPUT_BORDERSTYLE_ROUNDED,
	passwordMask: true
});

// Listen for return events.
passwordConfirmation.addEventListener('return', function(e) {
	passwordConfirmation.blur();
	//alert('Input was: ' + passwordConfirmation.value);
});

// Add to the parent view.
register_win.add(passwordConfirmation);

// Create a TextField.
var firstName = Ti.UI.createTextField({
	height : 35,
	top : 130,
	left : 40,
	width : 240,
	hintText : 'First Name',
	keyboardType : Ti.UI.KEYBOARD_DEFAULT,
	returnKeyType : Ti.UI.RETURNKEY_DEFAULT,
	borderStyle : Ti.UI.INPUT_BORDERSTYLE_ROUNDED
});

// Listen for return events.
firstName.addEventListener('return', function(e) {
	firstName.blur();
	//alert('Input was: ' + firstName.value);
});

// Add to the parent view.
//register_win.add(firstName);

// Create a TextField.
var lastName = Ti.UI.createTextField({
	height : 35,
	top : 170,
	left : 40,
	width : 240,
	hintText : 'Last Name',
	keyboardType : Ti.UI.KEYBOARD_DEFAULT,
	returnKeyType : Ti.UI.RETURNKEY_DEFAULT,
	borderStyle : Ti.UI.INPUT_BORDERSTYLE_ROUNDED
});

// Listen for return events.
lastName.addEventListener('return', function(e) {
	lastName.blur();
	//alert('Input was: ' + lastName.value);
});

// Add to the parent view.
//register_win.add(lastName);

// Create a TextField.
var emailAddress = Ti.UI.createTextField({
	height : 35,
	top : 210,
	left : 40,
	width : 240,
	hintText : 'email@address.com',
	keyboardType : Ti.UI.KEYBOARD_DEFAULT,
	returnKeyType : Ti.UI.RETURNKEY_DEFAULT,
	borderStyle : Ti.UI.INPUT_BORDERSTYLE_ROUNDED
});

// Listen for return events.
emailAddress.addEventListener('return', function(e) {
	emailAddress.blur();
	//alert('Input was: ' + emailAddress.value);
});

// Add to the parent view.
//register_win.add(emailAddress);

// Create a Button.
var registerButton = Ti.UI.createButton({
	title : 'Register',
	height : 35,
	width : 100,
	top : 250,
});

// Listen for click events.
registerButton.addEventListener('click', function() {

	Cloud.Users.create ({
		username: userNameField.value,
		password: passwordField.value,
		password_confirmation : passwordConfirmation.value,
		//first_name: firstName.value,
		//last_name: lastName.value,
		//email: emailAddress.value
	}, function (e) {
		if (e.success) {
			//alert('Success');
			var alertDialog = Titanium.UI.createAlertDialog({
        title: 'Alert',
        message: "Thanks for registering, happy uploading!!",
        buttonNames: ['OK']
    	});
			alertDialog.show();
			alertDialog.addEventListener('click',function(e)
        {
            register_win.tabGroup.setActiveTab(0);
        });
		} else {
			alert('Fail');
		}
	});
});

// Add to the parent view.
register_win.add(registerButton);


text:
package org.spongepowered.common.registry.type.world;

import static com.google.common.base.Preconditions.checkNotNull;

import com.google.common.collect.ImmutableList;
import net.minecraft.world.EnumDifficulty;
import org.spongepowered.api.registry.AlternateCatalogRegistryModule;
import org.spongepowered.api.registry.util.AdditionalRegistration;
import org.spongepowered.api.registry.util.RegisterCatalog;
import org.spongepowered.api.world.difficulty.Difficulties;
import org.spongepowered.api.world.difficulty.Difficulty;

import java.util.Collection;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;

public final class DifficultyRegistryModule implements AlternateCatalogRegistryModule<Difficulty> {

    public static DifficultyRegistryModule getInstance() {
        return Holder.INSTANCE;
    }

    @RegisterCatalog(Difficulties.class)
    private final Map<String, Difficulty> difficultyMappings = new HashMap<>();

    @Override
    public Optional<Difficulty> getById(String id) {
        checkNotNull(id);
        if (!id.contains(":") && !id.equals("none")) {
            id = "minecraft:" + id; // assume vanilla
        }
        return Optional.ofNullable(this.difficultyMappings.get(checkNotNull(id).toLowerCase(Locale.ENGLISH)));
    }

    @Override
    public Collection<Difficulty> getAll() {
        return ImmutableList.copyOf(this.difficultyMappings.values());
    }

    @Override
    public Map<String, Difficulty> provideCatalogMap() {
        Map<String, Difficulty> newMap = new HashMap<>();
        for (Map.Entry<String, Difficulty> entry : this.difficultyMappings.entrySet()) {
            newMap.put(entry.getKey().replace("minecraft:", ""), entry.getValue());
        }
        return newMap;
    }

    @Override
    public void registerDefaults() {
        this.difficultyMappings.put("minecraft:peaceful", (Difficulty) (Object) EnumDifficulty.PEACEFUL);
        this.difficultyMappings.put("minecraft:easy", (Difficulty) (Object) EnumDifficulty.EASY);
        this.difficultyMappings.put("minecraft:normal", (Difficulty) (Object) EnumDifficulty.NORMAL);
        this.difficultyMappings.put("minecraft:hard", (Difficulty) (Object) EnumDifficulty.HARD);
    }

    @AdditionalRegistration
    public void additional() {
        for (EnumDifficulty difficulty : EnumDifficulty.values()) {
            if (!this.difficultyMappings.containsValue(difficulty)) {
                // TODO This doesn't have the modid...
                this.difficultyMappings.put(difficulty.name(), (Difficulty) (Object) difficulty);
            }
        }
    }

    private static final class Holder {
        static final DifficultyRegistryModule INSTANCE = new DifficultyRegistryModule();
    }
}

redpajama_set_name: RedPajamaGithub


text:
package io.crate.analyze.relations;

import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;

import java.io.IOException;

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

import io.crate.analyze.TableDefinitions;
import io.crate.expression.symbol.Symbols;
import io.crate.test.integration.CrateDummyClusterServiceUnitTest;
import io.crate.testing.SQLExecutor;

public class GroupByScalarAnalyzerTest extends CrateDummyClusterServiceUnitTest {

    private SQLExecutor executor;

    @Before
    public void prepare() throws IOException {
        executor = SQLExecutor.builder(clusterService)
            .addTable(TableDefinitions.USER_TABLE_DEFINITION)
            .build();
    }

    @Test
    public void testScalarFunctionArgumentsNotAllInGroupByThrowsException() throws Exception {
        expectedException.expect(IllegalArgumentException.class);
        expectedException.expectMessage("'(id * other_id)' must appear in the GROUP BY");
        executor.analyze("select id * other_id from users group by id");
    }

    @Test
    public void testValidGroupByWithScalarAndMultipleColumns() throws Exception {
        AnalyzedRelation relation = executor.analyze("select id * other_id from users group by id, other_id");
        assertThat(Symbols.pathFromSymbol(relation.outputs().get(0)).sqlFqn(), is("(id * other_id)"));
    }

    @Test
    public void testValidGroupByWithScalar() throws Exception {
        AnalyzedRelation relation = executor.analyze("select id * 2 from users group by id");
        assertThat(Symbols.pathFromSymbol(relation.outputs().get(0)).sqlFqn(), is("(id * 2::bigint)"));
    }

    @Test
    public void testValidGroupByWithMultipleScalarFunctions() throws Exception {
        AnalyzedRelation relation = executor.analyze("select abs(id * 2) from users group by id");
        assertThat(Symbols.pathFromSymbol(relation.outputs().get(0)).sqlFqn(), is("abs((id * 2::bigint))"));
    }
}


text:
/*
 * Created on 2005. 6. 28.
 *
 * TODO To change the template for this generated file go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
package com.zimbra.cs.redolog;

import com.zimbra.common.service.ServiceException;
import com.zimbra.cs.account.Provisioning;
import com.zimbra.cs.account.Server;
import com.zimbra.cs.util.Config;
import com.zimbra.cs.util.Zimbra;

/**
 * @author jhahm
 *
 * TODO To change the template for this generated type comment go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
public class RedoConfig {

    private static RedoConfig theInstance;
    static {
        try {
            theInstance = new RedoConfig();
        } catch (ServiceException e) {
            Zimbra.halt("Unable to read redolog configuration", e);
        }
    }

    private RedoConfig() throws ServiceException {
        reloadInstance();
    }

    private void reloadInstance() throws ServiceException {
        Server config = Provisioning.getInstance().getLocalServer();

        mServiceHostname = config.getAttr(Provisioning.A_zimbraServiceHostname);
        mRedoLogEnabled = config.getBooleanAttr(Provisioning.A_zimbraRedoLogEnabled, D_REDOLOG_ENABLED);
        mRedoLogPath =
            Config.getPathRelativeToZimbraHome(
                    config.getAttr(Provisioning.A_zimbraRedoLogLogPath,
                                   D_REDOLOG_PATH)).getAbsolutePath();
        mRedoLogArchiveDir =
            Config.getPathRelativeToZimbraHome(
                    config.getAttr(Provisioning.A_zimbraRedoLogArchiveDir,
                                   D_REDOLOG_ARCHIVEDIR)).getAbsolutePath();
        mRedoLogRolloverFileSizeKB =
            config.getLongAttr(Provisioning.A_zimbraRedoLogRolloverFileSizeKB,
                               D_REDOLOG_ROLLOVER_FILESIZE_KB);
        mRedoLogRolloverHardMaxFileSizeKB =
            config.getLongAttr(Provisioning.A_zimbraRedoLogRolloverHardMaxFileSizeKB,
                               D_REDOLOG_ROLLOVER_HARDMAX_FILESIZE_KB);
        mRedoLogRolloverMinFileAge =
            config.getLongAttr(Provisioning.A_zimbraRedoLogRolloverMinFileAge,
                               D_REDOLOG_ROLLOVER_MIN_FILE_AGE);
        mRedoLogDeleteOnRollover =
            config.getBooleanAttr(Provisioning.A_zimbraRedoLogDeleteOnRollover,
                                  D_REDOLOG_DELETE_ON_ROLLOVER);
        mRedoLogFsyncIntervalMS =
            config.getLongAttr(Provisioning.A_zimbraRedoLogFsyncIntervalMS,
                               D_REDOLOG_FSYNC_INTERVAL_MS);

        mRedoLogCrashRecoveryLookbackSec =
            config.getLongAttr(Provisioning.A_zimbraRedoLogCrashRecoveryLookbackSec,
                               D_REDOLOG_CRASH_RECOVERY_LOOKBACK_SEC);
    }

    public static synchronized void reload() throws ServiceException {
        theInstance.reloadInstance();
    }

    private String mServiceHostname;
    public static synchronized String serviceHostname() {
        return theInstance.mServiceHostname;
    }

    private boolean mRedoLogEnabled;
    private static final boolean D_REDOLOG_ENABLED = true;
    /**
     * Indicates whether redo logging is enabled.
     * @return
     */
    public static synchronized boolean redoLogEnabled() {
        return theInstance.mRedoLogEnabled;
    }

    private String mRedoLogPath;
    private static final String D_REDOLOG_PATH = "redolog/redo.log";
    /**
     * The path to the redo.log file.  Relative path is resolved against
     * ZIMBRA_HOME.  Default value is "$ZIMBRA_HOME/redolog/redo.log".
     * @return absolute path to redo log file
     */
    public static synchronized String redoLogPath() {
        return theInstance.mRedoLogPath;
    }

    private String mRedoLogArchiveDir;
    private static final String D_REDOLOG_ARCHIVEDIR = "redolog/archive";
    /**
     * Directory in which redo logs are archived.  When the current redo.log
     * file reaches a certain threshold, it is rolled over and archived.
     * That is, the current redo.log file is renamed to a timestamped name,
     * moved into the archive directory, and a new empty redo.log file is
     * created.
     * @return absolute path to the archive directory
     * @see #redoLogRolloverFileSizeKB()
     */
    public static synchronized String redoLogArchiveDir() {
        return theInstance.mRedoLogArchiveDir;
    }

    private long mRedoLogRolloverFileSizeKB;
    private static final long D_REDOLOG_ROLLOVER_FILESIZE_KB = 102400;
    /**
     * Returns the redolog rollover threshold filesize.
     * The current redolog file is rolled over if it reaches or exceeds
     * this size and file is old enough.
     * @return threshold filesize in kilobytes
     */
    public static synchronized long redoLogRolloverFileSizeKB() {
        return theInstance.mRedoLogRolloverFileSizeKB;
    }

    private long mRedoLogRolloverHardMaxFileSizeKB;
    private static final long D_REDOLOG_ROLLOVER_HARDMAX_FILESIZE_KB = 1048576;
    /**
     * Returns the redolog rollover hard threshold filesize.
     * The current redolog file is rolled over if it reaches or exceeds
     * this size, regardless of file age.
     * @return threshold filesize in kilobytes
     */
    public static synchronized long redoLogRolloverHardMaxFileSizeKB() {
        return theInstance.mRedoLogRolloverHardMaxFileSizeKB;
    }

    private long mRedoLogRolloverMinFileAge;
    private static final long D_REDOLOG_ROLLOVER_MIN_FILE_AGE = 30;
    /**
     * Returns the redolog rollover minimum file age.
     * The current redolog file is rolled over if it is older than this
     * and reaches the size threshold.
     * @return age in minutes
     */
    public static synchronized long redoLogRolloverMinFileAge() {
        return theInstance.mRedoLogRolloverMinFileAge;
    }

    private boolean mRedoLogDeleteOnRollover;
    private static final boolean D_REDOLOG_DELETE_ON_ROLLOVER = true;
    /**
     * If true, redo log file is deleted and discarded upon rollover.
     * If false, redo log being rolled over is archived.
     * @return
     */
    public static synchronized boolean redoLogDeleteOnRollover() {
        return theInstance.mRedoLogDeleteOnRollover;
    }

    private long mRedoLogFsyncIntervalMS;
    private static final long D_REDOLOG_FSYNC_INTERVAL_MS = 10;
    /**
     * Returns the fsync interval for flush/fsync thread.  Writes to the log
     * are written securely to disk by forcing an fsync.  But fsyncs are very
     * slow, so instead of each logging thread calling fsync individually,
     * they wait for a dedicated thread to fsync the accumulated changes
     * periodically.  This configuration value controls the interval between
     * the fsyncs.
     *
     * With a longer interval, there will be fewer fsyncs compared to the
     * number of logging calls.  This can improve throughput under heavy
     * load but increases the latency on individual logging calls.
     *
     * @return interval in milliseconds; default is 10ms
     */
    public static synchronized long redoLogFsyncIntervalMS() {
        return theInstance.mRedoLogFsyncIntervalMS;
    }

    private long mRedoLogCrashRecoveryLookbackSec;
    private static final long D_REDOLOG_CRASH_RECOVERY_LOOKBACK_SEC = 10;
    /**
     * This parameter is also related to running mysql with innodb_flush_log_at_trx_commit=0.
     * When recovering from a crash, mysql may not have the committed changes from roughly the last second.
     * ZCS must re-execute enough past operations to bring mysql into consistent state.
     *
     * This parameter controls how long to look back.  Default is 10 seconds.  Crash recovery normally
     * re-executes only pending changes.  But with this parameter committed changes within the last 10
     * seconds are also re-executed.
     * @return
     */
    public static synchronized long redoLogCrashRecoveryLookbackSec() {
        return theInstance.mRedoLogCrashRecoveryLookbackSec;
    }
}


text:
<?php

use Concrete\Core\Attribute\Key\Category;

abstract class UserTestCase extends ConcreteDatabaseTestCase
{
    protected $fixtures = array();
    protected $tables = array(
        'UserGroups', 'Groups',
        'TreeTypes', 'TreeNodes', 'TreeNodePermissionAssignments',
        'PermissionKeyCategories', 'PermissionKeys', 'TreeNodeTypes', 'Trees',
        'TreeGroupNodes',
    ); // so brutal

    protected $metadatas = array(
        'Concrete\Core\Entity\User\User',
        'Concrete\Core\Entity\User\UserSignup',
        'Concrete\Core\Entity\Attribute\Category',
        'Concrete\Core\Entity\Attribute\Key\Key',
        'Concrete\Core\Entity\Attribute\Key\UserValue',
        'Concrete\Core\Entity\Attribute\Key\UserKey',
    );

    protected static $users = [];

    public static function setUpBeforeClass()
    {
        parent::setUpBeforeClass(); // TODO: Change the autogenerated stub
        Category::add('user');
    }

    public static function tearDownAfterClass()
    {
        parent::tearDownAfterClass();
        static::$users = [];
    }

    protected static function createUser($uName, $uEmail)
    {
        $key = "{$uName}.{$uEmail}";
        if (!isset(static::$users[$key])) {

            static::$users[$key] = \Concrete\Core\User\UserInfo::add(
                array('uName' => $uName, 'uEmail' => $uEmail)
            );
        }

        return static::$users[$key];
    }
}


text:
/* nauthread2.c

   This program tests sparse nauty running in multiple threads.
   It must be linked with nauty as configured with
   --enable-tls and will only run on systems which support
   thread-local storage.
*/

#include <pthread.h>
#include "nauty.h"
#include "nausparse.h"
/* MAXN=0 is defined by nauty.h, which implies dynamic allocation */

#define THREADS 1000    /* Total number of threads to run */
#define ATONCE 20       /* Number of threads to run at once */
#define GRAPHSIZE 500   /* Least graph size to use */

typedef struct
{
    int n;
    boolean writeautoms;
} params;   /* Used to pass parameters to the thread */

static void*
runit(void * threadarg)          /* Main routine for one thread */
{
    DYNALLSTAT(int,lab,lab_sz);
    DYNALLSTAT(int,ptn,ptn_sz);
    DYNALLSTAT(int,orbits,orbits_sz);
    DEFAULTOPTIONS_SPARSEGRAPH(options);
    statsblk stats;
    sparsegraph sg;   /* Declare sparse graph structure */

    int n,m,i;

    n = ((params*)threadarg)->n;
    options.writeautoms = ((params*)threadarg)->writeautoms;

 /* Initialise sparse graph structure. */

    SG_INIT(sg);

    m = SETWORDSNEEDED(n);
    nauty_check(WORDSIZE,m,n,NAUTYVERSIONID);

    DYNALLOC1(int,lab,lab_sz,n,"malloc");
    DYNALLOC1(int,ptn,ptn_sz,n,"malloc");
    DYNALLOC1(int,orbits,orbits_sz,n,"malloc");

 /* SG_ALLOC makes sure that the v,d,e fields of a sparse graph
    structure point to arrays that are large enough.  This only
    works if the structure has been initialised. */

    SG_ALLOC(sg,n,2*n,"malloc");

    sg.nv = n;              /* Number of vertices */
    sg.nde = 2*n;           /* Number of directed edges */

    for (i = 0; i < n; ++i)
    {
        sg.v[i] = 2*i;
        sg.d[i] = 2;
        sg.e[2*i] = (i+n-1)%n;      /* edge i->i-1 */
        sg.e[2*i+1] = (i+n+1)%n;    /* edge i->i+1 */
    }

    if (options.writeautoms)
        printf("Generators for Aut(C[%d]):\n",n);
    sparsenauty(&sg,lab,ptn,orbits,&options,&stats,NULL);

    if (options.writeautoms)
    {
        printf("Automorphism group size = ");
        writegroupsize(stdout,stats.grpsize1,stats.grpsize2);
        printf("\n");
    }
    if (stats.numorbits != 1 || stats.grpsize1 != 2*n)
        fprintf(stderr,">E group error\n");

 /* If we are using multiple threads, we need to free all the dynamic
    memory we have allocated.  We don't have to do this after each
    call to nauty, just once before the thread finishes. */

    SG_FREE(sg);
    DYNFREE(lab,lab_sz);
    DYNFREE(ptn,ptn_sz);
    DYNFREE(orbits,orbits_sz);
    nauty_freedyn();
    nautil_freedyn();
    nausparse_freedyn();  /* Use naugraph_freedyn() instead if
                            dense format is being used. */

    return NULL;
}

int
main(int argc, char *argv[])
{
    int n,ret;
    pthread_t thread[THREADS];
    params par[THREADS];
    int started,finished;

#if !HAVE_TLS
    fprintf(stderr,">E This program needs to be linked with a version\n");
    fprintf(stderr,"  of nauty successfully configured using --enable-tls.\n");
    exit(1);
#endif

    for (started = finished = 0; finished < THREADS; )
    {
	if (started == THREADS || started-finished == ATONCE)
	{
	    if ((ret = pthread_join(thread[finished],NULL)) != 0)
	    {
                fprintf(stderr,">E Thread joining failed, code=%d\n",ret);
                exit(1);
            }
	    ++finished;
	}
	else
	{
		/* We vary the graph size a bit as it tests the
                   thread independence better. */
	    par[started].n = GRAPHSIZE + (started % 17);
	    par[started].writeautoms = FALSE;

            if ((ret = pthread_create(&thread[started],NULL,
					runit,&par[started])) != 0)
            {
                fprintf(stderr,">E Thread creation failed, code=%d\n",ret);
                exit(1);
            }
	    ++started;
	}
    }

    exit(0);
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Coniothyrium delacroixii Sacc.

### Remarks
null


text:
using System;
using System.Text;

class SeriesOfLetters
{
    static void Main()
    {
        string theString = Console.ReadLine();
        string result = TrimString(theString);

        Console.WriteLine(result);
    }

    static string TrimString(string str)
    {
        StringBuilder result = new StringBuilder();

        for (int i = 0; i < str.Length; i++)
        {
            result.Append(str[i]);

            while ((i + 1) < str.Length && str[i] == str[i + 1])
            {
                i++;
            }
        }

        return result.ToString();
    }
}


text:
'use strict';

// Declare imports
const _ = require('lodash');
const AftershipError = require('./error/error');

// Global variable
const RetryLimit = 5;
const UnauthorizedError = 401;
const TooManyRequestError = 429;
const RetriableApiError = [500, 502, 503, 504];
const RetriableRequestError = ['ETIMEDOUT', 'ECONNRESET', 'ECONNREFUSED'];
const ErrorEnum = require('./error/error_enum');

// Handler class
class Handler {
	/**
	 * Function to get the payload and create the request
	 *
	 * @param aftership {Aftership} - the aftership object
	 * @param payload {object} - The payload object to create the request
	 * @param callback {function}
	 */
	static handlePayload(aftership, payload, callback) {
		aftership.request(payload.request_object, function (err, response, body) {
			if (err) {
				// If request return err
				if (RetriableRequestError.indexOf(err.code) !== -1) {
					// Retry if err is retriable
					Handler._retryRequestError(aftership, payload, err, callback);
				} else {
					// Return err if not retriable
					callback(err);
				}
			} else {
				if (_.isString(body)) {
					// Non json response, throw error
					let internal_error = {
						meta: _.cloneDeep(ErrorEnum.InternalError)
					};
					internal_error.meta.code = 500;
					internal_error.data = payload.request_object.body || {};
					Handler._retryApiError(aftership, payload, internal_error, callback);
				} else {
					// check http status code
					if (response.statusCode !== UnauthorizedError) {
						// Not UnauthorizedError
						// Set rate_limit
						aftership.rate_limit[payload.request_object.headers['aftership-api-key']] = {
							limit: Number(response.headers['x-ratelimit-limit']),
							remaining: Number(response.headers['x-ratelimit-remaining']),
							reset: Number(response.headers['x-ratelimit-reset'])
						};
					}

					if (response.statusCode === TooManyRequestError) {
						// Retry if err is TooManyRequestError
						Handler._retryTooManyRequestError(aftership, payload, body, callback);
					} else if (RetriableApiError.indexOf(response.statusCode) !== -1) {
						// Retry if err is RetriableApiError
						Handler._retryApiError(aftership, payload, body, callback);
					} else if (response.statusCode !== 200 && response.statusCode !== 201) {
						// Return err if it is not OK response
						callback(AftershipError.getApiError(body));
					} else {
						// Response OK
						if (payload.raw) {
							// If raw is true, response string
							callback(null, JSON.stringify(body));
						} else {
							// Else response Object
							callback(null, body);
						}
					}
				}
			}
		});
	}

	/**
	 * Function to retry request error
	 *
	 * @param aftership {aftership}
	 * @param payload {object} - The payload object to create the request
	 * @param err {error} - the error object request return
	 * @param callback {function}
	 */
	static _retryRequestError(aftership, payload, err, callback) {
		// If retry is true && retry_count < 5
		if (payload.retry && payload.retry_count < RetryLimit) {
			// Increase retry_count
			payload.retry_count++;
			// Retry after 1s
			setTimeout(function () {
				Handler.handlePayload(aftership, payload, callback);
			}, 1000);
		} else {
			// Return err
			callback(AftershipError.getRequestError(err, payload.request_object, payload.retry_count));
		}
	}

	/**
	 * Function to retry 429 too many request error
	 *
	 * @param aftership {aftership}
	 * @param payload {object} - The payload object to create the request
	 * @param body {object} - If it is an RetriableError, body is the response body, else is the request error object
	 * @param callback {function}
	 */
	static _retryTooManyRequestError(aftership, payload, body, callback) {
		// If aftership.rate is true
		if (aftership.rate) {
			let timeout = aftership.rate_limit[payload.request_object.headers['aftership-api-key']].reset - Math.ceil(Date.now() / 1000);
			timeout *= 1000;

			// Retry after 1s
			setTimeout(function () {
				Handler.handlePayload(aftership, payload, callback);
			}, timeout);
		} else {
			// Return err
			callback(AftershipError.getApiError(body, payload.retry_count));
		}
	}

	/**
	 * Function to retry API error (code >= 500)
	 *
	 * @param aftership {aftership}
	 * @param payload {object} - The payload object to create the request
	 * @param body {object} - If it is an RetriableError, body is the response body, else is the request error object
	 * @param callback {function}
	 */
	static _retryApiError(aftership, payload, body, callback) {
		// If retry is true && retry_count < 5
		if (payload.retry && payload.retry_count < RetryLimit) {
			// Increase retry_count
			payload.retry_count++;
			// Retry after 1s
			setTimeout(function () {
				Handler.handlePayload(aftership, payload, callback);
			}, 1000);
		} else {
			// Return err
			callback(AftershipError.getApiError(body, payload.retry_count));
		}
	}
}

module.exports = Handler;


text:
/**
 * @file OGV/client/views/model_meta.js
 *
 * Helpers and events for editing models.
 */

/**
 * Update information about model
 *
 * Each model has some information associated with it, it can be name
 * bio or a representative image. Whenever user uploads he gets an option
 * to edit this information.
 */

Template.modelMeta.events({
    'submit #uploader-form': function(e, t)
    {
	e.preventDefault();

	var modelMetaForm = $(e.currentTarget),
	    filename = modelMetaForm.find('#desc-filename').val().toLowerCase(),
	    description = modelMetaForm.find('#desc-about').val(),
	    thumbnail,
	    modelId = modelMetaForm.find('#model-id').val();

	file = $('#desc-model-thumb')

	var fsFile = new FS.File(e.target[2].files[0]);
	fsFile.gFile = modelId;

	ThumbFiles.insert(fsFile,function(err,thumbFile) {
	    if (err) {
		throwError(err.reason);
	    } else {
		throwNotification("Image has been Uploaded" );
		ModelFiles.update(modelId, {$set: {name: filename, about: description, thumbnail:thumbFile._id}}, function(error, res) {
		    if (error) {
			throwError(error.reason);
		    } else {
			throwNotification("Data about model has been saved");
		    }
		});

	    }
	});
    }
});


text:
<?php
/* vim: set expandtab sw=4 ts=4 sts=4: */
/**
 * tests for relation.lib.php
 *
 * @package PhpMyAdmin-test
 */

/*
 * Include to test.
 */
require_once 'libraries/Util.class.php';
require_once 'libraries/Theme.class.php';
require_once 'libraries/php-gettext/gettext.inc';
require_once 'libraries/database_interface.inc.php';
require_once 'libraries/Tracker.class.php';
require_once 'libraries/relation.lib.php';

/**
 * Tests for libraries/relation.lib.php
 *
 * @package PhpMyAdmin-test
 * @group medium
 */
class PMA_Relation_Test extends PHPUnit_Framework_TestCase
{
    /**
     * Sets up the fixture, for example, opens a network connection.
     * This method is called before a test is executed.
     *
     * @access protected
     * @return void
     */
    public function setUp()
    {
        $GLOBALS['server'] = 1;
        $GLOBALS['cfg']['Server']['user'] = 'root';
        $GLOBALS['cfg']['Server']['pmadb'] = 'phpmyadmin';
        $_SESSION['relation'][$GLOBALS['server']] = "PMA_relation";
        $_SESSION['PMA_Theme'] = new PMA_Theme();
        $_SESSION['relation'] = array();

        $GLOBALS['pmaThemePath'] = $_SESSION['PMA_Theme']->getPath();
        $GLOBALS['pmaThemeImage'] = 'theme/';
        $GLOBALS['cfg']['ServerDefault'] = 0;

        include_once 'libraries/relation.lib.php';
    }

    /**
     * Test for PMA_queryAsControlUser
     *
     * @return void
     */
    public function testPMAQueryAsControlUser()
    {
        $dbi = $this->getMockBuilder('PMA_DatabaseInterface')
            ->disableOriginalConstructor()
            ->getMock();

        $dbi->expects($this->once())
            ->method('query')
            ->will($this->returnValue('executeResult1'));

        $dbi->expects($this->once())
            ->method('tryQuery')
            ->will($this->returnValue('executeResult2'));

        $GLOBALS['dbi'] = $dbi;

        $sql = "insert into PMA_bookmark A,B values(1, 2)";
        $this->assertEquals(
            'executeResult1',
            PMA_queryAsControlUser($sql)
        );
        $this->assertEquals(
            'executeResult2',
            PMA_queryAsControlUser($sql, false)
        );
    }

    /**
     * Test for PMA_getRelationsParam & PMA_getRelationsParamDiagnostic
     *
     * @return void
     */
    public function testPMAGetRelationsParam()
    {
        $relationsPara = PMA_getRelationsParam();
        $this->assertEquals(
            false,
            $relationsPara['relwork']
        );
        $this->assertEquals(
            false,
            $relationsPara['bookmarkwork']
        );
        $this->assertEquals(
            'root',
            $relationsPara['user']
        );
        $this->assertEquals(
            'phpmyadmin',
            $relationsPara['db']
        );

        $retval = PMA_getRelationsParamDiagnostic($relationsPara);
        //check $cfg['Servers'][$i]['pmadb']
        $this->assertContains(
            "\$cfg['Servers'][\$i]['pmadb']",
            $retval
        );
        $this->assertContains(
            'OK',
            $retval
        );

        //$cfg['Servers'][$i]['relation']
        $result = "\$cfg['Servers'][\$i]['pmadb']  ... 	"
            . "OK";
        $this->assertContains(
            $result,
            $retval
        );
        // $cfg['Servers'][$i]['relation']
        $result = "\$cfg['Servers'][\$i]['relation']  ... 	"
            . "not OK";
        $this->assertContains(
            $result,
            $retval
        );
        // General relation features
        $result = 'General relation features: Disabled';
        $this->assertContains(
            $result,
            $retval
        );
        // $cfg['Servers'][$i]['table_info']
        $result = "\$cfg['Servers'][\$i]['table_info']  ... 	"
            . ""
            . "not OK";
        $this->assertContains(
            $result,
            $retval
        );
        // Display Features:
        $result = 'Display Features: Disabled';
        $this->assertContains(
            $result,
            $retval
        );

        //$GLOBALS['cfg']['Server']['pmadb']==false
        $value = $GLOBALS['cfg']['Server']['pmadb'];
        $GLOBALS['cfg']['Server']['pmadb'] = false;
        $retval = PMA_getRelationsParamDiagnostic($relationsPara);

        $result = __('General relation features');
        $this->assertContains(
            $result,
            $retval
        );
        $result = 'Configuration of pmadb… ';
        $this->assertContains(
            $result,
            $retval
        );
        $result = "not OK";
        $this->assertContains(
            $result,
            $retval
        );

        $GLOBALS['cfg']['Server']['pmadb'] = $value;

    }

    /**
     * Test for PMA_getDisplayField
     *
     * @return void
     */
    public function testPMAGetDisplayField()
    {
        $db = 'information_schema';
        $table = 'CHARACTER_SETS';
        $this->assertEquals(
            'DESCRIPTION',
            PMA_getDisplayField($db, $table)
        );

        $db = 'information_schema';
        $table = 'TABLES';
        $this->assertEquals(
            'TABLE_COMMENT',
            PMA_getDisplayField($db, $table)
        );

        $db = 'information_schema';
        $table = 'PMA';
        $this->assertEquals(
            false,
            PMA_getDisplayField($db, $table)
        );

    }

    /**
     * Test for PMA_getComments
     *
     * @return void
     */
    public function testPMAGetComments()
    {
        $GLOBALS['cfg']['ServerDefault'] = 0;
        $_SESSION['relation'] = array();

        $dbi = $this->getMockBuilder('PMA_DatabaseInterface')
            ->disableOriginalConstructor()
            ->getMock();

        $getColumnsResult = array(
                array(
                        'Field' => 'field1',
                        'Type' => 'int(11)',
                        'Comment' => 'Comment1'
                ),
                array(
                        'Field' => 'field2',
                        'Type' => 'text',
                        'Comment' => 'Comment1'
                )
        );
        $dbi->expects($this->any())->method('getColumns')
            ->will($this->returnValue($getColumnsResult));

        $GLOBALS['dbi'] = $dbi;

        $db = 'information_schema';
        $this->assertEquals(
            array(''),
            PMA_getComments($db)
        );

        $db = 'information_schema';
        $table = 'TABLES';
        $this->assertEquals(
            array(
                'field1' => 'Comment1',
                'field2' => 'Comment1'
            ),
            PMA_getComments($db, $table)
        );
    }

    /**
     * Test for PMA_tryUpgradeTransformations
     *
     * @return void
     */
    public function testPMATryUpgradeTransformations()
    {
        $dbi = $this->getMockBuilder('PMA_DatabaseInterface')
            ->disableOriginalConstructor()
            ->getMock();
        $dbi->expects($this->any())
            ->method('tryQuery')
            ->will($this->returnValue(true));
        $dbi->expects($this->any())
            ->method('numRows')
            ->will($this->returnValue(0));
        $dbi->expects($this->any())
            ->method('getError')
            ->will($this->onConsecutiveCalls(true, false));
        $GLOBALS['dbi'] = $dbi;

        $GLOBALS['cfg']['Server']['pmadb'] = 'pmadb';
        $GLOBALS['cfg']['Server']['column_info'] = 'column_info';

        // Case 1
        $actual = PMA_tryUpgradeTransformations();
        $this->assertEquals(
            false,
            $actual
        );

        // Case 2
        $actual = PMA_tryUpgradeTransformations();
        $this->assertEquals(
            true,
            $actual
        );
    }

    /**
     * Test for PMA_searchColumnInForeigners
     *
     * @return void
     */
    public function testPMASearchColumnInForeigners()
    {
        $foreigners = array(
            'value' => array(
                  'master_field' => 'value',
                  'foreign_db' => 'GSoC14',
                  'foreign_table' => 'test',
                  'foreign_field' => 'value'
            ),
            'foreign_keys_data' => array(
                0 => array(
                    'constraint' => 'ad',
                    'index_list' => array('id', 'value'),
                    'ref_db_name' => 'GSoC14',
                    'ref_table_name' => 'table_1',
                    'ref_index_list' => array('id', 'value'),
                    'on_delete' => 'CASCADE',
                    'on_update' => 'CASCADE'
                )
            )
        );

        $foreigner = PMA_searchColumnInForeigners($foreigners, 'id');
        $expected = array();
        $expected['foreign_field'] = 'id';
        $expected['foreign_db'] = 'GSoC14';
        $expected['foreign_table'] = 'table_1';
        $expected['constraint'] = 'ad';

        $this->assertEquals(
            $expected,
            $foreigner
        );
    }
}


text:
<?php

namespace Lexik\Bundle\FormFilterBundle\Tests;

use Doctrine\Bundle\DoctrineBundle\DependencyInjection\DoctrineExtension;
use Doctrine\Bundle\DoctrineBundle\DoctrineBundle;
use Doctrine\Common\Annotations\AnnotationReader;
use Doctrine\Common\Cache\Psr6\DoctrineProvider;
use Doctrine\ODM\MongoDB\Configuration;
use Doctrine\ODM\MongoDB\DocumentManager;
use Doctrine\ODM\MongoDB\Mapping\Driver\AnnotationDriver;
use Doctrine\ORM\EntityManager;
use Lexik\Bundle\FormFilterBundle\DependencyInjection\Compiler\FormDataExtractorPass;
use Lexik\Bundle\FormFilterBundle\DependencyInjection\LexikFormFilterExtension;
use Lexik\Bundle\FormFilterBundle\Filter\Form\FilterExtension;
use Lexik\Bundle\FormFilterBundle\LexikFormFilterBundle;
use Symfony\Bundle\FrameworkBundle\DependencyInjection\FrameworkExtension;
use Symfony\Bundle\FrameworkBundle\FrameworkBundle;
use Symfony\Component\Cache\Adapter\ArrayAdapter;
use Symfony\Component\DependencyInjection\Compiler\ResolveChildDefinitionsPass;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag;
use Symfony\Component\EventDispatcher\DependencyInjection\RegisterListenersPass;
use Symfony\Component\Form\Extension\Core\CoreExtension;
use Symfony\Component\Form\FormFactory;
use Symfony\Component\Form\FormRegistry;
use Symfony\Component\Form\ResolvedFormTypeFactory;

abstract class TestCase extends \PHPUnit\Framework\TestCase
{
    /**
     * @var FormFactory
     */
    protected $formFactory;

    public function setUp(): void
    {
        $this->formFactory = $this->getFormFactory();
    }

    /**
     * Create a form factory instance.
     *
     * @return FormFactory
     */
    public function getFormFactory()
    {
        $resolvedFormTypeFactory = new ResolvedFormTypeFactory();

        $registery = new FormRegistry([new CoreExtension(), new FilterExtension()], $resolvedFormTypeFactory);

        $formFactory = new FormFactory($registery, $resolvedFormTypeFactory);

        return $formFactory;
    }

    /**
     * EntityManager object together with annotation mapping driver and
     * pdo_sqlite database in memory
     *
     * @return EntityManager
     */
    public function getSqliteEntityManager()
    {
        $arrayAdapter = new ArrayAdapter();
        $cache = DoctrineProvider::wrap(new ArrayAdapter());

        $reader = new AnnotationReader(new \Doctrine\Common\Annotations\DocParser());

        $mappingDriver = new \Doctrine\ORM\Mapping\Driver\AnnotationDriver($reader, array(
            __DIR__.'/Fixtures/Entity',
        ));

        $config = \Doctrine\ORM\Tools\Setup::createAnnotationMetadataConfiguration(array());

        $config->setMetadataDriverImpl($mappingDriver);
        $config->setMetadataCache($arrayAdapter);
        $config->setQueryCacheImpl($cache);
        $config->setProxyDir(sys_get_temp_dir());
        $config->setProxyNamespace('Proxy');
        $config->setAutoGenerateProxyClasses(true);
        $config->setClassMetadataFactoryName('Doctrine\ORM\Mapping\ClassMetadataFactory');
        $config->setDefaultRepositoryClassName('Doctrine\ORM\EntityRepository');

        $conn = array(
            'driver' => 'pdo_sqlite',
            'memory' => true,
        );

        $em = EntityManager::create($conn, $config);

        return $em;
    }

    public function getMongodbDocumentManager(): DocumentManager
    {
        $arrayAdapter = new ArrayAdapter();

        $config = new Configuration();
        $config->setMetadataCache($arrayAdapter);
        $config->setMetadataDriverImpl(new AnnotationDriver(new AnnotationReader(), [__DIR__.'/Fixtures/Document/']));

        $config->setAutoGenerateProxyClasses(Configuration::AUTOGENERATE_FILE_NOT_EXISTS);
        $config->setProxyDir(sys_get_temp_dir());
        $config->setHydratorDir(sys_get_temp_dir());

        $config->setProxyNamespace('Proxy');
        $config->setDefaultDB('lexik_form_filter_bundle_test');
        $config->setHydratorNamespace('Doctrine\ODM\MongoDB\Hydrator');
        $config->setAutoGenerateHydratorClasses(true);
        $config->setDefaultCommitOptions(array());

        return DocumentManager::create(null, $config);
    }

    protected function initQueryBuilderUpdater()
    {
        $container = $this->createContainerBuilder([
            'framework' => [
                'secret' => 'test',
                'http_method_override' => true,
            ],
            'lexik_form_filter' => [
                'listeners' => [
                    'doctrine_orm' => true, 'doctrine_dbal' => true, 'doctrine_mongodb' => true,
                ]
            ],
        ]);

        return $container->get('lexik_form_filter.query_builder_updater');
    }

    private static function createContainerBuilder(array $configs = [])
    {
        $container = new ContainerBuilder(new ParameterBag([
            'kernel.bundles'          => [
                'FrameworkBundle' => FrameworkBundle::class,
                'DoctrineBundle' => DoctrineBundle::class,
                'LexikFormFilterBundle' => LexikFormFilterBundle::class
            ],
            'kernel.bundles_metadata' => [],
            'kernel.cache_dir'        => __DIR__,
            'kernel.debug'            => false,
            'kernel.environment'      => 'test',
            'kernel.name'             => 'kernel',
            'kernel.root_dir'         => __DIR__,
            'kernel.project_dir'      => __DIR__,
            'kernel.container_class'  => 'AutowiringTestContainer',
            'kernel.charset'          => 'utf8',
            'env(base64:default::SYMFONY_DECRYPTION_SECRET)' => 'dummy',
            'debug.file_link_format' => null,
        ]));

        $container->registerExtension(new FrameworkExtension());
        $container->registerExtension(new LexikFormFilterExtension());

        $extension = new DoctrineExtension();
        $container->registerExtension($extension);
        $extension->load([[
            'dbal' => [
                'connections' => [
                    'default' => [
                        'driver' => 'pdo_mysql',
                        'charset' => 'UTF8',
                    ],
                ],
                'default_connection' => 'default',
            ], 'orm' => [
                'default_entity_manager' => 'default',
                'resolve_target_entities' => ['Symfony\Component\Security\Core\User\UserInterface' => 'stdClass'],
            ],
        ],
        ], $container);

        $container->setParameter('lexik_form_filter.where_method', null);

        foreach ($configs as $extension => $config) {
            $container->loadFromExtension($extension, $config);
        }

        $container->getCompilerPassConfig()->setOptimizationPasses([new ResolveChildDefinitionsPass()]);
        $container->getCompilerPassConfig()->setRemovingPasses([]);
        $container->addCompilerPass(new FormDataExtractorPass());
        $container->addCompilerPass(new RegisterListenersPass());

        $container->compile();

        return $container;
    }
}


text:
package com.mokiat.data.front.error;

/**
 * This exception is used to indicate that a WaveFront
 * resource is too large to load.
 *
 * @author Momchil Atanasov
 *
 */
public class WFSizeException extends WFException {

    private static final long serialVersionUID = 1L;

    public WFSizeException() {
        super();
    }

    public WFSizeException(String message) {
        super(message);
    }

    public WFSizeException(Throwable ex) {
        super(ex);
    }

    public WFSizeException(String message, Throwable ex) {
        super(message, ex);
    }
}


text:
import type { $Request, $Response } from "express";

const express = require("express");

const Log = require("log"),
  log = new Log("info");

const path = require("path");

const router = express.Router();

const suffixRegex = /(?:\.([^.]+))?$/;

const renderSuffixes = new Set(["ipynb", "html", "json", "md", "rmd"]);
const renderAccepts = new Set(["text/html", "application/xhtml+xml"]);

router.get("*", (req: $Request, res: $Response) => {
  const suffix = (suffixRegex.exec(req.path)[1] || "").toLowerCase();
  const accepts = (req.headers.accept || "").split(",");

  if (
    // If one of our suffixes is a renderable item
    renderSuffixes.has(suffix) ||
    // If the file is requested as `text/html` first and foremost, we'll also
    // render our file viewer
    renderAccepts.has(accepts[0]) ||
    renderAccepts.has(accepts[1])
  ) {
    res.sendFile(path.resolve(__dirname, "..", "..", "build", "index.html"));
    return;
  }

  // TODO: Include the config.basePath
  const newPath = req.path.replace(/^\//, "/files/");
  res.redirect(newPath);
  return;
});

module.exports = router;


text:
require('dotenv').config();

// Require keystone
var keystone = require('keystone');

// Initialise Keystone with your project's configuration.
// See http://keystonejs.com/guide/config for available options
// and documentation.

keystone.init({
	'name': "Jason Chiu - Website",
	'brand': 'Vartyr',
	'less': 'public',
	'static': 'public',
	'favicon': 'public/favicon.ico',
	'views': 'templates/views',
	'view engine': 'jade',
	'emails': 'templates/emails',
	'cloudinary config': 'cloudinary://api_key:api_secret@cloud_name',
	'cookie secret': '(your secret here)',
	'static': 'public',
	'auto update': true,
	'session': true,
	'auth': true,
	'user model': 'Adventurer',
});

// Load your project's Models
keystone.import('models');

// Setup common locals for your templates. The following are required for the
// bundled templates and layouts. Any runtime locals (that should be set uniquely
// for each request) should be added to ./routes/middleware.js
keystone.set('locals', {
	_: require('lodash'),
	env: keystone.get('env'),
	utils: keystone.utils,
	editable: keystone.content.editable,
	moment: require ('moment')
});

// Load your project's Routes
keystone.set('routes', require('./routes'));

// Setup common locals for your emails. The following are required by Keystone's
// default email templates, you may remove them if you're using your own.
keystone.set('email locals', {
	logo_src: '/images/logo-email.gif',
	logo_width: 194,
	logo_height: 76,
	theme: {
		email_bg: '#f9f9f9',
		link_color: '#2697de',
		buttons: {
			color: '#fff',
			background_color: '#2697de',
			border_color: '#1a7cb7',
		},
	},
});

// Load your project's email test routes
keystone.set('email tests', require('./routes/emails'));

// Configure the navigation bar in Keystone's Admin UI
keystone.set('nav', {
	posts: ['posts', 'post-categories'],
	galleries: 'galleries',
	enquiries: 'enquiries',
	adventurers: 'adventurers',
});

// Start Keystone to connect to your database and initialise the web server

keystone.start();


text:
<?php
class Example extends PluginBase {

    protected $storage = 'DbStorage';
    static protected $description = 'Example plugin';

    protected $settings = array(
        'test' => array(
            'type' => 'string',
            'label' => 'Message'
        ),
        'messages' => array(
            'type' => 'list',
            'label' => 'messages',
            'items' => array(
                'number' => array(
                    'type' => 'int',
                    'label' => 'Index'
                ),
                'message' => array(
                    'type' => 'string',
                    'label' => 'Message'
                ),

            )
        )
    );

    public function __construct(PluginManager $manager, $id) {
        parent::__construct($manager, $id);

        /**
         * Here you should handle subscribing to the events your plugin will handle
         */
        $this->subscribe('afterPluginLoad', 'helloWorld');
        $this->subscribe('afterAdminMenuLoaded');
        $this->subscribe('beforeSurveySettings');
        $this->subscribe('newSurveySettings');
    }

    /*
     * Below are the actual methods that handle events
     */

    public function afterAdminMenuLoaded()
    {
        $event = $this->event;
        $menu = $event->get('menu', array());
        $menu['left'][]=array(
                'href' => "http://docs.limesurvey.org",
                'alt' => gT('LimeSurvey online manual'),
                'image' => 'showhelp.png'
            );

        $event->set('menu', $menu);
    }

    public function helloWorld()
    {
        $event = $this->event;
        $count = (int) $this->get('count');
        if ($count === false) $count = 0;
        $count++;
        $this->pluginManager->getAPI()->setFlash($this->get('message') . $count);
        $this->set('count', $count);
    }

    /**
     * This event is fired by the administration panel to gather extra settings
     * available for a survey.
     * The plugin should return setting meta data.
     * @param PluginEvent $event
     */
    public function beforeSurveySettings()
    {
        $event = $this->event;
        $event->set("surveysettings.{$this->id}", array(
            'name' => get_class($this),
            'settings' => array(
                'message' => array(
                    'type' => 'string',
                    'label' => 'Message to show to users:',
                    'current' => $this->get('message', 'Survey', $event->get('survey'))
                )
            )
         ));
    }

    public function newSurveySettings()
    {
        $event = $this->event;
        foreach ($event->get('settings') as $name => $value)
        {

            $this->set($name, $value, 'Survey', $event->get('survey'));
        }
    }

}


text:
package org.apache.sis.util;

/**
 * Thrown when an object cannot be {@linkplain ObjectConverter#apply(Object) converted}
 * from the source type to the target type.
 *
 *
Some converters may attempt many strategies before to give up, resulting in more than
 * one exception being caught. In such case, all the failed attempts will be reported as
 * {@linkplain #getSuppressed() suppressed exceptions} and the {@linkplain #getCause() cause}
 * will be an arbitrary item of this list.

 *
 * @author  Martin Desruisseaux (Geomatys)
 * @version 0.3
 * @since   0.3
 * @module
 */
public class UnconvertibleObjectException extends IllegalArgumentException {
    /**
     * For cross-version compatibility.
     */
    private static final long serialVersionUID = 4436966248421454692L;

    /**
     * Constructs a new exception with no message.
     */
    public UnconvertibleObjectException() {
        super();
    }

    /**
     * Constructs a new exception with the specified detail message.
     *
     * @param message  the detail message, or {@code null} if none.
     */
    public UnconvertibleObjectException(final String message) {
        super(message);
    }

    /**
     * Constructs a new exception with the specified detail message and cause.
     *
     * @param message  the detail message, or {@code null} if none.
     * @param cause    the cause, or {@code null} if none.
     */
    public UnconvertibleObjectException(final String message, final Throwable cause) {
        super(message, cause);
    }

    /**
     * Constructs a new exception with the specified cause.
     *
     * @param cause  the cause, or {@code null} if none.
     */
    public UnconvertibleObjectException(final Throwable cause) {
        super(cause);
    }
}


text:
layout: post
title: Omnipotent Düşünme
date: 2013-02-15 22:28
author: admin
comments: true
tags: [Eğitim Bilimleri, Eğitim Bilimleri, kpss, kpss eğitim bilimleri, Kpss Sözlük, o]
---
Ergenlik dönemindeki bireyin, her işin üstesinden gelebilecek güçte olduğunu düşünmesi. Ergen, her şeyi halledebileceği kanısındadır. Ona göre hayat aslında büyüklerin anlattığı kadar zor değildir."Bana bişey olmaz" düşüncesi hâkimdir. Ergenler hayal âlemine dalıp gelecekte gerçekleştirebilecekleri şeyleri düşünürler. Düşünmekle de kalmayıp bu hayalleri gerçekleştirebilecek enerjiyle dolu olduklarına, hayatın aslında büyüklerin abarttığında daha kolay olduğuna inanırlar.


text:
This plugin writes to [CrateDB](https://crate.io/) via its [PostgreSQL protocol](https://crate.io/docs/crate/reference/protocols/postgres.html).

## Table Schema

The plugin requires a table with the following schema.

```sql
CREATE TABLE my_metrics (
  "hash_id" LONG INDEX OFF,
  "timestamp" TIMESTAMP,
  "name" STRING,
  "tags" OBJECT(DYNAMIC),
  "fields" OBJECT(DYNAMIC),
  PRIMARY KEY ("timestamp", "hash_id","day")
) PARTITIONED BY("day");
```

The plugin can create this table for you automatically via the `table_create`
config option, see below.

## Configuration

```toml
# Configuration for CrateDB to send metrics to.
[[outputs.cratedb]]
  # A github.com/jackc/pgx/v4 connection string.
  # See https://pkg.go.dev/github.com/jackc/pgx/v4#ParseConfig
  url = "postgres://user:password@localhost/schema?sslmode=disable"
  # Timeout for all CrateDB queries.
  timeout = "5s"
  # Name of the table to store metrics in.
  table = "metrics"
  # If true, and the metrics table does not exist, create it automatically.
  table_create = true
  # The character(s) to replace any '.' in an object key with
  key_separator = "_"
```


text:
(function() {
  function foo(x) {
    return Math.abs(Math.trunc(x * -2));
  }

  %PrepareFunctionForOptimization(foo);
  assertEquals(2, foo(1));
  assertEquals(4, foo(2));
  %OptimizeFunctionOnNextCall(foo);
  assertEquals(2, foo(1));
  assertEquals(4, foo(2));
  assertOptimized(foo);
  // Now `foo` should stay optimized even if `x * -2` would produce `-0`.
  assertEquals(0, foo(0));
  assertOptimized(foo);
})();


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>(A)nother (C)hallenge in (L)ife for Female Athletes - Stories</title>

    <link href="vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">

    <link href="css/clean-blog.css" rel="stylesheet">

    <link href="vendor/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
    <link href='https://fonts.googleapis.com/css?family=Lora:400,700,400italic,700italic' rel='stylesheet' type='text/css'>
    <link href='https://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/css'>

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                    Toggle navigation
                    Menu
                </button>
                (A)nother (C)hallenge in (L)ife for Female Athletes

                        Home

                        The Injury

                        The Recovery

                        Stories

                        About Me

                        Contact Me

Stories

Female Athletes that have torn their ACL

Candace Parker

On July 11, 2003, Parker tore her ACL in her left knee in a summer league game.  On December 29, Parker returned to action for Naperville Central and a
                    few months later, led her team to its second consecutive state title.

Want to know more?

                    Click here for more information about Parker's Early Life.

                    Click here for more information on the hardest part of Parker's career.

Alex Morgan

Ten years ago, American soccer player Alex Morgan suffered a torn anterior cruciate ligament (ACL). After surgery, she resumed a successful career. In the 2012 London Olympics, she scored the
                    winning goal against Canada to send the U.S. to the gold-medal game. There, she faced off with Japan and the U.S. won.

Want to know more?

                    Click here for an interview with Morgan where she talks about
                    recovering from a possible career ending injury.

                    Click here for a story about Morgan working with young soccer players on stretches
                    and how to prevent ACL injuries.

Caroline Doty

Her contribution to Connecticut in 2011 was limited to suggesting plays from the sidelines. Doty first tore her ACL while playing soccer as a high school senior
                    in the fall of 2007. On January 27, 2009, during her freshman season against Syracuse, she drove for a layup and landed awkwardly. In August of 2010, while practicing
                    one-on-one moves, she drove for a left-handed layup and felt her left knee shift when she landed. The ACL was 80 percent torn and third operation was required.

Want to know more?

                    Click here for more information about her operations and recovery.

                    Click here for more background on Caroline.

Copyright © (A)nother (C)hallenge in (L)ife for Female Athletes 2017


text:
SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";

CREATE TABLE IF NOT EXISTS `materials` (
  `material_id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `datestamp` char(10) NOT NULL,
  `publications` varchar(1500) NOT NULL,
  `plate_1` int(5) unsigned NOT NULL,
  `plate_2` int(5) unsigned NOT NULL,
  `plate_3` int(5) unsigned NOT NULL,
  `paper_1` int(5) unsigned NOT NULL,
  `paper_1s` int(5) unsigned NOT NULL,
  `paper_2` int(5) unsigned NOT NULL,
  `paper_2s` int(5) unsigned NOT NULL,
  `paper_3` int(5) unsigned NOT NULL,
  `paper_3s` int(5) unsigned NOT NULL,
  `paper_4` int(5) unsigned NOT NULL,
  `paper_4s` int(5) unsigned NOT NULL,
  `color_c` decimal(5,2) unsigned NOT NULL,
  `color_m` decimal(5,2) unsigned NOT NULL,
  `color_y` decimal(5,2) unsigned NOT NULL,
  `color_k` decimal(5,2) unsigned NOT NULL,
  PRIMARY KEY (`material_id`),
  UNIQUE KEY `timestamp` (`datestamp`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=14 ;

CREATE TABLE IF NOT EXISTS `publications` (
  `publication_id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(30) NOT NULL,
  `frequency` decimal(5,2) unsigned NOT NULL,
  `num_pages` int(3) unsigned NOT NULL,
  `plate_1` int(3) unsigned NOT NULL,
  `plate_2` int(3) unsigned NOT NULL,
  `plate_3` int(3) unsigned NOT NULL,
  `paper_1` int(5) unsigned NOT NULL,
  `paper_1s` int(5) unsigned NOT NULL,
  `paper_2` int(5) unsigned NOT NULL,
  `paper_2s` int(5) unsigned NOT NULL,
  `paper_3` int(5) unsigned NOT NULL,
  `paper_3s` int(5) unsigned NOT NULL,
  `paper_4` int(5) unsigned NOT NULL,
  `paper_4s` int(5) unsigned NOT NULL,
  `color_c` decimal(5,2) NOT NULL,
  `color_m` decimal(5,2) NOT NULL,
  `color_y` decimal(5,2) NOT NULL,
  `color_k` decimal(5,2) NOT NULL,
  PRIMARY KEY (`publication_id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=50 ;


text:
#include <map>
using namespace std;

#ifndef TYPENAME
#define TYPENAME typename
// gcc 3.x accepts typename, gcc 2.95.3 does not
#endif

template <typename T>
struct Foo
{
        typedef T TT;
        typedef Foo<TT> ThisType;
        typedef map<ThisType::TT,ThisType::TT> map_type;

        /**
           gcc 2.95.3 will do something like the following:
           stl_check.cpp: In method `void Foo<T>::check_for_gcc2_9_failure(const map<T,T,less<_Key>,allocator<_Tp1> > &)':
           stl_check.cpp:15: no class template named `map' in `struct Foo<T>'
           stl_check.cpp:16: no class template named `map' in `struct Foo<T>'

           gcc 3.x (3.3pre, at least) swallows it nicely.

           The problem here is the 'typename' part: without that gcc
           2.95.3 compiles it fine. gcc 3, however, warns that
           "implicite typenames are deprecated", and this kills my
           builds (i always use -Werror :/).
        */
        void check_for_gcc2_9_failure()
        {
                ThisType::map_type map;
                TYPENAME ThisType::map_type::const_iterator it = map.begin();
                TYPENAME ThisType::map_type::const_iterator et = map.end();
                for( ; it != et; ++it ) {}
        }
};

int main()
{
        typedef Foo<int> Fii;
        Fii fii;
        fii.check_for_gcc2_9_failure();
        return 0;
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using Ical.Net.Collections.Interfaces;
using Ical.Net.Collections.Proxies;

namespace Ical.Net.Collections
{
    public class GroupedValueList<TGroup, TInterface, TItem, TValueType> :
        GroupedList<TGroup, TInterface>
        where TInterface : class, IGroupedObject<TGroup>, IValueObject<TValueType>
        where TItem : new()
    {
        public virtual void Set(TGroup group, TValueType value)
        {
            Set(group, new[] { value });
        }

        public virtual void Set(TGroup group, IEnumerable<TValueType> values)
        {
            if (ContainsKey(group))
            {
                AllOf(group)?.FirstOrDefault()?.SetValue(values);
                return;
            }

            // No matching item was found, add a new item to the list
            var obj = Activator.CreateInstance(typeof(TItem)) as TInterface;
            obj.Group = group;
            Add(obj);
            obj.SetValue(values);
        }

        public virtual TType Get<TType>(TGroup group)
        {
            var firstItem = AllOf(group).FirstOrDefault();
            if (firstItem?.Values != null)
            {
                return firstItem
                    .Values
                    .OfType<TType>()
                    .FirstOrDefault();
            }
            return default(TType);
        }

        public virtual IList<TType> GetMany<TType>(TGroup group) => new GroupedValueListProxy<TGroup, TInterface, TItem, TValueType, TType>(this, group);
    }
}


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

class TestConfigFile < Test::Unit::TestCase
  include Fixtures

  def setup
    clean_tmp_dir
    ENV['DROPBOX_HOME'] = TMP_DIR
    config_dir = File.join(TMP_DIR, '.dropsite')
    Dir.mkdir(config_dir) if !File.exist?(config_dir)
  end

  def teardown; clean_tmp_dir end

  def test_read_exclude
    write_config_file <<-YAML
exclude: [ignore_this, and_also_this]
YAML

    cf = ConfigFile.new
    cf.read

    es = cf.exclude
    assert_equal 2, es.size
    assert es.include?('ignore_this')
    assert es.include?('and_also_this')
  end

  private

  def write_config_file(content)
    File.open(File.join(TMP_DIR, '.dropsite', 'config.yml'), 'w') {|f| f.puts content}
  end
end


text:
using System;
using System.Collections.Generic;
using System.Web;
using System.Text;
using System.Reflection;

namespace PLSQLGatewayModule
{
    ///
    /// Generates error pages in the gateway
    ///
    public static class GatewayError
    {

        private const string PRODUCT_URL = "https://github.com/mortenbra/thoth-gateway";

        ///
        /// returns the version string for the assembly
        ///
        /// <returns></returns>
        private static string GetGatewayAssemblyVersion()
        {
            Assembly assembly = Assembly.GetAssembly(typeof(PLSQLHttpModule));
            return assembly.GetName().Version.ToString();
        }

        ///
        /// returns a signature for the page footer
        ///
        /// <returns></returns>
        private static string GetSignature()
        {
            return string.Format("

Thoth PL/SQL Gateway Module version {1}
", PRODUCT_URL, GetGatewayAssemblyVersion());
        }

        ///
        /// Given a request, returns a HTML-formatted error page with the details of the request and the error
        ///
        public static string GetErrorDebugPage(GatewayRequest req, string errorMessage)
        {
            StringBuilder page = new StringBuilder();

            string htmlErrorMessage = errorMessage.Replace("\n", "
");

            page.Append("");
            page.AppendFormat("
Thoth Gateway Error

{2}: Module = {0}, Database Access Descriptor (DAD) = {1}
", req.ModuleName, req.DadName, DateTime.Now.ToString());

            page.AppendFormat("
The gateway encountered the following error while executing the request:

{0}
", htmlErrorMessage);

            page.AppendFormat("
Request

{0}
", req.OriginalRequest);

            page.AppendFormat("
SQL

{0}
", req.OwaProc.SQLStatement);

            page.AppendFormat("
Parameters ({0})

", req.RequestParameters.Count);
            foreach (NameValuePair nvp in req.RequestParameters)
            {
                page.AppendFormat("
{0} = {1}
", nvp.Name, nvp.DebugValue);
            }
            page.AppendFormat("
");

            page.AppendFormat("
Environment ({0})

", req.CGIParameters.Count);
            foreach (NameValuePair nvp in req.CGIParameters)
            {
                page.AppendFormat("
{0} = {1}
", nvp.Name, nvp.DebugValue);
            }
            page.AppendFormat("
");

            page.AppendFormat("
DAD Configuration ({0})

", req.DadName);
            page.AppendFormat("
DatabaseConnectString = {0}
", req.DadConfig.DatabaseConnectString);
            page.AppendFormat("
DatabaseUserName = {0}
", req.DadConfig.DatabaseUserName);
            page.AppendFormat("
NLSLanguage = {0}_{1}.{2}
", req.DadConfig.NLSLanguage, req.DadConfig.NLSTerritory, req.DadConfig.NLSCharset);
            page.AppendFormat("
InvocationProtocol = {0}
", req.DadConfig.InvocationProtocol);
            page.AppendFormat("
DocumentTableName = {0}
", req.DadConfig.DocumentTableName);
            page.AppendFormat("
DocumentFilePath = {0}
", req.DadConfig.DocumentFilePath);
            page.AppendFormat("
DocumentXdbPath = {0}
", req.DadConfig.DocumentXdbPath);
            page.AppendFormat("
Document Path = {0}
", req.DadConfig.DocumentPath);
            page.AppendFormat("
Path Alias = {0}
", req.DadConfig.PathAlias);
            page.AppendFormat("
Xdb Alias = {0}
", req.DadConfig.XdbAlias);
            page.AppendFormat("
");

            page.Append(GetSignature());

            return page.ToString();

        }

        ///
        /// For an invalid request, returns a HTML-formatted error page with the details of the request and the error
        ///
        public static string GetInvalidRequestDebugPage(string requestPath, DadConfiguration dadConfig)
        {
            StringBuilder page = new StringBuilder();

            page.Append("");
            page.AppendFormat("
Thoth Gateway Invalid Request
");

            page.AppendFormat("
The request is invalid. Please check the URL syntax, and examine the inclusion and exclusion lists.
");

            page.AppendFormat("
Request

{0}
", requestPath);

            page.AppendFormat("
Inclusion List

{0}
", dadConfig.InclusionList);

            page.AppendFormat("
Exclusion List

{0}
", DadConfiguration.DEFAULT_EXCLUSION_LIST + " " + dadConfig.ExclusionList);

            page.Append(GetSignature());

            return page.ToString();

        }

    }
}


text:
@protocol ALO7ProgressiveMigrateDelegate;

@interface ALO7ProgressiveMigrationManager : NSObject
+ (instancetype)sharedManager;
- (BOOL)migrateStoreAtUrl:(NSURL *)srcStoreUrl storeType:(NSString *)storeType targetModel:(NSManagedObjectModel *)targetModel bundle:(NSBundle *)bundle error:(NSError **)error;

@property (nonatomic, weak) id <ALO7ProgressiveMigrateDelegate> delegate;
@property (nonatomic, strong, readonly) NSManagedObjectModel *migrationSrcModel;
@end

@protocol ALO7ProgressiveMigrateDelegate <NSObject>
@required
- (NSManagedObjectModel *)nextModelOfModel:(NSManagedObjectModel *)model amongModelPaths:(NSArray *)allModelPaths;
@optional
- (BOOL)modelA:(NSManagedObjectModel *)modelA equalsToModelB:(NSManagedObjectModel *)modelB;
@end


text:
{% extends "observations/encounter_detail.html" %}

{% load leaflet_tags geojson_tags static observations %}

{% block update_links %}
{% include "shared/update_links_qa.html" with label=False %}
{% endblock %}

{% block heading %}
{{ object.get_taxon_display }} - {{ object.get_species_display }}
{% endblock %}

  {% block obsdetails %}
    Data source: {{ object.get_source_display }}

    Health status: {{ object.get_health_display }}

    Sex: {{ object.get_sex_display }}

    Maturity: {{ object.get_maturity_display }}

  {% endblock %}

{% block obscards %}

  {% for tag in tags %}

      Tag ID {{ tag.name }}

      Type: {{ tag.get_tag_type_display }}

      Location: {{ tag.get_tag_location_display }}

  {% endfor %}

{% endblock %}


text:
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

/**
 * @fileoverview Does common handling for requests coming from web pages and
 * routes them to the provided handler.
 */

/**
 * Gets the scheme + origin from a web url.
 * @param {string} url Input url
 * @return {?string} Scheme and origin part if url parses
 */
function getOriginFromUrl(url) {
  var re = new RegExp('^(https?://)[^/]*/?');
  var originarray = re.exec(url);
  if (originarray == null) return originarray;
  var origin = originarray[0];
  while (origin.charAt(origin.length - 1) == '/') {
    origin = origin.substring(0, origin.length - 1);
  }
  if (origin == 'http:' || origin == 'https:')
    return null;
  return origin;
}

/**
 * Returns whether the registered key appears to be valid.
 * @param {Object} registeredKey The registered key object.
 * @param {boolean} appIdRequired Whether the appId property is required on
 *     each challenge.
 * @return {boolean} Whether the object appears valid.
 */
function isValidRegisteredKey(registeredKey, appIdRequired) {
  if (appIdRequired && !registeredKey.hasOwnProperty('appId')) {
    return false;
  }
  if (!registeredKey.hasOwnProperty('keyHandle'))
    return false;
  if (registeredKey['version']) {
    if (registeredKey['version'] != 'U2F_V1' &&
        registeredKey['version'] != 'U2F_V2') {
      return false;
    }
  }
  return true;
}

/**
 * Returns whether the array of registered keys appears to be valid.
 * @param {Array<Object>} registeredKeys The array of registered keys.
 * @param {boolean} appIdRequired Whether the appId property is required on
 *     each challenge.
 * @return {boolean} Whether the array appears valid.
 */
function isValidRegisteredKeyArray(registeredKeys, appIdRequired) {
  return registeredKeys.every(function(key) {
    return isValidRegisteredKey(key, appIdRequired);
  });
}

/**
 * Returns whether the array of SignChallenges appears to be valid.
 * @param {Array<SignChallenge>} signChallenges The array of sign challenges.
 * @param {boolean} challengeValueRequired Whether each challenge object
 *     requires a challenge value.
 * @param {boolean} appIdRequired Whether the appId property is required on
 *     each challenge.
 * @return {boolean} Whether the array appears valid.
 */
function isValidSignChallengeArray(signChallenges, challengeValueRequired,
    appIdRequired) {
  for (var i = 0; i < signChallenges.length; i++) {
    var incomingChallenge = signChallenges[i];
    if (challengeValueRequired &&
        !incomingChallenge.hasOwnProperty('challenge'))
      return false;
    if (!isValidRegisteredKey(incomingChallenge, appIdRequired)) {
      return false;
    }
  }
  return true;
}

/** Posts the log message to the log url.
 * @param {string} logMsg the log message to post.
 * @param {string=} opt_logMsgUrl the url to post log messages to.
 */
function logMessage(logMsg, opt_logMsgUrl) {
  console.log(UTIL_fmt('logMessage("' + logMsg + '")'));

  if (!opt_logMsgUrl) {
    return;
  }
  // Image fetching is not allowed per packaged app CSP.
  // But video and audio is.
  var audio = new Audio();
  audio.src = opt_logMsgUrl + logMsg;
}

/**
 * @param {Object} request Request object
 * @param {MessageSender} sender Sender frame
 * @param {Function} sendResponse Response callback
 * @return {?Closeable} Optional handler object that should be closed when port
 *     closes
 */
function handleWebPageRequest(request, sender, sendResponse) {
  switch (request.type) {
    case GnubbyMsgTypes.ENROLL_WEB_REQUEST:
      return handleWebEnrollRequest(sender, request, sendResponse);

    case GnubbyMsgTypes.SIGN_WEB_REQUEST:
      return handleWebSignRequest(sender, request, sendResponse);

    case MessageTypes.U2F_REGISTER_REQUEST:
      return handleU2fEnrollRequest(sender, request, sendResponse);

    case MessageTypes.U2F_SIGN_REQUEST:
      return handleU2fSignRequest(sender, request, sendResponse);

    default:
      sendResponse(
          makeU2fErrorResponse(request, ErrorCodes.BAD_REQUEST, undefined,
              MessageTypes.U2F_REGISTER_RESPONSE));
      return null;
  }
}

/**
 * Set-up listeners for webpage connect.
 * @param {Object} port connection is on.
 * @param {Object} request that got received on port.
 */
function handleWebPageConnect(port, request) {
  var closeable;

  var onMessage = function(request) {
    console.log(UTIL_fmt('request'));
    console.log(request);
    closeable = handleWebPageRequest(request, port.sender,
        function(response) {
          response['requestId'] = request['requestId'];
          port.postMessage(response);
        });
  };

  var onDisconnect = function() {
    port.onMessage.removeListener(onMessage);
    port.onDisconnect.removeListener(onDisconnect);
    if (closeable) closeable.close();
  };

  port.onMessage.addListener(onMessage);
  port.onDisconnect.addListener(onDisconnect);

  // Start work on initial message.
  onMessage(request);
}

/**
 * Makes a response to a request.
 * @param {Object} request The request to make a response to.
 * @param {string} responseSuffix How to name the response's type.
 * @param {string=} opt_defaultType The default response type, if none is
 *     present in the request.
 * @return {Object} The response object.
 */
function makeResponseForRequest(request, responseSuffix, opt_defaultType) {
  var type;
  if (request && request.type) {
    type = request.type.replace(/_request$/, responseSuffix);
  } else {
    type = opt_defaultType;
  }
  var reply = { 'type': type };
  if (request && request.requestId) {
    reply.requestId = request.requestId;
  }
  return reply;
}

/**
 * Makes a response to a U2F request with an error code.
 * @param {Object} request The request to make a response to.
 * @param {ErrorCodes} code The error code to return.
 * @param {string=} opt_detail An error detail string.
 * @param {string=} opt_defaultType The default response type, if none is
 *     present in the request.
 * @return {Object} The U2F error.
 */
function makeU2fErrorResponse(request, code, opt_detail, opt_defaultType) {
  var reply = makeResponseForRequest(request, '_response', opt_defaultType);
  var error = {'errorCode': code};
  if (opt_detail) {
    error['errorMessage'] = opt_detail;
  }
  reply['responseData'] = error;
  return reply;
}

/**
 * Makes a success response to a web request with a responseData object.
 * @param {Object} request The request to make a response to.
 * @param {Object} responseData The response data.
 * @return {Object} The web error.
 */
function makeU2fSuccessResponse(request, responseData) {
  var reply = makeResponseForRequest(request, '_response');
  reply['responseData'] = responseData;
  return reply;
}

/**
 * Makes a response to a web request with an error code.
 * @param {Object} request The request to make a response to.
 * @param {GnubbyCodeTypes} code The error code to return.
 * @param {string=} opt_defaultType The default response type, if none is
 *     present in the request.
 * @return {Object} The web error.
 */
function makeWebErrorResponse(request, code, opt_defaultType) {
  var reply = makeResponseForRequest(request, '_reply', opt_defaultType);
  reply['code'] = code;
  return reply;
}

/**
 * Makes a success response to a web request with a responseData object.
 * @param {Object} request The request to make a response to.
 * @param {Object} responseData The response data.
 * @return {Object} The web error.
 */
function makeWebSuccessResponse(request, responseData) {
  var reply = makeResponseForRequest(request, '_reply');
  reply['code'] = GnubbyCodeTypes.OK;
  reply['responseData'] = responseData;
  return reply;
}

/**
 * Maps an error code from the ErrorCodes namespace to the GnubbyCodeTypes
 * namespace.
 * @param {ErrorCodes} errorCode Error in the ErrorCodes namespace.
 * @param {boolean} forSign Whether the error is for a sign request.
 * @return {GnubbyCodeTypes} Error code in the GnubbyCodeTypes namespace.
 */
function mapErrorCodeToGnubbyCodeType(errorCode, forSign) {
  var code;
  switch (errorCode) {
    case ErrorCodes.BAD_REQUEST:
      return GnubbyCodeTypes.BAD_REQUEST;

    case ErrorCodes.DEVICE_INELIGIBLE:
      return forSign ? GnubbyCodeTypes.NONE_PLUGGED_ENROLLED :
          GnubbyCodeTypes.ALREADY_ENROLLED;

    case ErrorCodes.TIMEOUT:
      return GnubbyCodeTypes.WAIT_TOUCH;
  }
  return GnubbyCodeTypes.UNKNOWN_ERROR;
}

/**
 * Maps a helper's error code from the DeviceStatusCodes namespace to a
 * U2fError.
 * @param {number} code Error code from DeviceStatusCodes namespace.
 * @return {U2fError} An error.
 */
function mapDeviceStatusCodeToU2fError(code) {
  switch (code) {
    case DeviceStatusCodes.WRONG_DATA_STATUS:
      return {errorCode: ErrorCodes.DEVICE_INELIGIBLE};

    case DeviceStatusCodes.TIMEOUT_STATUS:
    case DeviceStatusCodes.WAIT_TOUCH_STATUS:
      return {errorCode: ErrorCodes.TIMEOUT};

    default:
      var reportedError = {
        errorCode: ErrorCodes.OTHER_ERROR,
        errorMessage: 'device status code: ' + code.toString(16)
      };
      return reportedError;
  }
}

/**
 * Sends a response, using the given sentinel to ensure at most one response is
 * sent. Also closes the closeable, if it's given.
 * @param {boolean} sentResponse Whether a response has already been sent.
 * @param {?Closeable} closeable A thing to close.
 * @param {*} response The response to send.
 * @param {Function} sendResponse A function to send the response.
 */
function sendResponseOnce(sentResponse, closeable, response, sendResponse) {
  if (closeable) {
    closeable.close();
  }
  if (!sentResponse) {
    sentResponse = true;
    try {
      // If the page has gone away or the connection has otherwise gone,
      // sendResponse fails.
      sendResponse(response);
    } catch (exception) {
      console.warn('sendResponse failed: ' + exception);
    }
  } else {
    console.warn(UTIL_fmt('Tried to reply more than once! Juan, FIX ME'));
  }
}

/**
 * @param {!string} string Input string
 * @return {Array<number>} SHA256 hash value of string.
 */
function sha256HashOfString(string) {
  var s = new SHA256();
  s.update(UTIL_StringToBytes(string));
  return s.digest();
}

/**
 * Normalizes the TLS channel ID value:
 * 1. Converts semantically empty values (undefined, null, 0) to the empty
 *     string.
 * 2. Converts valid JSON strings to a JS object.
 * 3. Otherwise, returns the input value unmodified.
 * @param {Object|string|undefined} opt_tlsChannelId TLS Channel id
 * @return {Object|string} The normalized TLS channel ID value.
 */
function tlsChannelIdValue(opt_tlsChannelId) {
  if (!opt_tlsChannelId) {
    // Case 1: Always set some value for  TLS channel ID, even if it's the empty
    // string: this browser definitely supports them.
    return '';
  }
  if (typeof opt_tlsChannelId === 'string') {
    try {
      var obj = JSON.parse(opt_tlsChannelId);
      if (!obj) {
        // Case 1: The string value 'null' parses as the Javascript object null,
        // so return an empty string: the browser definitely supports TLS
        // channel id.
        return '';
      }
      // Case 2: return the value as a JS object.
      return /** @type {Object} */ (obj);
    } catch (e) {
      console.warn('Unparseable TLS channel ID value ' + opt_tlsChannelId);
      // Case 3: return the value unmodified.
    }
  }
  return opt_tlsChannelId;
}

/**
 * Creates a browser data object with the given values.
 * @param {!string} type A string representing the "type" of this browser data
 *     object.
 * @param {!string} serverChallenge The server's challenge, as a base64-
 *     encoded string.
 * @param {!string} origin The server's origin, as seen by the browser.
 * @param {Object|string|undefined} opt_tlsChannelId TLS Channel Id
 * @return {string} A string representation of the browser data object.
 */
function makeBrowserData(type, serverChallenge, origin, opt_tlsChannelId) {
  var browserData = {
    'typ' : type,
    'challenge' : serverChallenge,
    'origin' : origin
  };
  if (BROWSER_SUPPORTS_TLS_CHANNEL_ID) {
    browserData['cid_pubkey'] = tlsChannelIdValue(opt_tlsChannelId);
  }
  return JSON.stringify(browserData);
}

/**
 * Creates a browser data object for an enroll request with the given values.
 * @param {!string} serverChallenge The server's challenge, as a base64-
 *     encoded string.
 * @param {!string} origin The server's origin, as seen by the browser.
 * @param {Object|string|undefined} opt_tlsChannelId TLS Channel Id
 * @return {string} A string representation of the browser data object.
 */
function makeEnrollBrowserData(serverChallenge, origin, opt_tlsChannelId) {
  return makeBrowserData(
      'navigator.id.finishEnrollment', serverChallenge, origin,
      opt_tlsChannelId);
}

/**
 * Creates a browser data object for a sign request with the given values.
 * @param {!string} serverChallenge The server's challenge, as a base64-
 *     encoded string.
 * @param {!string} origin The server's origin, as seen by the browser.
 * @param {Object|string|undefined} opt_tlsChannelId TLS Channel Id
 * @return {string} A string representation of the browser data object.
 */
function makeSignBrowserData(serverChallenge, origin, opt_tlsChannelId) {
  return makeBrowserData(
      'navigator.id.getAssertion', serverChallenge, origin, opt_tlsChannelId);
}

/**
 * Encodes the sign data as an array of sign helper challenges.
 * @param {Array<SignChallenge>} signChallenges The sign challenges to encode.
 * @param {string|undefined} opt_defaultChallenge A default sign challenge
 *     value, if a request does not provide one.
 * @param {string=} opt_defaultAppId The app id to use for each challenge, if
 *     the challenge contains none.
 * @param {function(string, string): string=} opt_challengeHashFunction
 *     A function that produces, from a key handle and a raw challenge, a hash
 *     of the raw challenge. If none is provided, a default hash function is
 *     used.
 * @return {!Array<SignHelperChallenge>} The sign challenges, encoded.
 */
function encodeSignChallenges(signChallenges, opt_defaultChallenge,
    opt_defaultAppId, opt_challengeHashFunction) {
  function encodedSha256(keyHandle, challenge) {
    return B64_encode(sha256HashOfString(challenge));
  }
  var challengeHashFn = opt_challengeHashFunction || encodedSha256;
  var encodedSignChallenges = [];
  if (signChallenges) {
    for (var i = 0; i < signChallenges.length; i++) {
      var challenge = signChallenges[i];
      var keyHandle = challenge['keyHandle'];
      var challengeValue;
      if (challenge.hasOwnProperty('challenge')) {
        challengeValue = challenge['challenge'];
      } else {
        challengeValue = opt_defaultChallenge;
      }
      var challengeHash = challengeHashFn(keyHandle, challengeValue);
      var appId;
      if (challenge.hasOwnProperty('appId')) {
        appId = challenge['appId'];
      } else {
        appId = opt_defaultAppId;
      }
      var encodedChallenge = {
        'challengeHash': challengeHash,
        'appIdHash': B64_encode(sha256HashOfString(appId)),
        'keyHandle': keyHandle,
        'version': (challenge['version'] || 'U2F_V1')
      };
      encodedSignChallenges.push(encodedChallenge);
    }
  }
  return encodedSignChallenges;
}

/**
 * Makes a sign helper request from an array of challenges.
 * @param {Array<SignHelperChallenge>} challenges The sign challenges.
 * @param {number=} opt_timeoutSeconds Timeout value.
 * @param {string=} opt_logMsgUrl URL to log to.
 * @return {SignHelperRequest} The sign helper request.
 */
function makeSignHelperRequest(challenges, opt_timeoutSeconds, opt_logMsgUrl) {
  var request = {
    'type': 'sign_helper_request',
    'signData': challenges,
    'timeout': opt_timeoutSeconds || 0,
    'timeoutSeconds': opt_timeoutSeconds || 0
  };
  if (opt_logMsgUrl !== undefined) {
    request.logMsgUrl = opt_logMsgUrl;
  }
  return request;
}


text:
'use strict';

// var request = require('request');
var htmlparser = require('htmlparser2-without-node-native');

var NAME_DELIM = ':';

var META = 'meta';
var HEAD = 'head';
var TITLE = 'title';
var CHARSET = 'charset'

var parseMetaInfo = function(html, callback) {
    var meta = {meta: {}};

    var isHead = false;
    var currentTag;
    var parser = new htmlparser.Parser({
        onopentag: function(tag, attribs) {
            currentTag = tag;
            if (tag === HEAD)
                isHead = true;

            var name = attribs.name || attribs.property || attribs.itemprop;
            if (tag === META && name) {
                var nameParts = name.split(NAME_DELIM);
                var content = attribs.content || attribs.value;

                var metaRef = meta;
                if (nameParts.length > 1) {
                    var i = 0;
                    for (var length = nameParts.length; i < length - 1; i++) {
                        if (metaRef[nameParts[i]]) {
                            if (typeof metaRef[nameParts[i]] !== 'object') {
                                var base = metaRef[nameParts[i]];
                                metaRef[nameParts[i]] = { base };
                            }

                            metaRef = metaRef[nameParts[i]];
                        } else
                            metaRef = metaRef[nameParts[i]] = {};
                    }

                    if (metaRef[nameParts[i]]) {
                        if (!Array.isArray(metaRef[nameParts[i]])) {
                            metaRef[nameParts[i]] = [ metaRef[nameParts[i]] ];
                        }

                        metaRef[nameParts[i]].push(content);
                    } else
                        metaRef[nameParts[i]] = content;
                } else
                    metaRef.meta[name] = content;
            } else if (tag === META && CHARSET in attribs)
                meta.meta.charset = attribs.charset;
        },
        ontext: function(text) {
            if (text.trim().length > 0 && isHead && currentTag === TITLE)
                meta.title = text;
        },
        onclosetag: function(tag) {
            if (tag === HEAD)
                isHead = false;
        },
        onend: function() {
            callback && callback(meta);
        }
    });
    parser.write(html);
    parser.end();
}

// var getMetaInfo = function(url, callback, timeout) {
//     timeout = timeout || 10000;
//
//     var options = {
//         url: url,
//         headers: {
//             'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.87 Safari/537.36'
//         },
//         timeout: timeout
//     };
//
//     request(options, function(error, response, body) {
//         if (!error && response.statusCode == 200)
//             parseMetaInfo(body, callback);
//         else
//             callback && callback(null);
//     });
// }

module.exports = {
    // getMetaInfo,
    parseMetaInfo
};


text:
<?php

ini_set('display_errors', false);

require 'CurlClient.php';
require 'OAuthClient.php';

$method = $_SERVER['REQUEST_METHOD'];

// TODO: handle or reject relative and non-HTTP(S) URLs

switch ($method) {
  case 'OPTIONS':
    header('Access-Control-Allow-Origin: *');
    header('Access-Control-Allow-Methods: GET, HEAD, POST, DELETE, OPTIONS');
    header('Access-Control-Allow-Headers: accept, x-requested-with, content-type, vege-cache-control, vege-follow');
    exit();

  case 'GET':
  case 'HEAD':
  case 'POST':
  case 'PUT':
  case 'DELETE':
    break; // allowed

  default:
    http_status_code(406); // not allowed
    exit();
}

if (!isset($_GET['url'])) {
  throw new Exception('No URL');
}

$url = $_GET['url'];

$file = buildFilePath($method, $url);
//print "$file\n"; exit();

$headers = getallheaders();

$nocache = isset($headers['Vege-Cache-Control']) && ($headers['Vege-Cache-Control'] == 'no-cache');

if ($nocache || (!file_exists($file) || !file_exists($file . '.json') || filesize($file) < 50)) {
  /* pass through request headers */
  $requestHeaders = array_map(function($value, $key) {
    $key = strtolower($key);

    if (!in_array($key, array('origin', 'referer', 'connection', 'host', 'accept-encoding', 'dnt', 'vege-cache-control', 'vege-follow'))) {
      return $key . ': ' . $value;
    }
  }, $headers, array_keys($headers));

  /* host configuration */
  $config = readConfig($url);

  if (isset($config['oauth'])) {
    $client = new OAuthClient;
    $requestHeaders[] = $client->authorizationHeader($config['oauth']);
  } else {
    $client = new CurlClient;
  }

  if (isset($config['params'])) {
    $url .= (strpos($url, '?') === false ? '?' : '&') . http_build_query($config['params']);
  }

  if (isset($config['headers'])) {
    foreach ($config['headers'] as $key => $value) {
      $requestHeaders[] = $key . ': ' . $value;
    }
  }

  switch ($method) {
    case 'HEAD':
    curl_setopt($client->curl, CURLOPT_CUSTOMREQUEST, 'HEAD');
    curl_setopt($client->curl, CURLOPT_FOLLOWLOCATION, false);
    break;

    case 'POST':
    curl_setopt($client->curl, CURLOPT_POST, true);
    curl_setopt($client->curl, CURLOPT_POSTFIELDS, file_get_contents('php://input'));
    break;

    case 'DELETE':
    curl_setopt($client->curl, CURLOPT_CUSTOMREQUEST, 'DELETE');
    break;

    case 'PUT':
    // TODO
    break;
  }

  /* output file */
  $output = gzopen($file, 'w');

  // TODO: catch exceptions
  $info = $client->get($url, $requestHeaders, $output);

  gzclose($output);

  file_put_contents($file . '.json', json_encode($info, JSON_PRETTY_PRINT));
}

$info = json_decode(file_get_contents($file . '.json'), true);

$exposedHeaders = array(
  'link',
  'content-location',
  'x-status',
  'x-location',
  'x-ratelimit-limit',
  'x-ratelimit-remaining',
  'x-ratelimit-reset',
  'x-rate-limit-limit',
  'x-rate-limit-remaining',
  'x-rate-limit-reset',
);

if ($info['redirect_url']) {
  header('x-status: ' . $info['http_code']);
  header('x-location: ' . $info['redirect_url']);
  http_response_code(204);
} else {
  http_response_code($info['http_code']);
  header('Content-Type: ' . $info['content_type']);
}

header('Access-Control-Allow-Origin: *');
header('Access-Control-Expose-Headers: ' . implode(', ', $exposedHeaders));
header('Content-Location: ' . $info['url']);
//header('Content-Length: ' . filesize($file));

foreach ($info['headers'] as $key => $value) {
  if (in_array($key, $exposedHeaders)) {
    header($key . ': ' . $value);
  }
}

// remove the response file on failure. TODO: something better?
if ($info['http_code'] >= 400) {
  unlink($file);
  exit();
}

//if ($method === 'GET' || $method === 'POST') {
  readfile('compress.zlib://' . $file);
//}

function readConfig($url) {
  $configFile = __DIR__ . '/config.json';

  if (!file_exists($configFile)) {
    return null;
  }

  $configs = json_decode(file_get_contents($configFile), true);

  $host = parse_url($url, PHP_URL_HOST);

  return isset($configs[$host]) ? $configs[$host] : null;
}

function buildFilePath($method, $url) {
  $parts = parse_url($url);

  if (!in_array($parts['scheme'], array('http', 'https'))) {
    throw new Exception('URL must be HTTP or HTTPS');
  }

  $host = $parts['host'];

  if (isset($parts['port'])) {
    $host .= '-' . $parts['port'];
  }

  $host = preg_replace('/[^\w\.]/', '-', $host);

  $dir = __DIR__ . '/cache/' . $host . '/' . $method;

  if (!file_exists($dir)) {
    mkdir($dir, 0700, true);
  }

  if ($method == 'POST') {
    $url .= file_get_contents('php://input');
  }

  return $dir . '/' . hash('sha256', $url);
}


text:
package ro.infoiasi.sparql.dao;

import static ro.infoiasi.dao.entity.metamodel.AuthorMetaModel.*;
import static ro.infoiasi.dao.entity.metamodel.UserMetaModel.ID_VALUE;

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

import org.apache.jena.query.QueryExecutionFactory;
import org.apache.jena.query.QuerySolution;
import org.apache.jena.query.ResultSet;
import org.apache.jena.rdf.model.Literal;

import ro.infoiasi.dao.entity.Author;
import ro.infoiasi.sparql.insertionPoints.subqueries.AggregatePropertyFunction;
import ro.infoiasi.sparql.insertionPoints.subqueries.AggregateSubQuery;

public class AuthorDAO extends GenericDAO<Author>{

	public List<Author> authorList = new ArrayList<Author>();

	public AuthorDAO() {
		super(Author.class);
	}

	@Override
	protected Author toEntity(QuerySolution solution) throws Exception {
		Author a = new Author();
        a.setName(solution.getLiteral(NAME_VALUE).getString());
        a.setRating(solution.getLiteral(RATING_VALUE).getLong());
        return a;
	}
	public List<Author> getAllAuthors() {
		return authorList;
	}

	public Author getAuthor(int i) {
		for(Author a:authorList) {
			if(a.getId() == i) {
				return a;
			}
		}
		return null;
	}

	public int updateAuthor(Author updateAuthor) {
		List<Author> authorList = getAllAuthors();
		for(Author a:authorList) {
			if(a.getName().toLowerCase().equals(updateAuthor.getName().toLowerCase())) {
				int index = authorList.indexOf(a);
				authorList.set(index, updateAuthor);
				return 1;
			}
		}
		return 0;
	}

	public int deleteAuthor(String name) {
		List<Author> authorList = getAllAuthors();

		for (Author a : authorList) {
			if (a.getName().equals(name)) {
				int index = authorList.indexOf(a);
				authorList.remove(index);
				return 1;
			}
		}
		return 0;
	}

	public long getNextId() throws Exception {
        String mapping = "next";
        String query = new AggregateSubQuery(clazz, AggregatePropertyFunction.MAX, ID_VALUE, mapping).construct();
        if (DEBUG) {
            logger.debug(query);
        }
        ResultSet resultSet = QueryExecutionFactory.sparqlService(HTTP_ENDPOINT, query).execSelect();
        if (resultSet.hasNext()) {
            QuerySolution solution = resultSet.next();
            return getCurrentValue(mapping, solution) + 1;
        }
        throw new Exception("Could not query for next id");
    }

	private long getCurrentValue(String mapping, QuerySolution solution) {
        Literal literal = solution.getLiteral(mapping);
        if(literal == null) {
            return 0;
        }
        return literal.getLong();
    }

}


text:
This is a custom implementation of the password hashing logic from <http://www.passwordmaker.org/>

## How This Works ##

Unlike most password managers, this tool doesn't store your password data so there is nothing to lose or have stolen.

You memorize a single master password that you ideally keep in your head. This tool uses a standard one-way hash algorithm (MD5) to generate unique, partially disposable passwords for every password protected account you have. If the password to one account is compromised, your master password and other passwords are safe. The generated password is typically put on the clipboard. This tool doesn't write it to any files or databases and doesn't send anything over the network. Presumably, you paste the password into a web site or other application and then clear or overwrite your clipboard.

More information from <http://www.passwordmaker.org/>

There are two interfaces:

- __cli__: Console application, written in Java. Designed to be run from a shell on Linux, Mac, Windows, or any other Java compatible system.
- __android__: Android GUI application.

## CLI ##

To build, you will need

- Java 1.7+ <http://www.oracle.com/technetwork/java/javase/downloads/index.html>
- SBT <http://www.scala-sbt.org/>

run

```bash
sbt package
```

Running without arguments will bring up argument help text:

```bash
java -jar target/pwmaker-1.0-SNAPSHOT.jar
```

```
Error parsing command line arguments: Missing required option(s) ['user', 'url']
Option (* = required)  Description
---------------------  -----------
--alphaNumeric         Only use [A-Za-z0-9] characters. Do
                         not use [`~!@#$%^&*()_-+={}|[]
                         \:";'<>?,./]
--awtClipboard         Use Java AWT to write text to the
                         clipboard. Good for Windows users.
--consoleOutput        Output the generated password to the
                         console
--hang                 hang the process rather than exit. For
                         rare use cases.
--length <Integer>     Generated password length (default: 16)
--password             Master password. It is not recommended
                         to use this option for security.
                         Instead enter password on separate
                         hidden prompt.
--reenterPassword      Ask the user to enter the master
                         password twice for verification.
* --url                url to generate password with
* --user               user string to generate password with.
--xsel                 Pipe password to xsel UNIX clipboard
                         tool. Good for Linux users.
```

I use a script with preferred options included like this:

```bash
#!/bin/sh
java -jar ~/src/opensource/pwmaker/target/pwmaker-1.0-SNAPSHOT.jar -xsel -reenterPassword "$@"
```

## Android ##

This is quite self-explanatory.

![Android Screenshot](android_pwmaker_screenshot.png)