text:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title><?php if (isset($title)){ echo $title; } else { echo "NULL"; } ?></title>

    <!-- Bootstrap Core CSS -->
    <link href="<?php echo base_url('assets/bootstrap/css/bootstrap.min.css'); ?>" rel="stylesheet">

    <!-- MetisMenu CSS -->
    <link href="<?php echo base_url('assets/metisMenu/metisMenu.min.css'); ?>" rel="stylesheet">

    <!-- Custom CSS -->
    <link href="<?php echo base_url('assets/dist/css/sb-admin-2.css'); ?>" rel="stylesheet">

    <!-- Morris Charts CSS -->
    <link href="<?php echo base_url('assets/morrisjs/morris.css'); ?>" rel="stylesheet">

    <!-- Custom Fonts -->
    <link href="<?php echo base_url('assets/font-awesome/css/font-awesome.min.css'); ?>" rel="stylesheet" type="text/css">

    <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
    <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
    <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
    <![endif]-->
</head>
<body>
<div id="wrapper">


text:
using System;

using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;

using ExaminingLogging.Lib;

namespace ExaminingLogging
{
    public class Experiments
    {
        public static void SubMain()
        {
            Experiments.GetLoggingWhenNoProviders();
        }

        /// <summary>
        /// Result: Expected, no exception and no output to console (or any other logger).
        /// What happens if you ask for a logger, but there are no logging providers setup?
        /// Expected: No exception, logging just does nothing.
        /// </summary>
        private static void GetLoggingWhenNoProviders()
        {
            var serviceProvider = new ServiceCollection()
                .AddLogging()
                .BuildServiceProvider();

            var logger = serviceProvider.GetRequiredService<ILogger<Experiments>>();

            logger.TestAllLogLevels(); // No exception, no logging to console.
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package org.openflow.protocol;

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

import org.jboss.netty.buffer.ChannelBuffer;
import org.openflow.util.U16;

/**
 * Represents ofp_packet_queue
 *
 * @author Andrew Ferguson (adf@cs.brown.edu)
 */
public class OFPacketQueue {
	public static int MINIMUM_LENGTH = 8;

	protected int queueId;
	protected short length;
	protected List<OFQueueProp> properties = new ArrayList<OFQueueProp>();

	public OFPacketQueue() {
		this.queueId = -1;
		this.length = U16.t(MINIMUM_LENGTH);
	}

	public OFPacketQueue(int queueId) {
		this.queueId = queueId;
		this.length = U16.t(MINIMUM_LENGTH);
	}

	/**
	 * @return the queueId
	 */
	public long getQueueId() {
		return queueId;
	}

	/**
	 * @param queueId
	 *            the queueId to set
	 */
	public void setQueueId(int queueId) {
		this.queueId = queueId;
	}

	/**
	 * @return the queue's properties
	 */
	public List<OFQueueProp> getProperties() {
		return properties;
	}

	/**
	 * @param properties
	 *            the properties to set
	 */
	public void setProperties(List<OFQueueProp> properties) {
		this.properties = properties;

		this.length = U16.t(MINIMUM_LENGTH);
		for (OFQueueProp prop : properties) {
			this.length += prop.getLength();
		}
	}

	/**
	 * @return the length
	 */
	public short getLength() {
		return length;
	}

	public void readFrom(ChannelBuffer data) {
		this.queueId = data.readInt();
		this.length = data.readShort();
		data.readShort(); // pad

		int availLength = (this.length - MINIMUM_LENGTH);
		this.properties.clear();

		while (availLength > 0) {
			OFQueueProp prop = new OFQueueProp();
			prop.readFrom(data);
			properties.add(prop);
			availLength -= prop.getLength();
		}
	}

	public void writeTo(ChannelBuffer data) {
		data.writeInt(queueId);
		data.writeShort(length);
		data.writeShort(0); // pad

		for (OFQueueProp prop : properties) {
			prop.writeTo(data);
		}
	}

	@Override
	public int hashCode() {
		final int prime = 359;
		int result = super.hashCode();
		result = prime * result + queueId;
		result = prime * result + length;
		result = prime * result + properties.hashCode();
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj) {
			return true;
		}
		if (!super.equals(obj)) {
			return false;
		}
		if (!(obj instanceof OFPacketQueue)) {
			return false;
		}
		OFPacketQueue other = (OFPacketQueue) obj;
		if (queueId != other.queueId) {
			return false;
		}
		if (!properties.equals(other.properties)) {
			return false;
		}
		return true;
	}
}


text:
<!DOCTYPE html
    PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

  <xi:include href="layout.html" />

    <title>Prepare Diff</title>

Prepare Diff

        <form action="${href.changeset()}" method="get" class="form well">
          <fieldset>
            <legend>Select the base and the target for the diff:</legend>

                From:

                  <input type="text" id="old_path" name="old_path" value="$old_path"
                         class="input-block-level" />

                  at revision:

                    <input type="text" id="old" name="old" value="$old_rev"
                           class="input-block-level" />

                To:

                  <input type="text" id="new_path" name="new_path" value="$new_path"
                         class="input-block-level" />

                  at revision:

                    <input type="text" id="new" name="new" value="$new_rev"
                           class="input-block-level" />

              Note
              For either path, you can start typing the path and will be
              presented a list of existing directories and files to select
              from. Select an entry by clicking on it, or by using the
              up/down cursor keys and hitting tab.

          </fieldset>

            <button type="submit" class="btn">View changes</button>

        </form>

          Note: See
          TracChangeset
          for help on using the diff feature.


text:
package org.overlord.gadgets.web.server.http.auth;

import org.apache.shindig.gadgets.http.HttpRequest;

import com.google.inject.Singleton;

/**
 * Provides no authentication.  This is the default if no authentication provider
 * is provided by a guice module.
 * @author eric.wittmann@redhat.com
 */
@Singleton
public class NoAuthenticationProvider implements AuthenticationProvider {

    /**
     * Constructor.
     */
    public NoAuthenticationProvider() {
    }

    /**
     * @see org.overlord.gadgets.web.server.http.auth.AuthenticationProvider#provideAuthentication(org.apache.shindig.gadgets.http.HttpRequest)
     */
    @Override
    public void provideAuthentication(HttpRequest httpRequest) {
        // Does nothing.
    }

}


text:
/*	$KAME: advcap.c,v 1.11 2003/05/19 09:46:50 keiichi Exp $	*/

/*
 * Copyright (c) 1983 The Regents of the University of California.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *	This product includes software developed by the University of
 *	California, Berkeley and its contributors.
 * 4. Neither the name of the University nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

/*
 * remcap - routines for dealing with the remote host data base
 *
 * derived from termcap
 */
#include <sys/types.h>
#include <sys/uio.h>
#include <unistd.h>
#include <fcntl.h>
#include <ctype.h>
#include <stdlib.h>
#include <stdio.h>
#include <syslog.h>
#include <errno.h>
#include <string.h>
#include "pathnames.h"

#ifndef BUFSIZ
#define	BUFSIZ		1024
#endif
#define MAXHOP		32		/* max number of tc= indirections */

#define	tgetent		agetent
#define	tnchktc		anchktc
#define	tnamatch	anamatch
#define	tgetnum		agetnum
#define	tgetflag	agetflag
#define	tgetstr		agetstr

#if 0
#define V_TERMCAP	"REMOTE"
#define V_TERM		"HOST"
#endif

char	*RM;

/*
 * termcap - routines for dealing with the terminal capability data base
 *
 * BUG:		Should use a "last" pointer in tbuf, so that searching
 *		for capabilities alphabetically would not be a n**2/2
 *		process when large numbers of capabilities are given.
 * Note:	If we add a last pointer now we will screw up the
 *		tc capability. We really should compile termcap.
 *
 * Essentially all the work here is scanning and decoding escapes
 * in string capabilities.  We don't use stdio because the editor
 * doesn't, and because living w/o it is not hard.
 */

static	char *tbuf;
static	int hopcount;	/* detect infinite loops in termcap, init 0 */

static	char *remotefile;

extern char *conffile;

int tgetent __P((char *, char *));
int getent __P((char *, char *, char *));
int tnchktc __P((void));
int tnamatch __P((char *));
static char *tskip __P((char *));
int64_t tgetnum __P((char *));
#ifdef MIP6
int64_t agetusec __P((char *));
#endif
int tgetflag __P((char *));
char *tgetstr __P((char *, char **));
static char *tdecode __P((char *, char **));

/*
 * Get an entry for terminal name in buffer bp,
 * from the termcap file.  Parse is very rudimentary;
 * we just notice escaped newlines.
 */
int
tgetent(bp, name)
	char *bp, *name;
{
	char *cp;

	remotefile = cp = conffile ? conffile : _PATH_RTADVDCONF;
	return (getent(bp, name, cp));
}

int
getent(bp, name, cp)
	char *bp, *name, *cp;
{
	int c;
	int i = 0, cnt = 0;
	char ibuf[BUFSIZ];
	int tf;

	tbuf = bp;
	tf = 0;
	/*
	 * TERMCAP can have one of two things in it. It can be the
	 * name of a file to use instead of /etc/termcap. In this
	 * case it better start with a "/". Or it can be an entry to
	 * use so we don't have to read the file. In this case it
	 * has to already have the newlines crunched out.
	 */
	if (cp && *cp) {
		tf = open(RM = cp, O_RDONLY);
	}
	if (tf < 0) {
		syslog(LOG_INFO,
		       "<%s> open: %s", __func__, strerror(errno));
		return (-2);
	}
	for (;;) {
		cp = bp;
		for (;;) {
			if (i == cnt) {
				cnt = read(tf, ibuf, BUFSIZ);
				if (cnt <= 0) {
					close(tf);
					return (0);
				}
				i = 0;
			}
			c = ibuf[i++];
			if (c == '\n') {
				if (cp > bp && cp[-1] == '\\') {
					cp--;
					continue;
				}
				break;
			}
			if (cp >= bp + BUFSIZ) {
				write(2,"Remcap entry too long\n", 23);
				break;
			} else
				*cp++ = c;
		}
		*cp = 0;

		/*
		 * The real work for the match.
		 */
		if (tnamatch(name)) {
			close(tf);
			return (tnchktc());
		}
	}
}

/*
 * tnchktc: check the last entry, see if it's tc=xxx. If so,
 * recursively find xxx and append that entry (minus the names)
 * to take the place of the tc=xxx entry. This allows termcap
 * entries to say "like an HP2621 but doesn't turn on the labels".
 * Note that this works because of the left to right scan.
 */
int
tnchktc()
{
	char *p, *q;
	char tcname[16];	/* name of similar terminal */
	char tcbuf[BUFSIZ];
	char *holdtbuf = tbuf;
	int l;

	p = tbuf + strlen(tbuf) - 2;	/* before the last colon */
	while (*--p != ':')
		if (p < tbuf) {
			write(2, "Bad remcap entry\n", 18);
			return (0);
		}
	p++;
	/* p now points to beginning of last field */
	if (p[0] != 't' || p[1] != 'c')
		return (1);
	strlcpy(tcname, p + 3, sizeof tcname);
	q = tcname;
	while (*q && *q != ':')
		q++;
	*q = 0;
	if (++hopcount > MAXHOP) {
		write(2, "Infinite tc= loop\n", 18);
		return (0);
	}
	if (getent(tcbuf, tcname, remotefile) != 1) {
		return (0);
	}
	for (q = tcbuf; *q++ != ':'; )
		;
	l = p - holdtbuf + strlen(q);
	if (l > BUFSIZ) {
		write(2, "Remcap entry too long\n", 23);
		q[BUFSIZ - (p-holdtbuf)] = 0;
	}
	strcpy(p, q);
	tbuf = holdtbuf;
	return (1);
}

/*
 * Tnamatch deals with name matching.  The first field of the termcap
 * entry is a sequence of names separated by |'s, so we compare
 * against each such name.  The normal : terminator after the last
 * name (before the first field) stops us.
 */
int
tnamatch(np)
	char *np;
{
	char *Np, *Bp;

	Bp = tbuf;
	if (*Bp == '#')
		return (0);
	for (;;) {
		for (Np = np; *Np && *Bp == *Np; Bp++, Np++)
			continue;
		if (*Np == 0 && (*Bp == '|' || *Bp == ':' || *Bp == 0))
			return (1);
		while (*Bp && *Bp != ':' && *Bp != '|')
			Bp++;
		if (*Bp == 0 || *Bp == ':')
			return (0);
		Bp++;
	}
}

/*
 * Skip to the next field.  Notice that this is very dumb, not
 * knowing about \: escapes or any such.  If necessary, :'s can be put
 * into the termcap file in octal.
 */
static char *
tskip(bp)
	char *bp;
{
	int dquote;

	dquote = 0;
	while (*bp) {
		switch (*bp) {
		case ':':
			if (!dquote)
				goto breakbreak;
			else
				bp++;
			break;
		case '\\':
			bp++;
			if (isdigit(*bp)) {
				while (isdigit(*bp++))
					;
			} else
				bp++;
		case '"':
			dquote = (dquote ? 1 : 0);
			bp++;
			break;
		default:
			bp++;
			break;
		}
	}
breakbreak:
	if (*bp == ':')
		bp++;
	return (bp);
}

/*
 * Return the (numeric) option id.
 * Numeric options look like
 *	li#80
 * i.e. the option string is separated from the numeric value by
 * a # character.  If the option is not found we return -1.
 * Note that we handle octal numbers beginning with 0.
 */
int64_t
tgetnum(id)
	char *id;
{
	int64_t i;
	int base;
	char *bp = tbuf;

	for (;;) {
		bp = tskip(bp);
		if (*bp == 0)
			return (-1);
		if (strncmp(bp, id, strlen(id)) != 0)
			continue;
		bp += strlen(id);
		if (*bp == '@')
			return (-1);
		if (*bp != '#')
			continue;
		bp++;
		base = 10;
		if (*bp == '0')
			base = 8;
		i = 0;
		while (isdigit(*bp))
			i *= base, i += *bp++ - '0';
		return (i);
	}
}

#ifdef MIP6
/*
 * return the fraction option id.
 * fraction option looks like:
 *	id#12.345
 * this function take only three places.  hence, the following two
 * are same.
 *	id#12.345
 *	id#12.3456
 */
int64_t
agetusec(id)
	char *id;
{
	int64_t i;
	int64_t j, place;
	char *bp = tbuf;

	for (;;) {
		bp = tskip(bp);
		if (*bp == 0)
			return (-1);
		if (strncmp(bp, id, strlen(id)) != 0)
			continue;
		bp += strlen(id);
		if (*bp == '@')
			return (-1);
		if (*bp != '#')
			continue;
		bp++;
		i = 0;
		j = 0;
		while (isdigit(*bp))
			i *= 10, i += *bp++ - '0';
		if (*bp == '.') {
			bp++;
			place = 1000;
			while (isdigit(*bp) && place > 1)
				place /= 10, j += (*bp++ - '0') * place;
		}
		return (i * 1000 + j);
	}
}
#endif

/*
 * Handle a flag option.
 * Flag options are given "naked", i.e. followed by a : or the end
 * of the buffer.  Return 1 if we find the option, or 0 if it is
 * not given.
 */
int
tgetflag(id)
	char *id;
{
	char *bp = tbuf;

	for (;;) {
		bp = tskip(bp);
		if (!*bp)
			return (0);
		if (strncmp(bp, id, strlen(id)) == 0) {
			bp += strlen(id);
			if (!*bp || *bp == ':')
				return (1);
			else if (*bp == '@')
				return (0);
		}
	}
}

/*
 * Get a string valued option.
 * These are given as
 *	cl=^Z
 * Much decoding is done on the strings, and the strings are
 * placed in area, which is a ref parameter which is updated.
 * No checking on area overflow.
 */
char *
tgetstr(id, area)
	char *id, **area;
{
	char *bp = tbuf;

	for (;;) {
		bp = tskip(bp);
		if (!*bp)
			return (0);
		if (strncmp(bp, id, strlen(id)) != 0)
			continue;
		bp += strlen(id);
		if (*bp == '@')
			return (0);
		if (*bp != '=')
			continue;
		bp++;
		return (tdecode(bp, area));
	}
}

/*
 * Tdecode does the grung work to decode the
 * string capability escapes.
 */
static char *
tdecode(str, area)
	char *str;
	char **area;
{
	char *cp;
	int c;
	char *dp;
	int i;
	char term;

	term = ':';
	cp = *area;
again:
	if (*str == '"') {
		term = '"';
		str++;
	}
	while ((c = *str++) && c != term) {
		switch (c) {

		case '^':
			c = *str++ & 037;
			break;

		case '\\':
			dp = "E\033^^\\\\::n\nr\rt\tb\bf\f\"\"";
			c = *str++;
nextc:
			if (*dp++ == c) {
				c = *dp++;
				break;
			}
			dp++;
			if (*dp)
				goto nextc;
			if (isdigit(c)) {
				c -= '0', i = 2;
				do
					c <<= 3, c |= *str++ - '0';
				while (--i && isdigit(*str));
			}
			break;
		}
		*cp++ = c;
	}
	if (c == term && term != ':') {
		term = ':';
		goto again;
	}
	*cp++ = 0;
	str = *area;
	*area = cp;
	return (str);
}


text:
'use strict';

/**
 * @ngdoc function
 * @name ThemeTestController
 * @module c-3poUI
 * @kind function
 *
 * @description
 *
 * Handles the colors popup dialog
 */
angular.module('c-3poUI').
controller('ThemeTestController', function ($scope, cylonTheming) {
    $scope.themes = cylonTheming.themes;
    $scope.getPalette = cylonTheming.getPalette;
    $scope.rgba = cylonTheming.rgba;
    $scope.intentions = ['md-primary', 'md-accent', 'md-warn'];
    $scope.hues = ['', 'md-hue-1', 'md-hue-2', 'md-hue-3'];

    $scope.materialCSS = 'md-bottom-sheet.md-THEME_NAME-theme {\n    background-color: \'{{background-50}}\';\n    border-top-color: \'{{background-300}}\';\n}';
    $scope.compiledCSS = '';

    for(var t in $scope.themes) {
        $scope.selectedTheme = $scope.themes[t];
        break;
    }

    $scope.parseCSS = function() {
        $scope.compiledCSS = cylonTheming.parseRules($scope.selectedTheme, 'primary', $scope.materialCSS);
    };
});


text:
class SkPicture;

namespace cc {
struct PictureData;

// EnginePictureCache provides functionaltiy for marking when SkPictures are in
// use an when they stop being in use. Based on this, a PictureCacheUpdate can
// be retrieved that includes all the new items since last time it was called.
// This PictureCacheUpdate is then supposed to be sent to the client.
class EnginePictureCache {
 public:
  virtual ~EnginePictureCache() {}

  // MarkUsed must be called when an SkPicture needs to available on the client.
  virtual void MarkUsed(const SkPicture* picture) = 0;

  // Called when a PictureCacheUpdate is going to be sent to the client. This
  // must contain all the new SkPictures that are in use since last call.
  virtual std::vector<PictureData> CalculateCacheUpdateAndFlush() = 0;
};

}  // namespace cc

#endif  // CC_BLIMP_ENGINE_PICTURE_CACHE_H_


text:
<?php namespace Propaganistas\LaravelAuthContext\Tests\Models;

use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model as Eloquent;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticableContract;

class User extends Eloquent implements AuthenticableContract
{

    use Authenticatable;

    protected $table = 'users';

    protected $fillable = array('id', 'name', 'password', 'remember_token');
}


text:
package com.vaadin.tests.util;

import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;

public class Role implements Serializable {
    private String name = "";
    private Set<User> users = new HashSet<User>();

    public Role() {
    }

    public Role(String name) {
        setName(name);
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    /**
     * In this direction, the users for a role can be queried and the returned
     * collection modified, but the whole collection of users cannot be set
     * directly.
     *
     * @return set of users having the role (not null)
     */
    public Set<User> getUsers() {
        return users;
    }

}


text:
#define SOKOL_IMPL
#define SOKOL_NO_ENTRY
#if defined(_WIN32)
#define SOKOL_LOG(s) OutputDebugStringA(s)
#endif
/* sokol 3D-API defines are provided by build options */
#include "sokol_app.h"
#include "sokol_gfx.h"
#include "sokol_time.h"
#include "sokol_audio.h"
#include "sokol_glue.h"


text:
namespace embree
{
  static std::unique_ptr<std::vector<RegressionTest*>> regression_tests;

  void registerRegressionTest(RegressionTest* test)
  {
    if (!regression_tests)
      regression_tests = std::unique_ptr<std::vector<RegressionTest*>>(new std::vector<RegressionTest*>);

    regression_tests->push_back(test);
  }

  RegressionTest* getRegressionTest(size_t index)
  {
    if (!regression_tests)
      return nullptr;

    if (index >= regression_tests->size())
      return nullptr;

    return (*regression_tests)[index];
  }
}


text:
package com.jakespringer.lostexhaust.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import jetbrick.io.IoUtils;

public class Web {
    public static String getRequest(String urlToRead) throws IOException {
        // System.out.println("[GET-REQUEST] Requesting " + urlToRead + ".");

        StringBuilder result = new StringBuilder();
        URL url = new URL(urlToRead);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        try (BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()))) {
            String line;
            while ((line = rd.readLine()) != null) {
                result.append(line);
            }
            rd.close();
            return result.toString();
        }
    }

    public static byte[] getRequestBytes(String urlToRead) throws IOException {
        // System.out.println("[GET-REQUEST] Requesting " + urlToRead + ".");

        URL url = new URL(urlToRead);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        return IoUtils.toByteArray(conn.getInputStream());
    }
}


text:
package db

import (
	"database/sql"
	"errors"
	"fmt"

	. "github.com/polaris1119/config"

	_ "github.com/go-sql-driver/mysql"
	"xorm.io/xorm"
	"xorm.io/xorm/log"
)

var MasterDB *xorm.Engine

var dns string

func init() {
	mysqlConfig, err := ConfigFile.GetSection("mysql")
	if err != nil {
		fmt.Println("get mysql config error:", err)
		return
	}

	fillDns(mysqlConfig)

	// 启动时就打开数据库连接
	if err = initEngine(); err != nil {
		panic(err)
	}

	// 测试数据库连接是否 OK
	if err = MasterDB.Ping(); err != nil {
		panic(err)
	}
}

var (
	ConnectDBErr = errors.New("connect db error")
	UseDBErr     = errors.New("use db error")
)

// TestDB 测试数据库
func TestDB() error {
	mysqlConfig, err := ConfigFile.GetSection("mysql")
	if err != nil {
		fmt.Println("get mysql config error:", err)
		return err
	}

	tmpDns := fmt.Sprintf("%s:%s@tcp(%s:%s)/?charset=%s&parseTime=True&loc=Local",
		mysqlConfig["user"],
		mysqlConfig["password"],
		mysqlConfig["host"],
		mysqlConfig["port"],
		mysqlConfig["charset"])
	egnine, err := xorm.NewEngine("mysql", tmpDns)
	if err != nil {
		fmt.Println("new engine error:", err)
		return err
	}
	defer egnine.Close()

	// 测试数据库连接是否 OK
	if err = egnine.Ping(); err != nil {
		fmt.Println("ping db error:", err)
		return ConnectDBErr
	}

	_, err = egnine.Exec("use " + mysqlConfig["dbname"])
	if err != nil {
		fmt.Println("use db error:", err)
		_, err = egnine.Exec("CREATE DATABASE " + mysqlConfig["dbname"] + " DEFAULT CHARACTER SET " + mysqlConfig["charset"])
		if err != nil {
			fmt.Println("create database error:", err)

			return UseDBErr
		}

		fmt.Println("create database successfully!")
	}

	// 初始化 MasterDB
	return Init()
}

func Init() error {
	mysqlConfig, err := ConfigFile.GetSection("mysql")
	if err != nil {
		fmt.Println("get mysql config error:", err)
		return err
	}

	fillDns(mysqlConfig)

	// 启动时就打开数据库连接
	if err = initEngine(); err != nil {
		fmt.Println("mysql is not open:", err)
		return err
	}

	return nil
}

func fillDns(mysqlConfig map[string]string) {
	dns = fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=%s&parseTime=True&loc=Local",
		mysqlConfig["user"],
		mysqlConfig["password"],
		mysqlConfig["host"],
		mysqlConfig["port"],
		mysqlConfig["dbname"],
		mysqlConfig["charset"])
}

func initEngine() error {
	var err error

	MasterDB, err = xorm.NewEngine("mysql", dns)
	if err != nil {
		return err
	}

	maxIdle := ConfigFile.MustInt("mysql", "max_idle", 2)
	maxConn := ConfigFile.MustInt("mysql", "max_conn", 10)

	MasterDB.SetMaxIdleConns(maxIdle)
	MasterDB.SetMaxOpenConns(maxConn)

	showSQL := ConfigFile.MustBool("xorm", "show_sql", false)
	logLevel := ConfigFile.MustInt("xorm", "log_level", 1)

	MasterDB.ShowSQL(showSQL)
	MasterDB.Logger().SetLevel(log.LogLevel(logLevel))

	// 启用缓存
	// cacher := xorm.NewLRUCacher(xorm.NewMemoryStore(), 1000)
	// MasterDB.SetDefaultCacher(cacher)

	return nil
}

func StdMasterDB() *sql.DB {
	return MasterDB.DB().DB
}


text:
from PyQt4.QtCore import *
from PyQt4.QtGui import *
import PyQt4.QtGui
MAC = hasattr(PyQt4.QtGui, "qt_mac_set_native_menubar")
import about_dialog

class AboutDlg(QDialog,
        about_dialog.Ui_about_dialog):

    def __init__(self, parent=None):
        super(AboutDlg, self).__init__(parent)
        self.setupUi(self)
        if not MAC:
            self.buttonBox.setFocusPolicy(Qt.NoFocus)

if __name__ == "__main__":
    import sys

    app = QApplication(sys.argv)
    form = AboutDlg()
    form.show()
    app.exec_()


text:
@interface PlaySoundUtil : NSObject
+ (void)playSound:(NSString *)soundName callback:(void (^)())callback;

+ (void)playSound:(NSString *)soundName extension:(NSString *)extension callback:(void (^)())callback;

@end


text:
import {RegressionResult} from './regression-result';
import {RegressionResultStatus} from './regression-result-status.enum';

export class RegressionResultSet {

    private static DEFAULT_SUCCESS_STATUS_CODE: number = 200;

    private _violations: RegressionResult[] = [];
    private _passed: RegressionResult[] = [];
    private _errors: RegressionResult[] = [];

    public addResults(results: RegressionResult[]): this {
        results.forEach(this.addResult, this);
        return this;
    }

    public addResult(result: RegressionResult): this {
        switch (result.status) {
            case RegressionResultStatus.VIOLATION:
                this._violations.push(result);
                return this;
            case RegressionResultStatus.SUCCESS:
                this._passed.push(result);
                return this;
            case RegressionResultStatus.ERROR:
                this._errors.push(result);
                return this;
            default:
                throw new Error(`Unknown RegressionResultStatus: ${result.status}`);
        }
    }

    get hasViolations(): boolean {
        return this._violations.length > 0;
    }

    get violations(): RegressionResult[] {
        return this._violations;
    }

    get passed(): RegressionResult[] {
        return this._passed;
    }

    get hasErrors(): boolean {
        return this._errors.length > 0;
    }

    get errors(): RegressionResult[] {
        return this._errors;
    }
}


text:
package com.yeonjukko.teamplebox.TeampleBox.Calendar.search;

import java.util.List;

public interface OnFinishSearchListener {
	public void onSuccess(List<Item> itemList);
	public void onFail();
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE module PUBLIC "-//NetBeans//DTD Module Status 1.0//EN"
                        "http://www.netbeans.org/dtds/module-status-1_0.dtd">
<module name="org.netbeans.modules.spellchecker.dictionary_en">
    <param name="autoload">false</param>
    <param name="eager">false</param>
    <param name="enabled">true</param>
    <param name="jar">modules/org-netbeans-modules-spellchecker-dictionary_en.jar</param>
    <param name="reloadable">false</param>
</module>


text:
module A {
    export interface Point {
        x: number;
        y: number;
    }

    interface Point3d extends Point {
        z: number;
    }
}

module B {
    export class Line {
        constructor(public start: A.Point, public end: A.Point) { }
    }
}

module Geometry {
    export import Points = A;
    import Lines = B;

    export var Origin: Points.Point = { x: 0, y: 0 };

    // this is valid since B.Line _is_ visible outside Geometry
    export var Unit: Lines.Line = new Lines.Line(Origin, { x: 1, y: 0 });
}

// expected to work since all are exported
var p: { x: number; y: number };
var p: Geometry.Points.Point;
var p = Geometry.Origin;

var line: { start: { x: number; y: number }; end: { x: number; y: number; } };
var line = Geometry.Unit;

// not expected to work since non are exported
var line = Geometry.Lines.Line;

//// [ModuleWithExportedAndNonExportedImportAlias.js]
var B;
(function (B) {
    var Line = (function () {
        function Line(start, end) {
            this.start = start;
            this.end = end;
        }
        return Line;
    })();
    B.Line = Line;
})(B || (B = {}));
var Geometry;
(function (Geometry) {
    var Lines = B;
    Geometry.Origin = { x: 0, y: 0 };
    // this is valid since B.Line _is_ visible outside Geometry
    Geometry.Unit = new Lines.Line(Geometry.Origin, { x: 1, y: 0 });
})(Geometry || (Geometry = {}));
// expected to work since all are exported
var p;
var p;
var p = Geometry.Origin;
var line;
var line = Geometry.Unit;
// not expected to work since non are exported
var line = Geometry.Lines.Line;


text:
#import <UIKit/UIKit.h>

@interface SceneDelegate : UIResponder <UIWindowSceneDelegate>

@property(strong, nonatomic) UIWindow* window;

@end


text:
package org.mifos.application.master.persistence;

import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import org.mifos.framework.exceptions.SystemException;
import org.mifos.framework.persistence.Upgrade;

/*
 * Upgrade169 is an upgrade that cleans up remaining custom field related
 * entries, sets all label text in the database to null so that these
 * labels can serve as overrides for properties file based localized
 * labels, and introduces a locale for Spanish and French.
 */
public class Upgrade169 extends Upgrade {

    public Upgrade169() {
        super(169);
    }

    private short getLookupIdForSupporteLanguageId(Connection connection, int languageId) throws SQLException {

        short lookupId = 0;
        Statement statement = connection.createStatement();
        try {
            ResultSet results = statement.executeQuery("select LOOKUP_ID from LANGUAGE where LANG_ID = " + languageId);
            if (!results.next()) {
                throw new SystemException(SystemException.DEFAULT_KEY, "Query failed on table LANGUAGE for LANG_ID: "
                        + languageId);
            }
            lookupId = results.getShort(1);

        } finally {
            statement.close();
        }
        return lookupId;

    }

    @Override
    public void upgrade(Connection connection)
            throws IOException, SQLException {
        execute(connection, "DELETE FROM PERSONNEL_CUSTOM_FIELD WHERE PERSONNEL_ID = 1");
        /* Clean up unused custom field entities and labels */
        execute(connection, "DELETE FROM  LOOKUP_LABEL WHERE LABEL_ID = 61 AND ENTITY_NAME = \'CustomField1\'");
        execute(connection, "DELETE FROM  LOOKUP_LABEL WHERE LABEL_ID = 63 AND ENTITY_NAME = \'CustomField2\'");
        execute(connection, "DELETE FROM  LOOKUP_LABEL WHERE LABEL_ID = 65 AND ENTITY_NAME = \'CustomField3\'");

        execute(connection,
                "DELETE FROM  LOOKUP_VALUE_LOCALE WHERE LOOKUP_VALUE_ID = 123 AND LOOKUP_VALUE = \'CustomField1\'");
        execute(connection,
                "DELETE FROM  LOOKUP_VALUE_LOCALE WHERE LOOKUP_VALUE_ID = 125 AND LOOKUP_VALUE = \'CustomField2\'");
        execute(connection,
                "DELETE FROM  LOOKUP_VALUE_LOCALE WHERE LOOKUP_VALUE_ID = 127 AND LOOKUP_VALUE = \'CustomField3\'");

        execute(connection, "DELETE FROM  LOOKUP_VALUE WHERE LOOKUP_ID = 62 AND ENTITY_ID = 31");
        execute(connection, "DELETE FROM  LOOKUP_VALUE WHERE LOOKUP_ID = 63 AND ENTITY_ID = 32");
        execute(connection, "DELETE FROM  LOOKUP_VALUE WHERE LOOKUP_ID = 64 AND ENTITY_ID = 33");

        execute(connection,
                "DELETE FROM  LOOKUP_ENTITY WHERE ENTITY_ID = 31 AND ENTITY_NAME = \'PersonnelCustomField1\'");
        execute(connection,
                "DELETE FROM  LOOKUP_ENTITY WHERE ENTITY_ID = 32 AND ENTITY_NAME = \'PersonnelCustomField2\'");
        execute(connection,
                "DELETE FROM  LOOKUP_ENTITY WHERE ENTITY_ID = 33 AND ENTITY_NAME = \'PersonnelCustomField3\'");

        /*
         * set all lookup labels to be null so that text will come from resource
         * bundles
         */
        execute(connection, "UPDATE LOOKUP_LABEL SET ENTITY_NAME = NULL");

        /* Spanish locale support */
        execute(connection,
                "INSERT INTO COUNTRY(COUNTRY_ID,COUNTRY_NAME,COUNTRY_SHORT_NAME) VALUES(8,\'Spain\',\'ES\')");
        int lookup_id = insertLookupValue(connection, 74);
        execute(connection,
                "INSERT INTO LANGUAGE(LANG_ID,LANG_NAME,LANG_SHORT_NAME,LOOKUP_ID) VALUES(3,\'Spanish\',\'es\',"
                        + lookup_id + ")");
        execute(connection,
                "INSERT INTO SUPPORTED_LOCALE(LOCALE_ID,COUNTRY_ID,LANG_ID,LOCALE_NAME,DEFAULT_LOCALE) VALUES(3,8,3,\'Spanish\',0)");

        /* French locale support */
        execute(connection,
                "INSERT INTO COUNTRY(COUNTRY_ID,COUNTRY_NAME,COUNTRY_SHORT_NAME) VALUES(9,\'France\',\'FR\')");
        lookup_id = insertLookupValue(connection, 74);
        execute(connection,
                "INSERT INTO LANGUAGE(LANG_ID,LANG_NAME,LANG_SHORT_NAME,LOOKUP_ID) VALUES(4,\'French\',\'fr\',"
                        + lookup_id + ")");
        execute(connection,
                "INSERT INTO SUPPORTED_LOCALE(LOCALE_ID,COUNTRY_ID,LANG_ID,LOCALE_NAME,DEFAULT_LOCALE) VALUES(4,9,4,\'French\',0)");

        upgradeVersion(connection);
    }

}


text:
package ru.vryazanov.tasks5;

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

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;

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

/**
 * Test for class  NewIterator.
 *
 * @author vryazanov
 * @version 1.0
 * @since 02.04.2017
 */
public class NewIteratorTest {
    /**
     * Store iterator for testing.
     */
    private Iterator<Integer> iterator;
    /**
     * Before each test preparing iterator.
     */
    @Before
    public void setUp() {
        ArrayList<Integer> list1 = new ArrayList<Integer>(Arrays.asList(2, 3));
        ArrayList<Integer> list2 = new ArrayList<Integer>(Arrays.asList(1, 3));
        Iterator<Integer> it3 = list1.iterator();
        Iterator<Integer> it4 = list2.iterator();
        List<Iterator<Integer>> iteratorList = new ArrayList<Iterator<Integer>>(Arrays.asList(it3, it4));
        Iterator<Iterator<Integer>> iteratorIterator = iteratorList.iterator();
        NewIterator newIterator = new NewIterator();
        iterator = newIterator.convert(iteratorIterator);
    }
    /**
     * If Get Next Call There Is Next Iterator should Pointer Forward.
     */
    @Test
    public void whenGetNextCallAndThereIsNextIteratorShouldPointerForward() {
        iterator.next();
        iterator.next();
        int result = (Integer) iterator.next();

        assertThat(result, is(1));
    }
    /**
     * If Check Next Position And Have Next Iterator.
     */
    @Test
    public void whenCheckNextPositionAndHaveNextIteratorShouldReturnConstantValue() {

        iterator.next();
        iterator.next();
        iterator.hasNext();
        boolean result = iterator.hasNext();

        assertThat(result, is(true));
    }
    /**
     * If Check Next Position And Have No Next Iterator.
     */
    @Test
    public void whenCheckNextPositionAndHaveNoNextIteratorShouldReturnConstantValue() {

        iterator.next();
        iterator.next();
        iterator.next();
        iterator.next();
        iterator.hasNext();
        boolean result = iterator.hasNext();

        assertThat(result, is(false));
    }
    /**
     * If Get Next Call And There No Next Iterator.
     */
    @Test(expected = NoSuchElementException.class)
    public void whenGetNextCallAndThereNoNextIteratorShouldReturnError() {

        iterator.next();
        iterator.next();
        iterator.next();
        iterator.next();
        iterator.next();

    }

}


text:
<?php

class Wechatcooksign {
	private $app_id;
	private $app_secret;
	private $lib_path;

	public function __construct($appid, $appsecret,$libpath='./'){
		$this->app_id = $appid;
		$this->app_secret = $appsecret;
		$this->lib_path = dirname(__FILE__) . '/'	;
		// $this->nonce_str = NONCE_STR;

		$this->logit($this->app_id);
	}

	private function httpGet($url) {
		$curl = curl_init();
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($curl, CURLOPT_TIMEOUT, 500);
		curl_setopt($curl, CURLOPT_URL, $url);

		$res = curl_exec($curl);
		curl_close($curl);

		return $res;
	}

	//签名算法
	public function get_sign(){
		$jsapi_ticket = $this->get_jsapi_ticket();
		$url = "http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
		$timestamp = time();
		$nonceStr = $this->get_rand_str();
		 // 这里参数的顺序要按照 key 值 ASCII 码升序排序
		$string = "jsapi_ticket=$jsapi_ticket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";

		$signature = sha1($string);

		$signPackage = array(
			"appId"     => $this->app_id,
			"nonceStr"  => $nonceStr,
			"timestamp" => $timestamp,
			"url"       => $url,
			"signature" => $signature,
			"rawString" => $string,
			'jsapi_ticket'=>$jsapi_ticket,
			'string'	=> $string,

		);
		return $signPackage;
	}

	public function get_access_token(){
		//获取本地存储数据。如果已经过期,重新读取
		$this->logit('get_access_token');

		$store_file = $this->lib_path .'access_token.json';
		$data = json_decode( file_get_contents($store_file) );
		if( $data->expire_time < time() ){
			$this->logit('---------begin----get_access_token----------');
			$url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$this->app_id.'&secret='.$this->app_secret;
			$this->logit($url);

			// $res = json_decode($this->httpGet($url));
			$res = json_decode(file_get_contents($url), true);
			$this->logit('---------resssss----get_access_token----------');
			$this->logit($res['access_token']);
			$this->logit('---------getit----get_access_token----------');

			$access_token = $res['access_token'];
			$this->logit('---------'.$access_token.'----get_access_token----------');
			if($access_token){
				$data->expire_time = time()+ intval($res['expires_in']);
				$data->access_token = $access_token;
				file_put_contents($store_file, json_encode($data));
				$this->logit('---------finish write----get_access_token----------');
			}else{
				//未成功获取到
			}

		}else{
			$this->logit('---------no----get_access_token----------');
			$access_token = $data->access_token;
		}
		return $access_token ;

	}

	public function get_jsapi_ticket(){
		$access_token = $this->get_access_token();

		$store_file = $this->lib_path.'jsapi_ticket.json';
		$data = json_decode( file_get_contents($store_file) );
		if( $data->expire_time < time() ){
			$url = 'https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token='.$access_token.'&type=jsapi';
			$res = json_decode( $this->httpGet($url) );
			$jsapi_ticket = $res->ticket;
			if($jsapi_ticket){
				$data->ticket = $jsapi_ticket;
				$data->expire_time = time() + intval($res->expires_in);

				file_put_contents($store_file, json_encode($data));
			}
		}else{
			$jsapi_ticket = $data->ticket;
		}

		return $jsapi_ticket;

	}

	public function get_rand_str($length=16){
		$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
	    $str = "";
	    for ($i = 0; $i < $length; $i++) {
	      $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
	    }
	    return $str;
	}

	function logit($str){
		$path = $this->libpath.date('mdH').'.log';
		$str .= "\t". date('H:i:s')."\n";
		file_put_contents($path, $str, FILE_APPEND);
	}
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace F23Bag.Data
{
    [AttributeUsage(AttributeTargets.Property)]
    public class DontExtractStateAttribute : Attribute
    {
    }
}


text:
<?php

namespace perf\FileSystem;

/**
 *
 *
 */
class FileSystemClient
{

    /**
     *
     *
     * @var FileSystemWrapper
     */
    private $wrapper;

    /**
     * Static constructor.
     *
     * @return FileSystemClient
     */
    public static function createDefault()
    {
        return new self(new FileSystemWrapper());
    }

    /**
     * Constructor.
     *
     * @param FileSystemWrapper $wrapper
     */
    public function __construct(FileSystemWrapper $wrapper)
    {
        $this->wrapper = $wrapper;
    }

    /**
     *
     *
     * @param string $path
     * @return bool
     */
    public function fileExists($path)
    {
        return $this->wrapper->fileExists($path);
    }

    /**
     *
     *
     * @param string $path
     * @return int
     * @throws \RuntimeException
     */
    public function fileSize($path)
    {
        $size = $this->wrapper->fileSize($path);

        if (false === $size) {
            throw new \RuntimeException("Failed to get size of file at '{$path}'.");
        }

        return $size;
    }

    /**
     *
     *
     * @param string $path
     * @return bool
     */
    public function isDirectory($path)
    {
        return $this->wrapper->isDirectory($path);
    }

    /**
     *
     *
     * @param string $path
     * @return bool
     */
    public function isFile($path)
    {
        return $this->wrapper->isFile($path);
    }

    /**
     *
     *
     * @param string $path
     * @return bool
     */
    public function isLink($path)
    {
        return $this->wrapper->isLink($path);
    }

    /**
     *
     *
     * @param string $path
     * @return bool
     */
    public function isReadable($path)
    {
        return $this->wrapper->isReadable($path);
    }

    /**
     *
     *
     * @param string $path
     * @return bool
     */
    public function isWritable($path)
    {
        return $this->wrapper->isWritable($path);
    }

    /**
     *
     *
     * @param string $path
     * @return void
     * @throws \RuntimeException
     */
    public function makeDirectory($path)
    {
        if (!$this->wrapper->makeDirectory($path)) {
            throw new \RuntimeException("Failed to make directory '{$path}'.");
        }
    }

    /**
     *
     *
     * @param string $path
     * @return void
     * @throws \RuntimeException
     */
    public function removeDirectory($path)
    {
        if (!$this->wrapper->removeDirectory($path)) {
            throw new \RuntimeException("Failed to remove directory '{$path}'.");
        }
    }

    /**
     *
     *
     * @param string $path
     * @param int    $mode
     * @return void
     * @throws \RuntimeException
     */
    public function changeMode($path, $mode)
    {
        if (!$this->wrapper->changeMode($path, $mode)) {
            throw new \RuntimeException("Failed to change mode of '{$path}' to '{$mode}'.");
        }
    }

    /**
     *
     *
     * @param string $path
     * @param string $content
     * @param int    $flags
     * @throws \RuntimeException
     */
    public function putContent($path, $content, $flags = 0)
    {
        if (!$this->wrapper->putContent($path, $content, $flags)) {
            throw new \RuntimeException("Failed to put file content at '{$path}'.");
        }
    }

    /**
     *
     *
     * @param string $path
     * @param int    $flags
     * @return string
     * @throws \RuntimeException
     */
    public function getContent($path, $flags = 0)
    {
        $content = $this->wrapper->getContent($path, $flags);

        if (false === $content) {
            throw new \RuntimeException("Failed to get file content at '{$path}'.");
        }

        return $content;
    }

    /**
     *
     *
     * @param string $oldPath
     * @param string $newPath
     * @return void
     * @throws \RuntimeException
     */
    public function rename($oldPath, $newPath)
    {
        if (!$this->wrapper->rename($oldPath, $newPath)) {
            throw new \RuntimeException("Failed to rename file from '{$oldPath}' to '{$newPath}'.");
        }
    }

    /**
     *
     *
     * @param string $sourcePath
     * @param string $destinationPath
     * @return void
     * @throws \RuntimeException
     */
    public function copy($sourcePath, $destinationPath)
    {
        if (!$this->wrapper->copy($sourcePath, $destinationPath)) {
            throw new \RuntimeException("Failed to copy file from '{$sourcePath}' to '{$destinationPath}'.");
        }
    }

    /**
     *
     *
     * @param string $path
     * @return void
     * @throws \RuntimeException
     */
    public function delete($path)
    {
        if (!$this->wrapper->delete($path)) {
            throw new \RuntimeException("Failed to delete file '{$path}'.");
        }
    }

    /**
     *
     *
     * @param string $path
     * @return bool
     */
    public function isUploadedFile($path)
    {
        return $this->wrapper->isUploadedFile($path);
    }

    /**
     *
     *
     * @param string $sourcePath
     * @param string $destinationPath
     * @return void
     * @throws \RuntimeException
     */
    public function moveUploadedFile($sourcePath, $destinationPath)
    {
        if (!$this->wrapper->moveUploadedFile($sourcePath, $destinationPath)) {
            throw new \RuntimeException("Failed to move uploaded file from '{$sourcePath}' to '{$destinationPath}'.");
        }
    }
}


text:
package org.iotivity.test.ic.app;

import java.util.HashMap;
import java.util.Map;

import org.iotivity.base.OcPlatform;
import org.iotivity.base.OcResource;
import org.iotivity.base.QualityOfService;

public interface ICUtility {
    public final String              TAG                      = "ICTestApp";
    public final Map<String, String> MY_MAP                   = new HashMap<String, String>() {
                                                                  {
                                                                      put("a", "b");
                                                                  }
                                                              };
    public static String              IC_HOST_ADDRESS          = "coap+tcp://192.168.43.174:5683";
    public final String              MQ_BROKER_URI            = "/oic/ps";
    public final QualityOfService    IC_OC_QUALITY_OF_SERVICE = QualityOfService.LOW;
    public final String              DEFAULT_AUTH_PROVIDER    = "github";
    public final String              MQ_DEFAULT_TOPIC_URI     = "/oic/ps/cleanroom";
    public final String              Resource_URI             = "/a/light";
    public final String              RESOURCE_TYPE            = "core.light";
    public final String              RESOURCE_INTERFACE       = OcPlatform.DEFAULT_INTERFACE;
    public final int                 TIMEOUT                  = 5000;
}


text:
module Sidebar {

  export var _module = angular.module(pluginName, ['duScroll']);

  _module.directive('hawkularSidebar', function () {
    return new Sidebar.SidebarDirective();
  });

  hawtioPluginLoader.addModule(pluginName);
}


text:
<?php

namespace App\Modules\Nucleo\Controllers;

use App\Modules\Nucleo\Models\UsersGroups;
use App\Shared\Controllers\ControllerBase;

class UsersGroupsController extends ControllerBase {

    /**
     * initialize
     */
    public function initialize() {
        $this->tag->setTitle(' Grupos x Usuários ');
        parent::initialize();

        $this->entity = new UsersGroups();
    }

    /**
     * Index action
     */
    public function indexAction() {
        try {
            $this->view->users_groups = UsersGroups::find();
            $this->view->pesquisa = '';

            if ($this->request->isPost()) {

                $users = $this->request->getPost('userId', 'int');
                $groups = $this->request->getPost('groupId', 'int');

                $search = '1 = 1 ';
                if (!empty($this->request->getPost('userId'))) {
                    $search .= " AND UPPER(userId) LIKE UPPER('%{$users}%') ";
                }
                if (!empty($this->request->getPost('groupId'))) {
                    $search .= " AND UPPER(groupId) LIKE UPPER('%{$groups}%') ";
                }

                $this->view->users_groups = UsersGroups::find($search);
                $this->view->pesquisa = 'Usuários: ' . $users . ' | Grupos: ' . $groups;
            }
        } catch (Exception $e) {
            $this->flash->error($e->getMessage());
        }
    }

    /**
     * Displays the creation form
     */
    public function newAction() {

    }

    /**
     * Edits a users_group
     *
     * @param string $id
     */
    public function editAction($id) {
        try {

            if ($this->request->isPost()) {
                throw new Exception('Acesso inválido a essa action!!!');
            }

            $users_group = UsersGroups::findFirstByid($id);
            if (!$users_group) {
                throw new Exception('Grupo x Usuário não encontrado!');
            }

            $this->view->id = $users_group->id;

            $this->tag->setDefault('id', $users_group->getId());
            $this->tag->setDefault('userId', $users_group->getUserId());
            $this->tag->setDefault('groupId', $users_group->getGroupId());
        } catch (Exception $e) {
            $this->flash->error($e->getMessage());
            return $this->response->redirect('nucleo/users_groups');
        }
    }

    /**
     * Creates a new users_group
     */
    public function createAction() {

        try {

            if (!$this->request->isPost()) {
                throw new Exception('Acesso não permitido a essa action.');
            }

            $users_group = new UsersGroups();

            $users_group->setId($users_group->autoincrement());
            $users_group->setUserId($this->request->getPost('userId'));
            $users_group->setGroupId($this->request->getPost('groupId'));

            if (!$users_group->create()) {
                $msg = '';
                foreach ($users_group->getMessages() as $message) {
                    $msg .= $message . '
';
                }
                throw new Exception($msg);
            }

            $this->flash->success('Grupo x Usuário gravado com sucesso!!!');
        } catch (Exception $e) {
            $this->flash->error($e->getMessage());
        }
        return $this->response->redirect('nucleo/users_groups');
    }

    /**
     * Saves a users_group edited
     *
     */
    public function saveAction() {

        try {

            if (!$this->request->isPost()) {
                throw new Exception('Acesso não permitido a essa action.');
            }

            $id = $this->request->getPost('id');

            $users_group = UsersGroups::findFirstByid($id);
            if (!$users_group) {
                throw new Exception('Grupo x Usuário não encontrado!');
            }

            $users_group->setId($this->request->getPost('id'));
            $users_group->setUserId($this->request->getPost('userId'));
            $users_group->setGroupId($this->request->getPost('groupId'));

            if (!$users_group->update()) {

                $msg = '';
                foreach ($users_group->getMessages() as $message) {
                    $msg .= $message . '
';
                }
                throw new Exception($msg);
            }

            $this->flash->success('Grupo x Usuário atualizado com sucesso!!!');
        } catch (Exception $e) {
            $this->flash->error($e->getMessage());
        }
        return $this->response->redirect('nucleo/users_groups');
    }

    /**
     * Deletes a users_group
     *
     * @param string $id
     */
    public function deleteAction() {

        try {
            if (!$this->request->isPost()) {
                throw new Exception('Acesso não permitido a essa action.');
            }

            if ($this->request->isAjax()) {
                $this->view->disable();
            }

            $id = $this->request->getPost('id');

            $users_group = UsersGroups::findFirstByid($id);
            if (!$users_group) {
                throw new Exception('Grupo x Usuário não encontrado!');
            }

            if (!$users_group->delete()) {

                $msg = '';
                foreach ($users_group->getMessages() as $message) {
                    $msg .= $message . '
';
                }
                throw new Exception($msg);
            }
            echo 'ok';
        } catch (Exception $e) {
            $this->flash->error($e->getMessage());
            return $this->response->redirect('nucleo/users_groups');
        }
    }

}


text:
package org.activiti.engine.impl.bpmn.parser;

import java.io.Serializable;

/**

 */
public class CompensateEventDefinition implements Serializable {

  protected String activityRef;
  protected boolean waitForCompletion;

  public String getActivityRef() {
    return activityRef;
  }

  public void setActivityRef(String activityRef) {
    this.activityRef = activityRef;
  }

  public boolean isWaitForCompletion() {
    return waitForCompletion;
  }

  public void setWaitForCompletion(boolean waitForCompletion) {
    this.waitForCompletion = waitForCompletion;
  }

}


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

    <artifactId>Bean-Validation-2-0</artifactId>

    <dependencies>
        <dependency>
            <groupId>org.hibernate.validator</groupId>
            <artifactId>hibernate-validator</artifactId>
            <version>6.0.7.Final</version>
        </dependency>
        <dependency>
            <groupId>org.glassfish</groupId>
            <artifactId>javax.el</artifactId>
            <version>3.0.1-b09</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate.validator</groupId>
            <artifactId>hibernate-validator-cdi</artifactId>
            <version>6.0.7.Final</version>
        </dependency>
    </dependencies>

    <build>
        <finalName>Bean-Validation-2-0</finalName>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>${maven-compiler-plugin.version}</version>
                <configuration>
                    <source>${java.version}</source>
                    <target>${java.version}</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>


text:
import time
import uuid

from groundstation.proto.gizmo_pb2 import Gizmo
import groundstation.transfer.response
import groundstation.deferred

from groundstation.transfer import request_handlers

from groundstation import settings
from groundstation import logger
log = logger.getLogger(__name__)

def TERMINATE(self):
    terminate = self._Response(self.id, "TERMINATE", None)
    self.stream.enqueue(terminate)

class InvalidRequest(Exception):
    pass

class Request(object):
    VALID_REQUESTS = {
            "LISTALLOBJECTS": request_handlers.handle_listallobjects,
            "FETCHOBJECT": request_handlers.handle_fetchobject,
            "LISTALLCHANNELS": request_handlers.handle_listallchannels,
            "LISTDBHASH": request_handlers.handle_listdbhash
    }

    def __init__(self, verb, station=None, stream=None, payload=None, origin=None, remoteId=None):
        self.type = "REQUEST"
        self.id = remoteId or uuid.uuid1()
        self.verb = verb
        self.station = station
        self.stream = stream
        self.payload = payload
        # if origin:
        #     self.origin = uuid.UUID(origin)
        self.origin = origin
        self.validate()

    def _Response(self, *args, **kwargs):
        kwargs['station'] = self.station
        return groundstation.transfer.response.Response(*args, **kwargs)

    @classmethod
    def from_gizmo(klass, gizmo, station, stream):
        log.debug("Hydrating a request from gizmo")
        return klass(gizmo.verb, station, stream, gizmo.payload, gizmo.stationid, remoteId=gizmo.id)

    def SerializeToString(self):
        gizmo = self.station.gizmo_factory.gizmo()
        gizmo.id = str(self.id)
        gizmo.type = Gizmo.REQUEST
        gizmo.verb = self.verb
        if self.payload:
            gizmo.payload = self.payload
        return gizmo.SerializeToString()

    def validate(self):
        if self.verb not in self.VALID_REQUESTS:
            raise Exception("Invalid Request: %s" % (self.verb))

    def process(self):
        self.VALID_REQUESTS[self.verb](self)

    def TERMINATE(self):
        TERMINATE(self)

    def teardown(self):
        """Stub method for cleaning up after a request"""
        if self.verb == "LISTALLOBJECTS":
            log.info("LISTALLOBJECTS teardown called")
            listchannels = groundstation.transfer.request.Request("LISTALLCHANNELS", station=self.station)
            self.station.register_request(listchannels)
            self.stream.enqueue(listchannels)
            log.info("Registering deferred to check sync")

            @groundstation.deferred.defer_until(time.time() + settings.DEFAULT_CACHE_LIFETIME)
            def deferred():
                listobjects = groundstation.transfer.request.Request("LISTALLOBJECTS", station=self.station)
                self.station.register_request(listobjects)
            self.station.register_deferred(deferred)

    # Boilerplate to appease protobuf
    @property
    def payload(self):
        return self._payload
    @payload.setter
    def payload(self, value):
        self._payload = str(value)


text:
function LastFMClient(options) {
    this.apiKey = options.apiKey || console.error('LastFMClient: apiKey is required');
    this.apiSecret = options.apiSecret || console.error('LastFMClient: apiSecret is required');
    this.apiUrl = options.apiUrl || 'http://ws.audioscrobbler.com/2.0/';
}

LastFMClient.prototype._getApiSignature = function(data) {
    var keys = Object.keys(data).sort();
    var nameValueString = keys.reduce(function(prev, key) {
        return prev + key + data[key];
    }, '');
    return md5(nameValueString + this.apiSecret);
};

LastFMClient.prototype._call = function(type, data, successCallback, errorCallback, context, async) {
    var originalErrorCallback = errorCallback;
    errorCallback = function(response) {
        // sometimes last.fm does not specify application/json in content-type
        // let's try to parse JSON manually
        if (response instanceof XMLHttpRequest) {
            try {
                response = JSON.parse(response.responseText);
            } catch (e) {
            }
        }
        console.error('Something went wrong:', response);
        if (originalErrorCallback) {
            originalErrorCallback.call(this, response);
        }
    };

    var originalSuccessCallback = successCallback;
    successCallback = function(response) {
        // sometimes last.fm does not specify application/json in content-type,
        // let's try to parse JSON manually
        if (response instanceof XMLHttpRequest) {
            try {
                response = JSON.parse(response.responseText);
            } catch (e) {
            }
        }
        // sometimes last.fm returns errors with 2xx codes
        if (response.error) {
            errorCallback.call(this, response);
        } else {
            if (originalSuccessCallback) {
                originalSuccessCallback.call(this, response);
            }
        }
    };

    data.format = 'json';

    $.ajax({
        type: type,
        url: this.apiUrl,
        data: data,
        dataType: 'json',
        async: async,
        success: context ? successCallback.bind(context) : successCallback,
        error: context ? errorCallback.bind(context) : errorCallback
    });
};

LastFMClient.prototype._signedCall = function(type, data, callback, errorCallback, deauthCallback, context, async) {
    data.api_key = this.apiKey;
    data.api_sig = this._getApiSignature(data);

    var originalErrorCallback = errorCallback;
    errorCallback = function(response) {
        if (response instanceof XMLHttpRequest) {
            try {
                response = JSON.parse(response.responseText);
            } catch (e) {
            }
        }
        var AUTHENTICATION_FAILED = 4;  // Authentication Failed - You do not have permissions to access the service
        var INVALID_SESSION_KEY = 9;  // Invalid session key - Please re-authenticate
        var UNAUTHORIZED_TOKEN = 14;  // Unauthorized Token - This token has not been authorized
        if (response.error == AUTHENTICATION_FAILED ||
            response.error == INVALID_SESSION_KEY ||
            response.error == UNAUTHORIZED_TOKEN) {
            if (deauthCallback) {
                deauthCallback.call(this, response);
            }
        }
        if (originalErrorCallback) {
            originalErrorCallback.call(this, response);
        }
    };

    this._call(type, data, callback, errorCallback, context, async);
};

LastFMClient.prototype.synchronousSignedCall = function(type, data, callback, errorCallback, deauthCallback, context) {
    this._signedCall(type, data, callback, errorCallback, deauthCallback, context, false);
};

LastFMClient.prototype.signedCall = function(type, data, callback, errorCallback, deauthCallback, context) {
    this._signedCall(type, data, callback, errorCallback, deauthCallback, context, true);
};

LastFMClient.prototype.unsignedCall = function(type, data, callback, errorCallback, context) {
    data.api_key = this.apiKey;
    this._call(type, data, callback, errorCallback, context, true);
};


text:
"""
    Artificial Intelligence for Humans
    Volume 3: Deep Learning and Neural Networks
    Python Version
    http://www.aifh.org
    http://www.jeffheaton.com
    Code repository:
    https://github.com/jeffheaton/aifh
    Copyright 2015 by Jeff Heaton
    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at
        http://www.apache.org/licenses/LICENSE-2.0
    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
    For more information on Heaton Research copyrights, licenses
    and trademarks visit:
    http://www.heatonresearch.com/copyright
"""
import lasagne
from lib.aifh.mnist import *
import theano
import theano.tensor as T
import time
import types
from lasagne.layers import DenseLayer
from lasagne.layers import InputLayer
from lasagne.nonlinearities import sigmoid
from lasagne.nonlinearities import softmax
from lasagne.nonlinearities import rectify
from lasagne.updates import nesterov_momentum
from nolearn.lasagne import NeuralNet

layers0 = [('input', InputLayer),
           ('dense0', DenseLayer),
           ('output', DenseLayer)]

net0 = NeuralNet(layers=layers0,
    input_shape=(None, 28*28),
    dense0_num_units=1000,
    dense0_nonlinearity = sigmoid,
    output_num_units=10,
    output_nonlinearity=softmax,

    update=nesterov_momentum,
    update_learning_rate=0.1,
    update_momentum=0.9,
    regression=False,

    on_epoch_finished=[
        EarlyStopping(patience=20)
        ],

    eval_size=None,
    verbose=1,
    max_epochs=100)

X_train, y_train, X_val, y_val, X_test, y_test = load_dataset(False)

def my_split(self, X, y, eval_size):
    return X_train,X_val,y_train,y_val

net0.train_test_split = types.MethodType(my_split, net0)

net0.fit(X_train, y_train)

y_predict = net0.predict(X_val)

count = 0
wrong = 0
for element in zip(X_val,y_val,y_predict):
    if element[1] != element[2]:
        wrong = wrong + 1
    count = count + 1

print("Incorrect {}/{} ({}%)".format(wrong,count,(wrong/count)*100))


text:
<?php

/**
 * Skeleton subclass for performing query and update operations on the 'feed_type' table.
 *
 *
 *
 * You should add additional methods to this class to meet the
 * application requirements.  This class will only be generated as
 * long as it does not already exist in the output directory.
 *
 * @package    propel.generator.rss-reader
 */
class FeedTypeQuery extends BaseFeedTypeQuery
{
}


text:
export function getMostFrequentLanguage(numberOfFilesPerLanguage: Map<string, number>): string | undefined {
	let language
	let max = -1
	for (const [key, filesPerLanguage] of numberOfFilesPerLanguage) {
		if (max < filesPerLanguage) {
			max = filesPerLanguage
			language = key
		}
	}
	return language
}


text:
package com.intellij.util.text;

import com.intellij.openapi.util.text.StringUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

/**
 * Holds Semantic Version.
 */
public class SemVer implements Comparable<SemVer> {
  public static final SemVer UNKNOWN = new SemVer("?", 0, 0, 0);

  private final String myRawVersion;
  private final int myMajor;
  private final int myMinor;
  private final int myPatch;

  public SemVer(@NotNull String rawVersion, int major, int minor, int patch) {
    myRawVersion = rawVersion;
    myMajor = major;
    myMinor = minor;
    myPatch = patch;
  }

  @NotNull
  public String getRawVersion() {
    return myRawVersion;
  }

  public int getMajor() {
    return myMajor;
  }

  public int getMinor() {
    return myMinor;
  }

  public int getPatch() {
    return myPatch;
  }

  @NotNull
  public String getParsedVersion() {
    return myMajor + "." + myMinor + "." + myPatch;
  }

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

    SemVer semVer = (SemVer)o;

    if (myMajor != semVer.myMajor) return false;
    if (myMinor != semVer.myMinor) return false;
    if (myPatch != semVer.myPatch) return false;

    return true;
  }

  @Override
  public int hashCode() {
    int result = myMajor;
    result = 31 * result + myMinor;
    result = 31 * result + myPatch;
    return result;
  }

  @Override
  public String toString() {
    return myRawVersion;
  }

  @Nullable
  public static SemVer parseFromText(@NotNull String text) {
    int majorEndInd = text.indexOf('.');
    if (majorEndInd < 0) {
      return null;
    }
    int major = StringUtil.parseInt(text.substring(0, majorEndInd), -1);
    int minorEndInd = text.indexOf('.', majorEndInd + 1);
    if (minorEndInd < 0) {
      return null;
    }
    int minor = StringUtil.parseInt(text.substring(majorEndInd + 1, minorEndInd), -1);
    final String patchStr;
    int dashInd = text.indexOf('-', minorEndInd + 1);
    if (dashInd >= 0) {
      patchStr = text.substring(minorEndInd + 1, dashInd);
    }
    else {
      patchStr = text.substring(minorEndInd + 1);
    }
    int patch = StringUtil.parseInt(patchStr, -1);
    if (major >= 0 && minor >= 0 && patch >= 0) {
      return new SemVer(text, major, minor, patch);
    }
    return null;
  }

  @NotNull
  public static SemVer parseFromTextNonNullize(@Nullable final String text) {
    if (text == null) return UNKNOWN;
    final SemVer ver = parseFromText(text);
    return ver == null ? UNKNOWN : ver;
  }

  @Override
  public int compareTo(SemVer other) {
    // null is not permitted
    if (getMajor() != other.getMajor()) {
      return getMajor() - other.getMajor();
    }
    if (getMinor() != other.getMinor()) {
      return getMinor() - other.getMinor();
    }
    if (getPatch() != other.getPatch()) {
      return getPatch() - other.getPatch();
    }
    return 0;
  }
}


text:
<?php
// WARNING, this is a read only file created by import scripts
// WARNING
// WARNING,  Changes made to this file will be clobbered
// WARNING
// WARNING,  Please make changes on poeditor instead of here
//
//
?>
subject: Plik(i) nie są już dostępne do pobrania
subject: (Pliki nie są już dostępne do pobrania) {transfer.subject}

{alternative:plain}

Szanowni Państwo,

Transfer nr {transfer.id} został usunięty z {cfg:site_name} przez wysyłającego  ({transfer.user_email}) i nie jest już dostępny do pobrania.

Z Poważaniem,
{cfg:site_name}

{alternative:html}

    Szanowni Państwo,

    Transfer nr {transfer.id} został usunięty z {cfg:site_name} przez wysyłającego ({transfer.user_email}) i nie jest już dostępny do pobrania.

    Z Poważaniem,

    {cfg:site_name}


text:
@interface SimpleAuthYoutubeProvider : SimpleAuthProvider

@end


text:
import {StructureFactory} from "./../../../factories";
import {ClassStaticMethodParameterStructure} from "./../../../structures";
import {ClassStaticMethodParameterBinder} from "./../../base";
import {StructureBaseClassMethodParameterBinder} from "./base";

export class StructureClassStaticMethodParameterBinder extends ClassStaticMethodParameterBinder {
    constructor(factory: StructureFactory, structure: ClassStaticMethodParameterStructure) {
        super(new StructureBaseClassMethodParameterBinder(factory, structure));
    }
}


text:
<?php

chdir(getenv('HOME') . '/code');

print "\n====== Running 'composer prepare-for-pantheon' ======\n\n";
passthru('composer prepare-for-pantheon 2>&1');


text:
layout: none
permalink: /includes/group-menu.html
search: exclude
sitemap_include: false
---
{% include group-menu.html %}


text:
#region Copyright
//
// DotNetNuke® - http://www.dotnetnuke.com
// Copyright (c) 2002-2014
// by DotNetNuke Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
// documentation files (the "Software"), to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and
// to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions
// of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
// CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
#endregion
#region Usings

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web.Script.Serialization;
using System.Web.UI;
using System.Web.UI.WebControls;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Entities.Content.Common;
using DotNetNuke.Entities.Content.Taxonomy;
using DotNetNuke.Framework;
using DotNetNuke.Framework.JavaScriptLibraries;
using DotNetNuke.UI.Utilities;
using DotNetNuke.Web.Client.ClientResourceManagement;
using Telerik.Web.UI;

#endregion

namespace DotNetNuke.Web.UI.WebControls
{
    public class TermsSelector : DnnComboBox, IClientAPICallbackEventHandler
    {
        public TermsSelector()
        {
            IncludeSystemVocabularies = false;
            IncludeTags = true;
            EnableViewState = false;
        }

        #region Public Properties

        public int PortalId { get; set; }

        public bool IncludeSystemVocabularies { get; set; }

        public bool IncludeTags { get; set; }

        public List<Term> Terms { get; set; }

        #endregion

        #region Protected Methods

        protected override void OnInit(EventArgs e)
        {
            ItemTemplate = new TreeViewTemplate();
            Items.Add(new RadComboBoxItem());
            base.OnInit(e);

            JavaScript.RequestRegistration(CommonJs.jQueryMigrate);

            OnClientDropDownOpened = "webcontrols.termsSelector.OnClientDropDownOpened";
            if (!string.IsNullOrEmpty(CssClass))
            {
                CssClass = string.Format("{0} TermsSelector", CssClass);
            }
            else
            {
                CssClass = "TermsSelector";
            }
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            if (Page.IsPostBack)
            {
                if (Terms == null)
                {
                    Terms = new List<Term>();
                }
                else
                {
                    Terms.Clear();
                }

                if (!string.IsNullOrEmpty(SelectedValue))
                {
                    foreach (var id in SelectedValue.Split(','))
                    {
                        var termId = Convert.ToInt32(id.Trim());
                        var term = Util.GetTermController().GetTerm(termId);
                        if (term != null)
                        {
                            Terms.Add(term);
                        }
                    }

                    //clear the append item by client side
                    if (Items.Count > 1)
                    {
                        Items.Remove(1);
                    }
                }
            }

            if (!Page.IsPostBack)
            {
                Page.ClientScript.RegisterClientScriptResource(GetType(), "DotNetNuke.Web.UI.WebControls.Resources.TermsSelector.js");

                ClientResourceManager.RegisterStyleSheet(Page,
                    Page.ClientScript.GetWebResourceUrl(GetType(), "DotNetNuke.Web.UI.WebControls.Resources.TermsSelector.css"));

                ClientAPI.RegisterClientVariable(Page, "TermsSelectorCallback",
                    ClientAPI.GetCallbackEventReference(this, "'[PARAMS]'", "webcontrols.termsSelector.itemDataLoaded", "this",
                        "webcontrols.termsSelector.itemDataLoadError"), true);
            }
        }

        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);
            if (Terms != null)
            {
                Attributes.Add("SelectedTerms", String.Join(",", Terms.Select(t => t.TermId.ToString()).ToArray()));
            }
            Attributes.Add("IncludeSystemVocabularies", IncludeSystemVocabularies.ToString().ToLowerInvariant());
            Attributes.Add("IncludeTags", IncludeTags.ToString().ToLowerInvariant());
            Attributes.Add("PortalId", PortalId.ToString());
        }

        #endregion

        #region Private Template Class

        public class TreeViewTemplate : ITemplate
        {
            #region Private Fields

            private RadComboBoxItem _container;
            private TermsSelector _termsSelector;

            private DnnTreeView _tree;

            #endregion

            #region ITemplate Members

            public void InstantiateIn(Control container)
            {
                _container = (RadComboBoxItem)container;
                _termsSelector = (TermsSelector)container.Parent;

                _tree = new DnnTreeView();
                _tree.ID = string.Format("{0}_TreeView", _termsSelector.ID);
                _tree.CheckBoxes = true;
                _tree.EnableViewState = false;

                //bind client-side events
                _tree.OnClientNodeChecked = "webcontrols.termsSelector.OnClientNodeChecked";

                _container.Controls.Add(_tree);
            }

            #endregion
        }

        #endregion

        #region IClientAPICallbackEventHandler Implementation

        public string RaiseClientAPICallbackEvent(string eventArgument)
        {
            var parameters = eventArgument.Split('-');
            PortalId = Convert.ToInt32(parameters[1]);
            IncludeTags = Convert.ToBoolean(parameters[2]);
            IncludeSystemVocabularies = Convert.ToBoolean(parameters[3]);
            var terms = GetTerms();
            terms.Insert(0, new { clientId = parameters[0] });
            var serializer = new JavaScriptSerializer();
            return serializer.Serialize(terms);
        }

        #endregion

        #region Private Methods

        private ArrayList GetTerms()
        {
            var vocabRep = Util.GetVocabularyController();
            var terms = new ArrayList();
            var vocabularies = from v in vocabRep.GetVocabularies() where v.ScopeType.ScopeType == "Application" || (v.ScopeType.ScopeType == "Portal" && v.ScopeId == PortalId) select v;

            foreach (Vocabulary v in vocabularies)
            {
                if (v.IsSystem)
                {
                    if (IncludeSystemVocabularies || (IncludeTags && v.Name == "Tags"))
                    {
                        AddTerms(v, terms);
                    }
                }
                else
                {
                    AddTerms(v, terms);
                }
            }

            return terms;
        }

        private void AddTerms(Vocabulary v, ArrayList terms)
        {
            ITermController termRep = Util.GetTermController();

            //Add a dummy parent term if simple vocabulary
            if (v.Type == VocabularyType.Simple)
            {
                terms.Add(new { termId = -v.VocabularyId, name = v.Name, parentTermId = Null.NullInteger });
            }
            foreach (Term t in termRep.GetTermsByVocabulary(v.VocabularyId))
            {
                if (v.Type == VocabularyType.Simple)
                {
                    t.ParentTermId = -v.VocabularyId;
                }
                terms.Add(new { termId = t.TermId, name = t.Name, parentTermId = t.ParentTermId });
            }

        }

        #endregion
    }
}


text:
load('../NnClassLoader.js');

var L = new NnClassLoader({
	maven:[
		'com.h2database:h2:1.4.192',
		'org.apache.commons:commons-dbcp2:2.1.1'
	]
});

print('--------');
for each(var url in L.getUrls())
	print(" " + url);
print('--------');

if (L.getUrls().length < 2)
	throw "Wrong classpath.";

var BasicDataSource = L.type('org.apache.commons.dbcp2.BasicDataSource');

var ds = new BasicDataSource();

ds.setDriverClassName('org.h2.Driver');
ds.setUrl('jdbc:h2:mem:MyTestDb');

var c = ds.getConnection();
var s = c.createStatement();

if (s.executeUpdate('CREATE TABLE cars(name VARCHAR)') !== 0)
	throw "Unexpected CREATE reuslt.";

if (s.executeUpdate("INSERT INTO cars VALUES ('BMW'),('Volvo'),('Lexus')") !== 3)
	throw "Unexpected INSERT reuslt.";

var rs = s.executeQuery('SELECT * FROM cars');

var arr = ['BMW','Volvo','Lexus'];

var i = 0;

print('--------');
while (rs.next()) {
	var x = rs.getString(1);

	if (x != arr[i])
		throw "Result mismatch: " + x + " != " + arr[i];

	i++;

	print(x);
}
print('--------');

print('OK');


text:
using System;
using System.Runtime.InteropServices;

namespace SharpVk.Interop
{
    /// <summary>
    ///
    /// </summary>
    [StructLayout(LayoutKind.Sequential)]
    public unsafe partial struct QueueFamilyProperties2
    {
        /// <summary>
        /// The type of this structure.
        /// </summary>
        public SharpVk.StructureType SType;

        /// <summary>
        /// Null or an extension-specific structure.
        /// </summary>
        public void* Next;

        /// <summary>
        ///
        /// </summary>
        public SharpVk.QueueFamilyProperties QueueFamilyProperties;
    }
}


text:
// ZAP: 2012/04/25 Added @Override annotation to all appropriate methods.
// ZAP: 2013/01/25 Removed the "(non-Javadoc)" comments.
// ZAP: 2013/03/03 Issue 546: Remove all template Javadoc comments
package org.parosproxy.paros.extension.filter;

import org.parosproxy.paros.Constant;
import org.parosproxy.paros.network.HttpHeader;
import org.parosproxy.paros.network.HttpMessage;
import org.parosproxy.paros.network.HttpRequestHeader;

public class FilterIfModifiedSince extends FilterAdaptor {

    @Override
    public int getId() {
        return 10;
    }

    @Override
    public String getName() {
        return Constant.messages.getString("filter.nocache.name");

    }

    @Override
    public void onHttpRequestSend(HttpMessage httpMessage) {
        HttpRequestHeader reqHeader = httpMessage.getRequestHeader();
      	if (!reqHeader.isEmpty() && reqHeader.isText()){
      		String ifModifed = reqHeader.getHeader(HttpHeader.IF_MODIFIED_SINCE);
      		if (ifModifed != null){
      			reqHeader.setHeader(HttpHeader.IF_MODIFIED_SINCE, null);
      		}
      		String ifNoneMatch = reqHeader.getHeader(HttpHeader.IF_NONE_MATCH);
      		if (ifNoneMatch != null){
      			reqHeader.setHeader(HttpHeader.IF_NONE_MATCH, null);
      		}

      	}

    }

    @Override
    public void onHttpResponseReceive(HttpMessage httpMessage) {

    }

}


text:
"""
Created on Sun Jul  4 14:46:34 2021

@author: zach
@author: Alison updated with arguments for galaxy

"""
import argparse
import glob
import os
from pathlib import Path
import pandas as pd
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import seaborn as sns
import math

from upsetplot import UpSet

def getOptions():
    parser = argparse.ArgumentParser(description='Create plots and files for comparing pathway and in-Set meta-analyses')
    parser.add_argument("-i1", "--in1", dest="in1", action='store', required=True, help="Input summary file from pathway meta-analysis .")
    parser.add_argument("-p", "--inPath", dest="inPath", action='store', required=True, help="Name of metabolic pathway.")
    parser.add_argument("-m", "--inMut", dest="inMut", nargs='+', required=True, help="List of mutants (space separated) in the indicated metabolic pathway.")

    parser.add_argument("-i2", "--in2", dest="in2", action='store', required=True, help="Input directory containing summary files from in-Set meta-analysis .")

    parser.add_argument("-o", "--outD", dest="outD", action='store', required=True, help="Output directory.")
    parser.add_argument("--debug", action='store_true', default=False, help="Print debugging output")
    args=parser.parse_args()
    return args

def direction_determine(x):
    for i in x[1:]:
        if x[0] * i <=0:
            return 0
    return 1

def all_sig(x):
    for i in x:
        if i != 1:
            return 0
    return 1

def main():
    args = getOptions()

## set which pathway
    group = args.inPath
    muts = args.inMut

    print(group)
    print(muts)

## summary file from running pathway
    combined = pd.read_csv(args.in1)
    #print("print pathway input")
    #print(combined)
    combined.columns = ["rowID"] + combined.columns[1:].tolist()
    combined = combined[["rowID", 'effect', 'p_value']]
    combined.columns = ['rowID', 'effect_meta_pathway', 'p_meta_pathway']

## summary file in-Set
    df_mut = combined
    mutpath = args.in2 + "/"
    print(mutpath)
    suffix='_summary.csv'
    for mut in muts:
        for file in os.listdir(mutpath):
            if mut in file and suffix in file:
                print(mut)
                f = os.path.join(mutpath, file)
                print(f)
                dat = pd.read_csv(f)
                dat.columns =  ["rowID"] + dat.columns[1:].tolist()
                dat = dat[['rowID', 'effect', 'p_value']]
                column_names = ['rowID'] + ['effect_' + mut] + ['p_' + mut]
                dat.columns = column_names
                #print("printing dat")
                #print(dat)
                df_mut = pd.merge(df_mut, dat, on = 'rowID', how = 'outer', indicator = "merge_check")
                #print(df_mut["merge_check"].value_counts())
                df_mut = df_mut[df_mut["merge_check"] != "right_only"].drop(columns=["merge_check"])
                #print("printing df_mut")
                #print(df_mut)

    df_mut.index = df_mut["rowID"]
    df_mut = df_mut.drop("rowID", axis = 1)

    es_cols = pd.Series(df_mut.columns).str.contains("effect|rowID").tolist()
    df_es = df_mut.loc[:,es_cols].copy()

    p_cols = pd.Series(df_mut.columns).str.contains("p_|rowID").tolist()
    df_p = df_mut.loc[:,p_cols]

    df_es["flag_same_direction"] = df_es.apply(direction_determine, axis = 1)
    #print("PRINT")
    #print(df_es)
##### result 2: counts same direction
    counts_same_direct = sum(df_es["flag_same_direction"])

    sig_05_table = pd.DataFrame(np.where(df_p < 0.05, 1, 0))
    sig_05_table.columns = df_p.columns
    sig_05_table.index = df_p.index

    #sig_05_table.to_csv(args.outD + "/sig_table_" + group + ".csv")

##### result 1: count table for sig 0.05
    counts_sig_05 = pd.DataFrame(sig_05_table.apply(sum, axis = 0))
    counts_sig_05.columns = ['c_sig_0.05']

#####
    both_sig_same_05 = pd.Series(sig_05_table.loc[(df_es["flag_same_direction"] == 1) & (sig_05_table['p_meta_pathway'] == 1)].index)
    both_sig_same_05 = sig_05_table.apply(lambda x: len(df_p.loc[(df_es["flag_same_direction"] == 1) & (x ==1), x.name]))
    both_sig_same_05.name = 'both_sig_0.05_and_same_direct'

#####

####

    ## subset where pathway is significant in both dataframes
    sig_05_table_combine = sig_05_table[sig_05_table['p_meta_pathway'] == 1]
    df_es_sig_05_combine = df_es[sig_05_table["p_meta_pathway"] == 1]

    ## and is in the same direction
    df_es_sig_05_combine_sdirect = df_es_sig_05_combine[df_es_sig_05_combine["flag_same_direction"]==1]
    print(len(df_es_sig_05_combine_sdirect))

    ## and NOT in the same direction
    df_es_sig_05_combine_ndirect = df_es_sig_05_combine[df_es_sig_05_combine["flag_same_direction"]==0][100:200]

#######################
############ extract a effect size matrix for heatmap in R
    es_matrix = df_es[df_es['flag_same_direction'] == 1].copy()
    es_matrix['sig_counts'] = sig_05_table.loc[df_es['flag_same_direction'] == 1, ~sig_05_table.columns.str.contains("meta_pathway")].apply(sum, axis = 1)
    es_matrix['direction'] = np.where(es_matrix['effect_meta_pathway'] > 0, 1, 0)
    es_matrix = es_matrix.sort_values(by = ['sig_counts', 'direction'], ascending = False)
    sort_info = es_matrix[['sig_counts', 'direction']]

    es_matrix = es_matrix.merge(df_p["p_meta_pathway"], left_index = True, right_index = True, how = 'left')
    es_matrix.to_csv(args.outD + "/effect_size_matrix_" + group + ".csv")
    print(len(es_matrix))

####### scatter all same direction
    fig = plt.figure(figsize=(15,4), facecolor='white',edgecolor='black')
    ax = fig.add_subplot(111)
    colors = ['red', 'blue', 'green', 'orange', 'black', 'purple']
    labels = df_es_sig_05_combine.columns[:-1]
    #labels = pd.Series(labels).str.split("_").apply(lambda x: x[1])
    sizes = [3] + [1] * 5
    s = 0
    patches = []

    for i in df_es_sig_05_combine.columns[:-1]:
        patch = ax.plot([i for i in range(0, len(df_es_sig_05_combine_sdirect))],
        #patch = ax.plot([i * 2 for i in range(0, len(df_es_sig_05_combine_sdirect))],
        df_es_sig_05_combine_sdirect.loc[:, i].tolist(),
       'o', markersize = sizes[s], color = colors[s])
        s +=1
        patches += patch

    ax.hlines(0, ax.get_xlim()[0], ax.get_xlim()[1], color = 'black', linewidth = 0.5)
    box = ax.get_position()
    ax.set_position([box.x0, box.y0, box.width * 0.8, box.height])
    ax.legend([matplotlib.lines.Line2D([0],[0], color = x, marker = 'o', ls = '', markersize=3) for x in colors],
              labels, loc='lower left', bbox_to_anchor=(1, 0.05), prop = dict(size = 8))
    plt.xlabel("individual features")
    plt.ylabel("effect size")
    fig.savefig(args.outD + "/scatterPlot_ES_sig_path_and_all_models_same_direct_" + group + '.pdf')
    plt.close(fig)

##### upset plot
    def plot_upset(df,title, fig, boxCols=None):
        """
        Plot an UpSet plot given a properly formatted dataframe (multi-indexed with boolean values)
        """
        upset = UpSet(df,subset_size='count',show_counts=True,sort_by='degree',sort_categories_by=None)
        if boxCols is not None:
            if type(boxCols) != list:
                boxCols = list(boxCols)
            for col in boxCols:
                upset.add_catplot(value=col, kind='box', elements = 4, showfliers=False, color=sns.color_palette('colorblind',15).as_hex()[boxCols.index(col)])
        upset.plot(fig = fig)
        plt.subplots_adjust(right=1.00001)
        plt.suptitle(title, fontsize=9)

    def split_pos_neg(sig_table, es_table):
        cols = sig_table.columns
        res = pd.DataFrame(index = sig_table.index)
        for col in cols:
            sig_list = sig_table[col]
            es_list = es_table[col]
            res[col + "_up"] = 0
            res[col + "_down"] = 0

            res[col+"_up"] = np.where(sig_list & es_list ,1,0) + res[col+'_up']
            res[col+"_down"] = np.where((sig_list == 1) & (es_list == 0), 1, 0) + res[col+'_down']
        return res

###
    sig_upset = sig_05_table.iloc[:,1:]
    sig_upset = sig_upset[df_es['flag_same_direction'] == 0].copy()
    #sig_upset = sig_upset[~(df_es['flag_same_direction'] == 1)].copy()

    ## drop rows in sig_upset where all columns sum to 0
    sig_upset = sig_upset[~(sig_upset.apply(sum, axis = 1) == 0)]
###
    df_es_direct = df_es.loc[sig_upset.index, df_es.columns[1:-1]]
    df_es_direct = pd.DataFrame(np.where(df_es_direct > 0, 1, 0))

    print(df_es_direct)
    print(df_es_direct.shape) # 2, 4
    print(sig_upset.shape)    # 2, 6

    df_es_direct.index = sig_upset.index
    df_es_direct.columns = sig_upset.columns
    inputs = split_pos_neg(sig_upset, df_es_direct)

###
    cols = inputs.columns.to_list()
    inputs = inputs.reset_index()
    inputs[cols] = inputs[cols].astype(bool)
    inputs= inputs.set_index(cols)

###
    fig  = plt.figure(figsize=(12,8))
    plot_upset(inputs,"sig features where the ES is not consistent in direction between in-set and pathway models", fig)
    fig.savefig(args.outD + "/upset_num_sig_features_ES_inconsistent_inSet_vs_pathway_" + group + ".pdf", format='pdf')
    plt.close(fig)

if __name__ == '__main__':
    main()


text:
<!DOCTYPE html>

  <title>Popover</title>
  <link rel="stylesheet" type="text/css" href="../../../dist/css/bootstrap.min.css">

Popover Bootstrap Visual Test

  <button type="button" class="btn btn-default js-popover" data-container="body" data-toggle="popover" data-placement="left" data-content="Vivamus sagittis lacus vel augue laoreet rutrum faucibus." data-original-title="" title="">
    Popover on left
  </button>
  <button type="button" class="btn btn-default js-popover" data-container="body" data-toggle="popover" data-placement="top" data-content="Vivamus sagittis lacus vel augue laoreet rutrum faucibus." data-original-title="" title="">
    Popover on top
  </button>
  <button type="button" class="btn btn-default js-popover" data-container="body" data-toggle="popover" data-placement="bottom" data-content="Vivamus sagittis lacus vel augue laoreet rutrum faucibus." data-original-title="" title="">
    Popover on bottom
  </button>
  <button type="button" class="btn btn-default js-popover" data-container="body" data-toggle="popover" data-placement="right" data-content="Vivamus sagittis lacus vel augue laoreet rutrum faucibus." data-original-title="" title="">
    Popover on right
  </button>


text:
package fr.lteconsulting.hexa.client.comm;

public interface XRPCRequest
{
	void onResponse( Object cookie, ResponseJSO response, int msgLevel, String msg );
}


text:
@(implicit loggedManager: Manager)

@import controllers.admin.routes

@views.html.admin.templates.default(title = "Admin Area", tab = "admin") {

Admin Area

This is the Admin Area. Only managers with 'master' role can be here.

}


text:
<assembly xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0 http://maven.apache.org/xsd/assembly-1.1.0.xsd">
  <id>kettle-plugin</id>
  <formats>
    <format>tar.gz</format>
    <format>tar.bz2</format>
    <format>zip</format>
  </formats>
  <fileSets>
    <fileSet>
      <directory>${project.basedir}</directory>
      <outputDirectory>/</outputDirectory>
      <includes>
        <include>README*</include>
        <include>LICENSE*</include>
        <include>NOTICE*</include>
      </includes>
    </fileSet>
    <fileSet>
      <directory>${project.basedir}/src/main/resources</directory>
      <outputDirectory>/</outputDirectory>
      <includes>
        <include>DateDimension.png</include>
      </includes>
    </fileSet>
    <fileSet>
      <directory>${project.build.directory}</directory>
      <outputDirectory>/</outputDirectory>
      <includes>
        <include>*.jar</include>
      </includes>
    </fileSet>
    <fileSet>
      <directory>${project.build.directory}/classes</directory>
      <outputDirectory>/</outputDirectory>
      <includes>
        <include>plugin.xml</include>
      </includes>
    </fileSet>
  </fileSets>
  <dependencySets>
    <dependencySet>
      <outputDirectory>/</outputDirectory>
      <useProjectArtifact>true</useProjectArtifact>
      <unpack>false</unpack>
      <scope>runtime</scope>
    </dependencySet>
  </dependencySets>
</assembly>


text:
namespace ZY
{
	template <typename T, class Alloc = alloc>
	class vector
	{
	public:
		// vector µÄǶÌ×Ðͱð¶¨Òå
		typedef T			value_type;
		typedef value_type*	pointer;
		typedef value_type*	iterator;
		typedef value_type&	reference;
		typedef size_t		size_type;
		typedef ptrdiff_t	difference_type;

	public:
		vector() : start(0), end(0), end_of_storage(0) {};
		vector(size_type n, const T& value) { }
		vector(int n, const T& value);
		vector(long n, const T& value);
		explicit vector(size_type n);
		~vector();

		reference front() { return *begin(); }
		reference back() { return *(end() - 1); }
		void push_back();
		void pop_back();
		iterator erase(iterator position)
		{

		}
		void resize(size_type new_size, const T& x)
		{

		}
		void resize(size_type new_size)
		{

		}
		void clear()
		{
			erase(begin(), end());
		}
	public:
		iterator begin() { return start; }
		iterator end() { return finish; }
		size_type size() const { return size_type(end() - begin()); }
		size_type capacity const
		{
			return size_type(end_of_storage - begin());
		}
		bool empty() const
		{
			return begin() == end();
		}
		reference operator[](size_type n)
		{
			return *(begin() + n);
		}

	protected:
		iterator start;
		iterator finish;
		iterator end_of_storage;
	};
}


text:
from PyQt4.QtCore import pyqtSignal
from PyQt4.QtGui import QIcon, QTreeWidget, QTreeWidgetItem

class MessagesWidget( QTreeWidget ):
    message_added = pyqtSignal()

    def __init__( self, parent = None ):
        QTreeWidget.__init__( self, parent )

        self.setHeaderLabels( [ "Message", "Sender" ] )
        self.setRootIsDecorated( False )
        self.setColumnWidth( 0, 700 )

    def addMessage( self, message, sender, icon = "information" ):
        item = QTreeWidgetItem( [ message, sender ] );
        item.setIcon( 0, QIcon.fromTheme( "dialog-" + icon ) )
        self.addTopLevelItem( item )
        self.message_added.emit()


text:
#pragma once

#include <kernel/thread.h>
#include <lk/compiler.h>
#include <stdbool.h>
#include <sys/types.h>

__BEGIN_CDECLS

#define EVENT_MAGIC (0x65766E74)  // "evnt"

typedef struct event {
    int magic;
    bool signaled;
    uint flags;
    wait_queue_t wait;
} event_t;

#define EVENT_FLAG_AUTOUNSIGNAL 1

#define EVENT_INITIAL_VALUE(e, initial, _flags) \
{ \
    .magic = EVENT_MAGIC, \
    .signaled = initial, \
    .flags = _flags, \
    .wait = WAIT_QUEUE_INITIAL_VALUE((e).wait), \
}

/* Rules for Events:
 * - Events may be signaled from interrupt context *but* the reschedule
 *   parameter must be false in that case.
 * - Events may not be waited upon from interrupt context.
 * - Events without FLAG_AUTOUNSIGNAL:
 *   - Wake up any waiting threads when signaled.
 *   - Continue to do so (no threads will wait) until unsignaled.
 * - Events with FLAG_AUTOUNSIGNAL:
 *   - If one or more threads are waiting when signaled, one thread will
 *     be woken up and return.  The signaled state will not be set.
 *   - If no threads are waiting when signaled, the Event will remain
 *     in the signaled state until a thread attempts to wait (at which
 *     time it will unsignal atomicly and return immediately) or
 *     event_unsignal() is called.
*/

void event_init(event_t *, bool initial, uint flags);
void event_destroy(event_t *);
status_t event_wait_timeout(event_t *, lk_time_t); /* wait on the event with a timeout */
status_t event_signal(event_t *, bool reschedule);
status_t event_unsignal(event_t *);

static inline bool event_initialized(event_t *e) {
    return e->magic == EVENT_MAGIC;
}

static inline status_t event_wait(event_t *e) {
    return event_wait_timeout(e, INFINITE_TIME);
}

__END_CDECLS


text:
define("dojox/grid/nls/DataGrid_sl",{"dijit/nls/loading":{loadingState:"Nalaganje ...",errorState:"Oprostite, pri\u0161lo je do napake.",_localized:{}}});
//# sourceMappingURL=DataGrid_sl.js.map


text:
build:
	git rev-parse HEAD > .git-ref
	mkdir -p build/src
	mkdir -p build/demo/kitchen-sink
	mkdir -p build/textarea/src

	cp -r demo/kitchen-sink/styles.css build/demo/kitchen-sink/styles.css
	cp demo/kitchen-sink/logo.png build/demo/kitchen-sink/logo.png
	cp -r doc/site/images build/textarea

	./Makefile.dryice.js normal
	./Makefile.dryice.js demo
	./Makefile.dryice.js bm

clean:
	rm -rf build
	rm -rf ace-*
	rm -f ace-*.tgz

ace.tgz: build
	mv build ace-`./version.js`/
	cp Readme.md ace-`./version.js`/
	cp LICENSE ace-`./version.js`/
	tar cvfz ace-`./version.js`.tgz ace-`./version.js`/

dist: clean build ace.tgz