text:
package org.apache.poi.poifs.crypt.binaryrc4;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.security.GeneralSecurityException;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.util.Random;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;

import org.apache.poi.EncryptedDocumentException;
import org.apache.poi.poifs.crypt.ChunkedCipherOutputStream;
import org.apache.poi.poifs.crypt.CryptoFunctions;
import org.apache.poi.poifs.crypt.DataSpaceMapUtils;
import org.apache.poi.poifs.crypt.EncryptionInfo;
import org.apache.poi.poifs.crypt.Encryptor;
import org.apache.poi.poifs.crypt.HashAlgorithm;
import org.apache.poi.poifs.crypt.standard.EncryptionRecord;
import org.apache.poi.poifs.filesystem.DirectoryNode;
import org.apache.poi.util.LittleEndianByteArrayOutputStream;

public class BinaryRC4Encryptor extends Encryptor implements Cloneable {

    private int chunkSize = 512;

    protected BinaryRC4Encryptor() {
    }

    @Override
    public void confirmPassword(String password) {
        Random r = new SecureRandom();
        byte salt[] = new byte[16];
        byte verifier[] = new byte[16];
        r.nextBytes(salt);
        r.nextBytes(verifier);
        confirmPassword(password, null, null, verifier, salt, null);
    }

    @Override
    public void confirmPassword(String password, byte keySpec[],
            byte keySalt[], byte verifier[], byte verifierSalt[],
            byte integritySalt[]) {
        BinaryRC4EncryptionVerifier ver = (BinaryRC4EncryptionVerifier)getEncryptionInfo().getVerifier();
        ver.setSalt(verifierSalt);
        SecretKey skey = BinaryRC4Decryptor.generateSecretKey(password, ver);
        setSecretKey(skey);
        try {
            Cipher cipher = BinaryRC4Decryptor.initCipherForBlock(null, 0, getEncryptionInfo(), skey, Cipher.ENCRYPT_MODE);
            byte encryptedVerifier[] = new byte[16];
            cipher.update(verifier, 0, 16, encryptedVerifier);
            ver.setEncryptedVerifier(encryptedVerifier);
            HashAlgorithm hashAlgo = ver.getHashAlgorithm();
            MessageDigest hashAlg = CryptoFunctions.getMessageDigest(hashAlgo);
            byte calcVerifierHash[] = hashAlg.digest(verifier);
            byte encryptedVerifierHash[] = cipher.doFinal(calcVerifierHash);
            ver.setEncryptedVerifierHash(encryptedVerifierHash);
        } catch (GeneralSecurityException e) {
            throw new EncryptedDocumentException("Password confirmation failed", e);
        }
    }

    @Override
    public OutputStream getDataStream(DirectoryNode dir)
    throws IOException, GeneralSecurityException {
        OutputStream countStream = new BinaryRC4CipherOutputStream(dir);
        return countStream;
    }

    @Override
    public BinaryRC4CipherOutputStream getDataStream(OutputStream stream, int initialOffset)
    throws IOException, GeneralSecurityException {
        return new BinaryRC4CipherOutputStream(stream);
    }

    protected int getKeySizeInBytes() {
        return getEncryptionInfo().getHeader().getKeySize() / 8;
    }

    protected void createEncryptionInfoEntry(DirectoryNode dir) throws IOException {
        DataSpaceMapUtils.addDefaultDataSpace(dir);
        final EncryptionInfo info = getEncryptionInfo();
        final BinaryRC4EncryptionHeader header = (BinaryRC4EncryptionHeader)info.getHeader();
        final BinaryRC4EncryptionVerifier verifier = (BinaryRC4EncryptionVerifier)info.getVerifier();
        EncryptionRecord er = new EncryptionRecord() {
            @Override
            public void write(LittleEndianByteArrayOutputStream bos) {
                bos.writeShort(info.getVersionMajor());
                bos.writeShort(info.getVersionMinor());
                header.write(bos);
                verifier.write(bos);
            }
        };
        DataSpaceMapUtils.createEncryptionEntry(dir, "EncryptionInfo", er);
    }

    @Override
    public void setChunkSize(int chunkSize) {
        this.chunkSize = chunkSize;
    }

    @Override
    public BinaryRC4Encryptor clone() throws CloneNotSupportedException {
        return (BinaryRC4Encryptor)super.clone();
    }

    protected class BinaryRC4CipherOutputStream extends ChunkedCipherOutputStream {

        public BinaryRC4CipherOutputStream(OutputStream stream)
        throws IOException, GeneralSecurityException {
            super(stream, BinaryRC4Encryptor.this.chunkSize);
        }

        public BinaryRC4CipherOutputStream(DirectoryNode dir)
        throws IOException, GeneralSecurityException {
            super(dir, BinaryRC4Encryptor.this.chunkSize);
        }

        @Override
        protected Cipher initCipherForBlock(Cipher cipher, int block, boolean lastChunk)
        throws GeneralSecurityException {
            return BinaryRC4Decryptor.initCipherForBlock(cipher, block, getEncryptionInfo(), getSecretKey(), Cipher.ENCRYPT_MODE);
        }

        @Override
        protected void calculateChecksum(File file, int i) {
        }

        @Override
        protected void createEncryptionInfoEntry(DirectoryNode dir, File tmpFile)
        throws IOException, GeneralSecurityException {
            BinaryRC4Encryptor.this.createEncryptionInfoEntry(dir);
        }

        @Override
        public void flush() throws IOException {
            writeChunk(false);
            super.flush();
        }
    }
}


text: User ID for logging in to the database server.

redpajama_set_name: RedPajamaGithub


text:
namespace Data.Views
{
    using System;
    using System.Collections.Generic;

    public partial class Entity_Competencies_ForExport
    {
        public int Id { get; set; }
        public string EntityType { get; set; }
        public int EntityTypeId { get; set; }
        public int BaseId { get; set; }
        public string ParentEntityName { get; set; }
        public Nullable<int> OwningOrgId { get; set; }
        public string OwningOrganization { get; set; }
        public Nullable<System.Guid> orgUid { get; set; }
        public Nullable<int> orgId { get; set; }
        public string OrganizationCtid { get; set; }
        public int CompetencyFrameworkId { get; set; }
        public System.Guid FrameworkUid { get; set; }
        public Nullable<int> NumberOfFrameworks { get; set; }
        public string RecommendedFrameworkName { get; set; }
        public string EducationalFrameworkName { get; set; }
        public string FrameworkCtid { get; set; }
        public string EducationalFrameworkUrl { get; set; }
        public string AlignmentType { get; set; }
        public int ItemId { get; set; }
        public string Competency { get; set; }
        public string Description { get; set; }
        public string TargetName { get; set; }
        public string TargetDescription { get; set; }
        public string TargetUrl { get; set; }
        public string CodedNotation { get; set; }
        public string CompetencyCtid { get; set; }
        public System.Guid CompetencyUid { get; set; }
        public Nullable<System.DateTime> CompetencyCreated { get; set; }
    }
}


text:
using System;

public static partial class Extensions
{
    /// <summary>
    ///     Converts the value of the specified  to the equivalent 32-bit signed integer.
    /// </summary>
    /// <param name="d">The decimal number to convert.</param>
    /// <returns>A 32-bit signed integer equivalent to the value of .</returns>
    public static Int32 ToInt32(this Decimal d)
    {
        return Decimal.ToInt32(d);
    }
}


text:
package com.anysoftkeyboard.devicespecific;

import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Canvas;
import android.os.IBinder;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.GestureDetector;
import android.view.inputmethod.InputConnection;
import android.view.inputmethod.InputMethodManager;

import com.anysoftkeyboard.keyboards.KeyboardAddOnAndBuilder;

import java.util.List;

@TargetApi(3)
public class DeviceSpecificV3 implements DeviceSpecific {
    public DeviceSpecificV3() {
    }

    @Override
    public String getApiLevel() {
        return "DeviceSpecificV3";
    }

    @Override
    public GestureDetector createGestureDetector(Context appContext,
                                                 AskOnGestureListener listener) {
        return new GestureDetector(appContext, listener, null);
    }

    @Override
    public void commitCorrectionToInputConnection(InputConnection ic, int wordOffsetInInput, CharSequence oldWord, CharSequence newWord) {
        ic.commitText(newWord, 1);
    }

    @Override
    public boolean isHardwareAcceleratedCanvas(Canvas canvas) {
        return false;
    }

    @Override
    public void reportInputMethodSubtypes(@NonNull InputMethodManager inputMethodManager, @NonNull String imeId, @NonNull List<KeyboardAddOnAndBuilder> builders) {
        //no-op till API 14
    }

    @Override
    public void reportCurrentInputMethodSubtypes(@NonNull InputMethodManager inputMethodManager, @NonNull String imeId, @NonNull IBinder token, @Nullable String keyboardLocale, @NonNull CharSequence keyboardId) {
        //no-op till API 14
    }
}


text:
from celery import shared_task
from django.conf import settings
from django.urls import reverse
from templated_email import send_templated_mail

from ..core.emails import get_email_base_context
from ..core.utils import build_absolute_uri

@shared_task
def send_password_reset_email(context, recipient):
    reset_url = build_absolute_uri(
        reverse(
            'account:reset-password-confirm',
            kwargs={
                'uidb64': context['uid'],
                'token': context['token']}))
    context = get_email_base_context()
    context['reset_url'] = reset_url
    send_templated_mail(
        template_name='account/password_reset',
        from_email=settings.DEFAULT_FROM_EMAIL,
        recipient_list=[recipient],
        context=context)

@shared_task
def send_account_delete_confirmation_email(token, recipient_email):
    delete_url = build_absolute_uri(
        reverse('account:delete-confirm', kwargs={'token': token}))
    ctx = get_email_base_context()
    ctx['delete_url'] = delete_url
    send_templated_mail(
        template_name='account/account_delete',
        from_email=settings.DEFAULT_FROM_EMAIL,
        recipient_list=[recipient_email],
        context=ctx)


text:
package com.dianping.cat.consumer.transaction;

import org.junit.Assert;
import org.junit.Test;
import org.unidal.helper.Files;

import com.dianping.cat.consumer.transaction.model.entity.TransactionReport;
import com.dianping.cat.consumer.transaction.model.transform.DefaultSaxParser;
import com.dianping.cat.consumer.transaction.model.transform.DefaultXmlBuilder;

public class TransactionReportTest {
	@Test
	public void testXml() throws Exception {
		String source = Files.forIO().readFrom(getClass().getResourceAsStream("transaction_report.xml"), "utf-8");
		TransactionReport report = DefaultSaxParser.parse(source);
		String xml = new DefaultXmlBuilder().buildXml(report);
		String expected = source;

		Assert.assertEquals("XML is not well parsed!", expected.replace("\r", ""), xml.replace("\r", ""));
	}
}


text:
package apns;

public class ApnsException extends Exception {

    public ApnsException() {
    }

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

    public ApnsException(String message, Throwable cause) {
        super(message, cause);
    }

    public ApnsException(Throwable cause) {
        super(cause);
    }

    public ApnsException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
        super(message, cause, enableSuppression, writableStackTrace);
    }
}


text:
// the semi-colon before function invocation is a safety net against concatenated
// scripts and/or other plugins which may not be closed properly.
;(function ( $, window, document, undefined ) {

    $.extend({
        daisyNav: function () {

					$('ul.menu-list li.has-submenu>a').append('');

					$('.menu-toggle-button').click(function(){
						//if exist data-menu-id - bind for id, else - bind for class
						if($(this).data('menu-id')){
							var data_menu_id=$(this).data('menu-id').split(' '); //for multiple menu - split id by space ' '
							var data_menu_id_count=data_menu_id.length; //IDs count
							for(var i=0;i<data_menu_id_count;i++){ //toogle class for each binded menu id
								var menu_id=data_menu_id[i];
								if(menu_id){
									$( "#"+menu_id ).toggleClass( 'show-for-devices' );
								}
							}
						}else{
							$('ul.menu-list').toggleClass( 'show-for-devices' );
						}
						$(this).toggleClass( 'active' );
					});

					$('.menu-list .menu-expand').click(function(e){
						e.preventDefault();
						$(this).parent().next('ul').toggleClass('show-for-devices');
					});

        }
    });

})( jQuery, window, document );


text:
/*	$NetBSD: timedc.h,v 1.12 2007/01/27 17:57:45 cbiere Exp $	*/

/*-
 * Copyright (c) 1985, 1993 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. 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.
 *
 *	@(#)timedc.h	8.1 (Berkeley) 6/6/93
 */

#include <sys/param.h>
#include <sys/time.h>
#include <sys/socket.h>
#include <sys/poll.h>

#include <netinet/in.h>
#include <arpa/inet.h>

#include <errno.h>
#include <netdb.h>
#include <stdio.h>

#define ON		1
#define OFF		0

#define GOOD		1
#define UNREACHABLE	2
#define NONSTDTIME	3
#define HOSTDOWN 	0x7fffffff

struct cmd {
	const char *c_name;		/* command name */
	const char *c_help;		/* help message */
	void	(*c_handler)(int, char **); /* routine to do the work */
};

#include "timedc-extern.h"


text:
namespace Jcq.IcqProtocol.DataTypes
{
    public enum MetaResponseSubType
    {
        MetaProcessingErrorServerReply = 0x1,
        SetUserHomeInfoServerAck = 0x64,
        SetUserWorkInfoServerAck = 0x6e,
        SetUserMoreInfoServerAck = 0x78,
        SetUserNotesInfoServerAck = 0x82,
        SetUserEmailSInfoServerAck = 0x87,
        SetUserInterestsInfoServerAck = 0x8c,
        SetUserAffilationsInfoServerAck = 0x96,
        ServerSmsResponseDeliveryReceipt = 0x96,
        SetUserPermissionsServerAck = 0xa0,
        SetUserPasswordServerAck = 0xaa,
        UnregisterAccountServerAck = 0xb4,
        SetUserHomepageCategoryServerAck = 0xbe,
        UserBasicInfoReply = 0xc8,
        UserWorkInfoReply = 0xd2,
        UserMoreInfoReply = 0xdc,
        UserNotesAboutInfoReply = 0xe6,
        UserExtendedEmailInfoReply = 0xeb,
        UserInterestsInfoReply = 0xf0,
        UserPastAffilationsInfoReply = 0xfa,
        ShortUserInformationReply = 0x104,
        UserHomepageCategoryInformationReply = 0x10e,
        SearchUserFoundReply = 0x1a4,
        SearchLastUserFoundReply = 0x1ae,
        RegistrationStatsAck = 0x302,
        RandomSearchServerReply = 0x366,
        ServerVariableRequestedViaXml = 0x8a2,
        ServerAckForSetFullinfoCommand = 0xc3f,
        ServerAckForUserSpamReport = 0x2012
    }
}


text:
package org.springframework.cloud.skipper.domain;

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

/**
 * Package is the installation unit that contains metadata, dependencies, configuration values and related attributes.
 *
 * @author Mark Pollack
 */
public class Package {

	// Metadata describing the package
	private PackageMetadata metadata;

	// The templates for this package
	private List<Template> templates = new ArrayList<>();

	// The packages that this package depends upon
	private List<Package> dependencies = new ArrayList<>();

	// The configuration data that this package depends on
	private ConfigValues configValues;

	// Miscellaneous files in a package, e.g. README, LICENSE, etc.
	private List<FileHolder> fileHolders = new ArrayList<>();

	public Package() {
	}

	public PackageMetadata getMetadata() {
		return metadata;
	}

	public void setMetadata(PackageMetadata metadata) {
		this.metadata = metadata;
	}

	public List<Template> getTemplates() {
		return templates;
	}

	public void setTemplates(List<Template> templates) {
		this.templates = templates;
	}

	public List<Package> getDependencies() {
		return dependencies;
	}

	public void setDependencies(List<Package> dependencies) {
		this.dependencies = dependencies;
	}

	public ConfigValues getConfigValues() {
		return configValues;
	}

	public void setConfigValues(ConfigValues configValues) {
		this.configValues = configValues;
	}

	public List<FileHolder> getFileHolders() {
		return fileHolders;
	}

	public void setFileHolders(List<FileHolder> fileHolders) {
		this.fileHolders = fileHolders;
	}
}


text:
from __future__ import division

import os, sys
import math
import copy
import json
from functools import reduce

from numpy.linalg import norm

from ase import Atom, Atoms
from ase.geometry import cell_to_cellpar

from tilde.core.common import ModuleError #, generate_xyz
from tilde.core.constants import Perovskite_Structure
from tilde.core.symmetry import SymmetryFinder

class Perovskite_tilting():
    OCTAHEDRON_BOND_LENGTH_LIMIT = 2.5  # Angstrom
    OCTAHEDRON_ATOMS_Z_DIFFERENCE = 1.6 # Angstrom
    MAX_TILTING_DEGREE = 22.4           # degrees, this is for adjusting, may produce unphysical results

    def __init__(self, tilde_calc):
        self.prec_angles = {}    # non-rounded, non-unique, all-planes angles
        self.angles = {}         # rounded, unique, one-plane angles

        symm = SymmetryFinder()
        symm.refine_cell(tilde_calc)
        if symm.error:
            raise ModuleError("Cell refinement error: %s" % symm.error)

        # check if the longest axis is Z, rotate otherwise
        lengths = list(map(norm, symm.refinedcell.cell))
        if not (lengths[2] - lengths[0] > 1E-6 and lengths[2] - lengths[1] > 1E-6):
            axnames = {0: 'x', 1: 'y'}
            principal_ax = axnames[ lengths.index(max(lengths[0], lengths[1])) ]
            symm.refinedcell.rotate(principal_ax, 'z', rotate_cell = True)

        self.virtual_atoms = symm.refinedcell.copy()

        #f = open('tilting.xyz', 'w')
        #f.write(generate_xyz(self.virtual_atoms))
        #f.close()

        # translate atoms around octahedra in all directions
        shift_dirs = [(1, 0, 0), (-1, 0, 0), (0, 1, 0), (0, -1, 0), (1, 1, 0), (1, -1, 0), (-1, -1, 0), (-1, 1, 0), (0, 0, 1), (0, 0, -1)]

        for k, i in enumerate(symm.refinedcell):
            if i.symbol in Perovskite_Structure.C:
                for dir in shift_dirs:
                    self.translate(k, symm.refinedcell.cell, dir, self.virtual_atoms)

        # extract octahedra and their main tilting planes
        for octahedron in self.get_octahedra(symm.refinedcell, symm.refinedcell.periodicity):
            #print 'octahedron:', octahedron[0]+1 #, self.virtual_atoms[octahedron[0]].symbol, self.virtual_atoms[octahedron[0]].x, self.virtual_atoms[octahedron[0]].y, self.virtual_atoms[octahedron[0]].z
            #print 'corners:', [i+1 for i in octahedron[1]]

            # Option 1. Extract only one tilting plane, the closest to perpendicular to Z-axis
            '''tiltplane = self.get_tiltplane(octahedron[1])
            if len(tiltplane) == 4:
                t = self.get_tilting(tiltplane)
                #print 'result:', [i+1 for i in tiltplane], t
                self.prec_angles.update( { octahedron[0]: [ t ] } )'''

            # Option 2. Extract all three possible tilting planes,
            # try to spot the closest to perpendicular to Z-axis
            # and consider the smallest tilting
            plane_tilting = []
            for oplane in self.get_tiltplanes(octahedron[1]):
                t = self.get_tilting(oplane)
                #print "result:", [i+1 for i in oplane], t
                plane_tilting.append( t )
            self.prec_angles.update( { octahedron[0]: plane_tilting } )

        if not self.prec_angles: raise ModuleError("Cannot find any main tilting plane!")

        # uniquify and round self.prec_angles to obtain self.angles
        u, todel = [], []
        for o in self.prec_angles:
            self.prec_angles[o] = reduce(lambda x, y: x if sum(x) <= sum(y) else y, self.prec_angles[o]) # only minimal angles are taken if tilting planes vary!
            self.prec_angles[o] = list(map(lambda x: list(map(lambda y: round(y, 2), x)), [self.prec_angles[o]]))
            for i in self.prec_angles[o]:
                u.append([o] + i)
        u = sorted(u, key=lambda x:x[0])
        u.reverse() # to make index of oct.centers minimal
        for i in u:
            for j in range(u.index(i)+1, len(u)):
                if i[1:] == u[j][1:]:
                    todel.append(u.index(i))
                    continue
        for i in [j for j in u if u.index(j) not in todel]:
            self.angles[ i[0]+1 ] = i[1:] # atomic index is counted from zero!

    def translate(self, num_of_atom, cell, components, reference):
        a_component, b_component, c_component = components
        reference.append(Atom(
            reference[num_of_atom].symbol,
            (reference[num_of_atom].x + a_component * cell[0][0] + b_component * cell[1][0] + c_component * cell[2][0],
            reference[num_of_atom].y + a_component * cell[0][1] + b_component * cell[1][1] + c_component * cell[2][1],
            reference[num_of_atom].z + a_component * cell[0][2] + b_component * cell[1][2] + c_component * cell[2][2])
        ))

    def get_bisector_point(self, num_of_A, num_of_O, num_of_B, reference):
        xA = reference[num_of_A].x
        yA = reference[num_of_A].y
        zA = reference[num_of_A].z
        xO = reference[num_of_O].x
        yO = reference[num_of_O].y
        zO = reference[num_of_O].z
        xB = reference[num_of_B].x
        yB = reference[num_of_B].y
        zB = reference[num_of_B].z
        m = self.virtual_atoms.get_distance(num_of_O, num_of_A)
        n = self.virtual_atoms.get_distance(num_of_O, num_of_B)

        # bisector length
        l = 2*m*n*math.cos(self.virtual_atoms.get_angle([num_of_A, num_of_O, num_of_B])/2) / (m+n)
        v = math.sqrt(n*n - n*l*l/m)
        u = m*v/n
        A = yA*(zO - zB) + yO*(zB - zA) + yB*(zA - zO)
        B = zA*(xO - xB) + zO*(xB - xA) + zB*(xA - xO)
        C = xA*(yO - yB) + xO*(yB - yA) + xB*(yA - yO)
        if C == 0: C = 1E-10 # prevent zero division
        D = xA*(yO*zB - yB*zO) + xO*(yB*zA - yA*zB) + xB*(yA*zO - yO*zA)
        D *= -1

        # from surface analytical equation
        x = (xA + u*xB/v)/(1+u/v)
        y = (yA + u*yB/v)/(1+u/v)
        z = -((A*x + B*y + D) / C)
        return [x, y, z]

    def get_octahedra(self, atoms, periodicity=3):
        ''' extract octahedra as lists of sequence numbers of corner atoms '''

        octahedra = []
        for n, i in enumerate(atoms):
            found = []
            if i.symbol in Perovskite_Structure.B:
                for m, j in enumerate(self.virtual_atoms):
                    if j.symbol in Perovskite_Structure.C and self.virtual_atoms.get_distance(n, m) <= self.OCTAHEDRON_BOND_LENGTH_LIMIT:
                        found.append(m)
            if (periodicity == 3 and len(found) == 6) or (periodicity == 2 and len(found) in [5, 6]):
                octahedra.append([n, found])

        if not len(octahedra): raise ModuleError("Cannot extract valid octahedra: not enough corner atoms found!")
        return octahedra

    def get_tiltplane(self, sequence):
        ''' extract the main tilting plane basing on Z coordinate '''
        sequence = sorted(sequence, key=lambda x: self.virtual_atoms[ x ].z)
        in_plane = []
        for i in range(0, len(sequence)-4):
            if abs(self.virtual_atoms[ sequence[i] ].z - self.virtual_atoms[ sequence[i+1] ].z) < self.OCTAHEDRON_ATOMS_Z_DIFFERENCE and \
            abs(self.virtual_atoms[ sequence[i+1] ].z - self.virtual_atoms[ sequence[i+2] ].z) < self.OCTAHEDRON_ATOMS_Z_DIFFERENCE and \
            abs(self.virtual_atoms[ sequence[i+2] ].z - self.virtual_atoms[ sequence[i+3] ].z) < self.OCTAHEDRON_ATOMS_Z_DIFFERENCE:
                in_plane = [sequence[j] for j in range(i, i+4)]
        return in_plane

    def get_tiltplanes(self, sequence):
        ''' extract tilting planes basing on distance map '''

        tilting_planes = []
        distance_map = []

        for i in range(1, len(sequence)):
            distance_map.append([ sequence[i], self.virtual_atoms.get_distance( sequence[0], sequence[i] ) ])

        distance_map = sorted(distance_map, key=lambda x: x[1])

        if len(distance_map) == 4:
            # surface edge case
            # semi-octahedron at surface edge has only one tilting plane to consider
            sorted_dist = [i[0] for i in distance_map]
            if distance_map[-1][1] - distance_map[-2][1] < 0.5:
                # 1st case: max diff < 0.5 Angstrom,
                # meaning all distances to reference atom are similar,
                # therefore the reference atom is above the searched plane
                # and the searched plane consists of other atoms
                tilting_planes.append( [ i[0] for i in distance_map ] )
            else:
                # 2nd case: reference atom belongs to the searched plane,
                # procedure needs to be repeated with the next atom as reference atom
                candidates = [sequence[0], sorted_dist[-1]]
                next_distance_map = []
                next_distance_map.append([ sorted_dist[1], self.virtual_atoms.get_distance( sorted_dist[0], sorted_dist[1] ) ])
                next_distance_map.append([ sorted_dist[2], self.virtual_atoms.get_distance( sorted_dist[0], sorted_dist[2] ) ])
                next_distance_map = sorted(next_distance_map, key=lambda x: x[1])
                next_sorted_dist = [i[0] for i in next_distance_map]

                # the next reference atom is taken above the plane (distances are similar)
                if next_distance_map[1][1] - next_distance_map[0][1] < 0.5: candidates.extend([ next_sorted_dist[0], next_sorted_dist[1] ])

                # the next reference atom is taken in the plane (distances are different)
                else: candidates.extend([ sorted_dist[0], next_sorted_dist[1] ])
                tilting_planes.append(candidates)

        elif len(distance_map) == 5:
            # full octahedron case
            # full octahedron has 3 different tilting planes (perpendicular in ideal case)
            sorted_dist = [i[0] for i in distance_map]

            # 1st plane is found as:
            first_plane = sorted_dist[0:4]
            tilting_planes.append(first_plane)
            distance_map_first_plane = []
            for i in range(1, 4):
                distance_map_first_plane.append([ first_plane[i], self.virtual_atoms.get_distance( first_plane[0], first_plane[i] ) ])
            distance_map_first_plane = sorted(distance_map_first_plane, key=lambda x: x[1])
            sorted_first_plane = [i[0] for i in distance_map_first_plane]

            # 2nd and 3rd planes are found as:
            tilting_planes.append([ sequence[0], sorted_dist[4], first_plane[0], sorted_first_plane[2] ])
            tilting_planes.append([ sequence[0], sorted_dist[4], sorted_first_plane[0], sorted_first_plane[1] ])

        # filter planes by Z according to octahedral spatial compound
        filtered = list(filter(   lambda x: \
            abs(self.virtual_atoms[ x[0] ].z - self.virtual_atoms[ x[1] ].z) < self.OCTAHEDRON_ATOMS_Z_DIFFERENCE and \
            abs(self.virtual_atoms[ x[1] ].z - self.virtual_atoms[ x[2] ].z) < self.OCTAHEDRON_ATOMS_Z_DIFFERENCE and \
            abs(self.virtual_atoms[ x[2] ].z - self.virtual_atoms[ x[3] ].z) < self.OCTAHEDRON_ATOMS_Z_DIFFERENCE,   tilting_planes   ))
        if len(filtered): tilting_planes = filtered

        return tilting_planes

    def get_tilting(self, oplane):
        ''' main procedure '''

        surf_atom1, surf_atom2, surf_atom3, surf_atom4 = oplane

        # divide surface atoms into groups by distance between them
        compare = [surf_atom2, surf_atom3, surf_atom4]
        distance_map = []

        for i in range(0, 3):
            distance_map.append([ compare[i], self.virtual_atoms.get_distance(surf_atom1, compare[i]) ])

        distance_map = sorted(distance_map, key=lambda x: x[1])

        distance_map_keys = [i[0] for i in distance_map]
        surf_atom3 = distance_map_keys[2]
        surf_atom2 = distance_map_keys[1]
        surf_atom4 = distance_map_keys[0]

        if self.virtual_atoms[surf_atom1].z == self.virtual_atoms[surf_atom2].z and \
            self.virtual_atoms[surf_atom2].z == self.virtual_atoms[surf_atom3].z and \
            self.virtual_atoms[surf_atom3].z == self.virtual_atoms[surf_atom4].z:
            # this is done to prevent false zero tilting
            self.virtual_atoms[surf_atom1].z += 1E-10
            self.virtual_atoms[surf_atom2].z += 1E-10
            self.virtual_atoms[surf_atom3].z -= 1E-10
            self.virtual_atoms[surf_atom4].z -= 1E-10

        # new axes will be defined simply as vectors standing on 1 - 3 and 2 - 4 (they are moved to the point of origin)
        self.virtual_atoms.append(Atom('X', (self.virtual_atoms[surf_atom1].x - self.virtual_atoms[surf_atom3].x, self.virtual_atoms[surf_atom1].y - self.virtual_atoms[surf_atom3].y, self.virtual_atoms[surf_atom1].z - self.virtual_atoms[surf_atom3].z)))
        self.virtual_atoms.append(Atom('X', (self.virtual_atoms[surf_atom2].x - self.virtual_atoms[surf_atom4].x, self.virtual_atoms[surf_atom2].y - self.virtual_atoms[surf_atom4].y, self.virtual_atoms[surf_atom2].z - self.virtual_atoms[surf_atom4].z)))
        self.virtual_atoms.append(Atom('X', (0, 0, 0)))

        # redefine tilted axes
        surf_atom_first = len(self.virtual_atoms)-3
        surf_atom_second = len(self.virtual_atoms)-2
        center = len(self.virtual_atoms)-1

        # inverse arbitrary atom
        self.virtual_atoms.append(Atom('X', (-self.virtual_atoms[surf_atom_first].x, -self.virtual_atoms[surf_atom_first].y, -self.virtual_atoms[surf_atom_first].z)))
        inversed_one = len(self.virtual_atoms)-1

        # find and add bisectors, silly swapping
        first_bisector = self.get_bisector_point(surf_atom_first, center, surf_atom_second, self.virtual_atoms)
        sec_bisector = self.get_bisector_point(surf_atom_second, center, inversed_one, self.virtual_atoms)

        swap = True
        if first_bisector[0] < 0 and sec_bisector[0] < 0: swap = False
        if first_bisector[0] < 0:
            first_bisector[0] *= -1
            first_bisector[1] *= -1
            first_bisector[2] *= -1
        if sec_bisector[0] < 0:
            sec_bisector[0] *= -1
            sec_bisector[1] *= -1
            sec_bisector[2] *= -1
        if swap: first_bisector, sec_bisector = sec_bisector, first_bisector
        swap = False
        if first_bisector[0] < sec_bisector[0] and first_bisector[1] < 0:
            first_bisector[0] *= -1
            first_bisector[1] *= -1
            first_bisector[2] *= -1
            swap = True
        if first_bisector[0] < sec_bisector[0] and first_bisector[1] > 0: swap = True
        if first_bisector[0] > sec_bisector[0] and sec_bisector[1] < 0:
            sec_bisector[0] *= -1
            sec_bisector[1] *= -1
            sec_bisector[2] *= -1
        if swap: first_bisector, sec_bisector = sec_bisector, first_bisector

        self.virtual_atoms.append(Atom('X', (first_bisector[0], first_bisector[1], first_bisector[2])))
        self.virtual_atoms.append(Atom('X', (sec_bisector[0], sec_bisector[1], sec_bisector[2])))
        first_bisector = len(self.virtual_atoms)-2
        sec_bisector = len(self.virtual_atoms)-1

        # use vector cross product to define normal which will play Z axis role
        self.virtual_atoms.append(Atom('X', \
           (self.virtual_atoms[first_bisector].y*self.virtual_atoms[sec_bisector].z - self.virtual_atoms[first_bisector].z*self.virtual_atoms[sec_bisector].y, \
            self.virtual_atoms[first_bisector].z*self.virtual_atoms[sec_bisector].x - self.virtual_atoms[first_bisector].x*self.virtual_atoms[sec_bisector].z, \
            self.virtual_atoms[first_bisector].x*self.virtual_atoms[sec_bisector].y - self.virtual_atoms[first_bisector].y*self.virtual_atoms[sec_bisector].x)))
        tilt_z = len(self.virtual_atoms)-1

        # Euler angles ZYZ
        alpha = math.degrees(math.atan2(self.virtual_atoms[sec_bisector].z, self.virtual_atoms[first_bisector].z))
        beta = math.degrees(math.atan2(math.sqrt(self.virtual_atoms[tilt_z].x**2 + self.virtual_atoms[tilt_z].y**2), self.virtual_atoms[tilt_z].z))
        gamma = math.degrees(math.atan2(self.virtual_atoms[tilt_z].y, -self.virtual_atoms[tilt_z].x))

        # angles adjusting
        adjust_angles = [45, 90, 135, 180, 225, 270, 315, 360]
        tilting = [alpha, beta, gamma]
        for i in range(0, 3):
            tilting[i] = abs(tilting[i])
            if tilting[i] in adjust_angles:
                tilting[i] = 0.0
                continue
            if tilting[i] > self.MAX_TILTING_DEGREE:
                for checkpoint in adjust_angles:
                    if checkpoint - self.MAX_TILTING_DEGREE < tilting[i] < checkpoint + self.MAX_TILTING_DEGREE:
                        tilting[i] = abs(tilting[i] - checkpoint)
                        break
        return tilting


text:
package crawler

import (
	"bytes"
	"fmt"
	"log"
	"net/http"
	"text/template"
	"time"

	"github.com/janicduplessis/resultscrawler/pkg/api"
	"github.com/janicduplessis/resultscrawler/pkg/store/crawlerconfig"
	"github.com/janicduplessis/resultscrawler/pkg/store/results"
	"github.com/janicduplessis/resultscrawler/pkg/store/user"
	"github.com/janicduplessis/resultscrawler/pkg/tools"
)

const (
	// Time between checks to see if a user needs an update in seconds
	checkInterval time.Duration = 30 * time.Second
	// Time between updates for each user in minutes
	updateInterval time.Duration = 10 * time.Minute
)

var (
	// MsgTemplatePath is the html template used to render emails.
	msgTemplatePath = "msgtemplate.html"
	msgTemplate     *template.Template
)

// ResultGetter is an interface for something that fetches results.
type ResultGetter interface {
	// Run fetches results for a user.
	Run(user *User) []RunResult
}

// ResultGetterClient interface for sending a request to get results.
type ResultGetterClient interface {
	Do(*http.Request) (*http.Response, error)
}

// User contains info about the user of a ResultGetter run.
type User struct {
	ID      string
	Classes []api.Class
	Nip     string
	Code    string
	Name    string
	Email   string
	DoneCh  chan bool
}

// RunResult contains the result of a ResultGetter run for a class.
type RunResult struct {
	ClassIndex int
	Class      *api.Class
	Err        error
}

// SchedulerConfig initializes the scheduler.
type SchedulerConfig struct {
	ResultGetters      []ResultGetter
	UserStore          user.Store
	CrawlerConfigStore crawlerconfig.Store
	UserResultsStore   results.Store
	Sender             tools.Sender
}

// Scheduler handles scheduling crawler runs for every user.
type Scheduler struct {
	resultGetters      []ResultGetter
	userStore          user.Store
	crawlerConfigStore crawlerconfig.Store
	userResultsStore   results.Store
	sender             tools.Sender

	queueCh chan *User
	doneCh  chan bool
}

// NewScheduler creates a new scuduler object.
func NewScheduler(config *SchedulerConfig) *Scheduler {
	if msgTemplate == nil {
		msgTemplate = template.Must(template.New("msgtemplate.html").ParseFiles(msgTemplatePath))
	}

	queueCh := make(chan *User, len(config.ResultGetters))
	doneCh := make(chan bool)

	return &Scheduler{
		config.ResultGetters,
		config.UserStore,
		config.CrawlerConfigStore,
		config.UserResultsStore,
		config.Sender,

		queueCh,
		doneCh,
	}
}

// Start starts the scheduler
func (s *Scheduler) Start() {
	for _, getter := range s.resultGetters {
		go s.crawlerLoop(getter)
	}

	s.mainLoop()
}

// Stop stops the scheduler.
func (s *Scheduler) Stop() {
	// Stop the main loop.
	s.doneCh <- true
	// Stop the crawlers.
	for i := 0; i < len(s.resultGetters); i++ {
		s.doneCh <- true
	}
}

// Queue tells the scheduler do a run for a user
func (s *Scheduler) Queue(user *api.User) {
	doneCh := make(chan bool)
	s.QueueAsync(user, doneCh)
	<-doneCh
}

// QueueAsync tells the scheduler do a run for a user async
func (s *Scheduler) QueueAsync(user *api.User, doneCh chan bool) {
	// Get the user current results
	results, err := s.userResultsStore.GetResults(user.ID)
	if err != nil {
		log.Println(err)
		return
	}

	s.queueInternal(user, results, doneCh)
}

func (s *Scheduler) crawlerLoop(crawler ResultGetter) {
	for {
		select {
		case user := <-s.queueCh:
			s.run(user, crawler)
		case <-s.doneCh:
			return
		}
	}
}

// The scheduler main loop.
// Checks if any user needs to be updated every checkInterval.
func (s *Scheduler) mainLoop() {
	ticker := time.NewTicker(checkInterval)
	for {
		select {
		case <-ticker.C:
			users, err := s.userStore.ListUsers()
			if err != nil {
				log.Println(err)
				break
			}

			// Check which users need to update
			for _, user := range users {
				// Get the user current results
				results, err := s.userResultsStore.GetResults(user.ID)
				if err != nil {
					log.Println(err)
					continue
				}

				// Check last update time.
				if time.Now().Sub(results.LastUpdate) < updateInterval {
					continue
				}

				s.queueInternal(user, results, nil)
			}
		case <-s.doneCh:
			// Stop the program
			return
		}
	}
}

func (s *Scheduler) queueInternal(user *api.User, results *api.Results, doneCh chan bool) {
	// Get crawler config.
	crawlerConfig, err := s.crawlerConfigStore.GetCrawlerConfig(user.ID)
	if err != nil {
		log.Println(err)
		return
	}

	s.queueCh <- &User{
		ID:      user.ID,
		Classes: results.Classes,
		Code:    crawlerConfig.Code,
		Nip:     crawlerConfig.Nip,
		Email:   crawlerConfig.NotificationEmail,
		Name:    fmt.Sprintf("%s %s", user.FirstName, user.LastName),
		DoneCh:  doneCh,
	}
}

func (s *Scheduler) run(user *User, crawler ResultGetter) {
	// Notify the caller when the run is done.
	defer func() {
		if user.DoneCh != nil {
			user.DoneCh <- true
			close(user.DoneCh)
		}
	}()
	// Get results
	results := crawler.Run(user)
	// Check if results changed
	newRes := getNewResults(user, results)
	if len(newRes) > 0 {
		var oldRes []api.Class
		for _, class := range newRes {
			oldRes = append(oldRes, *getClassByID(class.ID, user.Classes))
		}
		log.Printf("New results for user %s. Results: %+v. Old results: %+v", user.Email, newRes, oldRes)
		if len(user.Email) > 0 {
			err := s.sendEmail(user, newRes)
			if err != nil {
				log.Println(err)
			}
		}
		// Update results
		for _, res := range results {
			// Ignore results with errors
			if res.Err == nil {
				user.Classes[res.ClassIndex].Results = res.Class.Results
				user.Classes[res.ClassIndex].Total = res.Class.Total
				user.Classes[res.ClassIndex].Final = res.Class.Final
			}
		}
	}

	err := s.userResultsStore.UpdateResults(&api.Results{
		UserID:     user.ID,
		Classes:    user.Classes,
		LastUpdate: time.Now(),
	})
	if err != nil {
		log.Println(err)
	}
}

func getClassByID(id string, classes []api.Class) *api.Class {
	for _, class := range classes {
		if class.ID == id {
			return &class
		}
	}
	return nil
}

// sendEmail notifies the user by email when he has new results.
func (s *Scheduler) sendEmail(user *User, newResults []api.Class) error {
	var msg bytes.Buffer
	data := struct {
		User       *User
		NewClasses []api.Class
	}{
		user,
		newResults,
	}
	err := msgTemplate.Execute(&msg, data)
	if err != nil {
		return err
	}

	return s.sender.Send(user.Email, "You have new results!", string(msg.Bytes()))
}

// getNewResults compares current results to new results fetched by a ResultGetter
// and returns results that have changed.
func getNewResults(user *User, newResults []RunResult) []api.Class {
	var resClasses []api.Class
	for i, resInfo := range newResults {
		if resInfo.Err != nil {
			continue
		}

		var curResults []api.Result
		for j, res := range resInfo.Class.Results {
			if len(user.Classes[i].Results) <= j {
				// If the is a new result
				curResults = append(curResults, res)
			} else {
				// Check if a result changed
				oldRes := user.Classes[i].Results[j]
				if oldRes.Name != res.Name ||
					oldRes.Normal.Average != res.Normal.Average ||
					oldRes.Normal.Result != res.Normal.Result ||
					oldRes.Normal.StandardDev != res.Normal.StandardDev {
					curResults = append(curResults, res)
				}
			}
		}
		if len(curResults) > 0 {
			classInfo := user.Classes[i]
			resClasses = append(resClasses, api.Class{
				ID:      classInfo.ID,
				Name:    classInfo.Name,
				Group:   classInfo.Group,
				Year:    classInfo.Year,
				Results: curResults,
				Final:   resInfo.Class.Final,
				Total:   resInfo.Class.Total,
			})
		}
	}
	return resClasses
}


text:
dojo.provide("dojox.drawing.manager.StencilUI");

(function(){
	var surface, surfaceNode;
	dojox.drawing.manager.StencilUI = dojox.drawing.util.oo.declare(
		// summary:
		//		Used for handling Stencils as UI components.
		// description:
		//		Replaces manager.Stencil. Handles basic UI mouse
		//		events like onmouseover. Does not handle selections
		//		or support delete, etc.
		//
		function(options){
			//
			// TODO: mixin props
			//
			surface = options.surface;
			this.canvas = options.canvas;

			this.defaults = dojox.drawing.defaults.copy();
			this.mouse = options.mouse;
			this.keys = options.keys;
			this._mouseHandle = this.mouse.register(this);
			this.stencils = {};
		},
		{
			register: function(/*Object*/stencil){
				this.stencils[stencil.id] = stencil;
				return stencil;
			},
			onUiDown: function(/*EventObject*/obj){
				// summary:
				//		Event fired on mousedown on a stencil
				//
				if(!this._isStencil(obj)){ return; }
				this.stencils[obj.id].onDown(obj);
			},
			onUiUp: function(/*EventObject*/obj){
				// summary:
				//		Event fired on mousedown on a stencil
				//
				if(!this._isStencil(obj)){ return; }
				this.stencils[obj.id].onUp(obj);
			},
			onOver: function(/*EventObject*/obj){
				// summary:
				//		Event fired on mousedown on a stencil
				//
				if(!this._isStencil(obj)){ return; }
				this.stencils[obj.id].onOver(obj);
			},
			onOut: function(/*EventObject*/obj){
				// summary:
				//		Event fired on mousedown on a stencil
				//
				if(!this._isStencil(obj)){ return; }
				this.stencils[obj.id].onOut(obj);
			},
			_isStencil: function(/*EventObject*/obj){
				return !!obj.id && !!this.stencils[obj.id] && this.stencils[obj.id].type == "drawing.library.UI.Button";
			}
		}
	);

})();


text:
var test;
// TEST config.core.js
console.log("[+] Loading config core");
test = require('../config.core.js');
WF().CONF['ERROR'] = true;
for(var exp in test)
{
		var tested = new test[exp]();
}

// TEST httpUtil.core.js
console.log("[+] Loading httputil core");
require('../httputil.core.js');

// TEST log.core.js
console.log("[+] Loading log core");
test = require('../log.core.js');
test.Log('Log ok');
test.Error('Error ok');

// TEST mkdirp.core.js
console.log("[+] Loading mkdirp core");
require('../mkdirp.core.js');

// TEST multipart.core.js
console.log("[+] Loading multipart core");
test = require('../multipart.core.js');
for(var exp in test)
{
		var tested = new test[exp]();
}

// TEST router.core.js
console.log("[+] Loading router core");
require('../router.core.js');

console.log('[+] CORE TEST OK');


text:
<?php
include("application/libraries/cezpdf.php");
include("application/libraries/class.backgroundpdf.php");
class Room extends CI_Controller{
    function __construct(){
        parent::__construct();
        $this->load->model('Room_model');
        $this->load->model('Users_model');
        $this->load->helper('form');
        if(!isset($this->session->userdata['home_user'])||$this->session->userdata['home_user']==null){
        redirect(base_url());
        }
    }
    public function index(){
       $list=$this->Room_model->get_list();
         //datos para el menu

        $usercode=$this->session->userdata['home_user'];

        $userlist=$this->Users_model->edit($usercode);//metodo llamar datos por codigo
        $data['user']=$userlist->person_Name.' '.$userlist->person_LastName;
        $data['imagen']=$userlist->person_Photo;
        //FIN datos para el menu
        $data['list']=$list;
        $data['number']="";
        $data['floor']="";
		$data['precio']="";
        $data['estado']=form_dropdown('estado', array('1'=> 'Actuales','0'=> 'Pasados','2'=> 'Todos'), '1','id="estadob" class="form-control"');

        $data['active']="room";
        $data['titulo']="Mantenimiento de Habitaciones";

        $this->load->view("layout/menu",$data);
        $this->load->view("layout/header",$data);
        $this->load->view("habitacion_index",$data);
        $this->load->view("layout/footer");
    }
	public function nuevo(){
       $list=$this->Room_model->get_list();
         //datos para el menu

        $usercode=$this->session->userdata['home_user'];

        $userlist=$this->Users_model->edit($usercode);//metodo llamar datos por codigo
        $data['user']=$userlist->person_Name.' '.$userlist->person_LastName;
        $data['imagen']=$userlist->person_Photo;
        //FIN datos para el menu
        $data['list']=$list;
        $data['number']="";
        $data['floor']="";
        $data['estado']=form_dropdown('estado', array('1'=> 'Actuales','0'=> 'Pasados','2'=> 'Todos'), '1','id="estadob" class="form-control"');

        $data['active']="room";
        $data['titulo']="Mantenimiento de Habitaciones";

        $this->load->view("layout/menu",$data);
        $this->load->view("layout/header",$data);
        $this->load->view("nueva_habitacion",$data);
        $this->load->view("layout/footer");
    }
     public function search(){
         //datos para el menu
        $usercode=$this->session->userdata['home_user'];
        $userlist=$this->Users_model->edit($usercode);//metodo llamar datos por codigo
        $data['user']=$userlist->person_Name.' '.$userlist->person_LastName;
        $data['imagen']=$userlist->person_Photo;
        $roomscobros=$this->Room_model->get_cobros('0');
        $data['npay']=count($roomscobros);
        //FIN datos para el menu
         $number=$this->input->post('number');
         $floor=$this->input->post('floor');
          $state=$this->input->post('state');

         $result=$this->Room_model->search($number,$floor,$state);

         $data['list']=$result;

        $data['number']=$number;
        $data['floor']=$floor;
        $data['active']="room";
        $data['titulo']="Mantenimiento de Habitaciones";
       $this->load->view("layout/menu",$data);
        $this->load->view("layout/header",$data);
        $this->load->view("habitacion_index",$data);
        $this->load->view("layout/footer");
        }
    public function add_room(){
		 $bath =$this->input->post('bath');
         $laundry=$this->input->post('laundry');
         $cable=$this->input->post('cable');
         $internet=$this->input->post('internet');
         //$datepay=$this->input->post('datepay');

        if($bath==""){$bath="0";}
        if($laundry==""){$laundry="0";}
        if($cable==""){$cable="0";}
        if($internet==""){$internet="0";}

        $filter = new stdClass();
		$filter->room_Number=$this->input->post('number');
        $filter->room_Floor=$this->input->post('floor');
        $filter->room_Size=$this->input->post('size');
        $filter->room_Price=$this->input->post('price');
        $filter->room_Description=$this->input->post('description');
        //$filter->room_Floors=$this->input->post('floors');
        //$filter->room_DatePay=$this->input->post('datepay');
        $filter->room_Bath=$bath;
        $filter->room_Laundry=$laundry;
        $filter->room_Cable=$cable;
        $filter->room_Internet=$internet;
        //$filter->room_Date= $datepay;
        $filter->room_Occupied=0;
        $filter->room_State=1;

        $result=$this->Room_model->add_room($filter);

        exit('{"result":"ok","codigo":"'.$result.'"}');

    }
    public function edit_room(){
         $id =$this->input->post('id');
         $bath =$this->input->post('bath');
         $laundry=$this->input->post('laundry');
         $cable=$this->input->post('cable');
         $internet=$this->input->post('internet');
         $datepay=$this->input->post('datepay');

        if($bath==""){$bath="0";}
        if($laundry==""){$laundry="0";}
        if($cable==""){$cable="0";}
        if($internet==""){$internet="0";}

        $filter = new stdClass();
        $filter->room_Number=$this->input->post('number');
        $filter->room_Floor=$this->input->post('floor');
        $filter->room_Size=$this->input->post('size');
        $filter->room_Price=$this->input->post('price');
        $filter->room_Description=$this->input->post('description');
        $filter->room_Floors=$this->input->post('floors');
        $filter->room_DatePay=$datepay;
        $filter->room_Bath=$bath;
        $filter->room_Laundry=$laundry;
        $filter->room_Cable=$cable;
        $filter->room_Internet=$internet;
		$filter->room_Date= $datepay;
        $filter->room_Occupied=0;
        $filter->room_State=1;

        $result=$this->Room_model->edit_room($filter,$id);

        exit('{"result":"ok","codigo":"'.$result.'"}');

    }
     public function delete_room(){
         $coderoom =$this->input->post('coderoom');

        $result=$this->Room_model->delete_room($coderoom);

        exit('{"result":"ok","codigo":"'.$result.'"}');
    }
    public function listedit_room(){

         $code=$this->input->post('coderoom');

         $result=$this->Room_model->edit($code);

         echo json_encode($result);
    }
    public function desocupar_room(){
        $coderoom =$this->input->post('coderoom');

        $this->Room_model->desocupar_room($coderoom);
        $result=$this->Room_model->limpiar_inquilino($coderoom);
        exit('{"result":"ok","codigo":"'.$result.'"}');
    }
     public function print_pdf($numberb,$floorb,$stateb)
    {
        $this->cezpdf = new cezpdf('a4','portrait');
        $this->cezpdf->selectFont('fonts/Helvetica.afm');
        /* Cabecera */
        $suma = '';

        $listado = $this->Room_model->get_pdf($numberb,$floorb,$stateb);

        foreach ($listado as $key => $value) {
           $suma=$suma+$value->room_Price;
            $db_data[] = array(
                'col1' => $key + 1,
                'col2' => $value->room_Number,
                'col3' => $value->room_Floor,
                'col4' => $value->room_Size.'m',
                'col5' => 'S/.'.number_format($value->room_Price,2),
                'col6' => $value->room_Description,
                'col7' => $value->room_Floors
            );
        }
          $db_data[] = array(
                'col1' => '',
                'col2' => '',
                'col3' => '',
                'col4' => 'Total',
                'col5' => 'S/.'.number_format($suma,2),
                'col6' => '',
                'col7' => ''
            );

        $col_names = array(
            'col1' => 'Itm',
            'col2' => 'N'.utf8_decode('°').' DE CUARTO',
            'col3' => 'PLANTA',
            'col4' => ''.utf8_decode('TAMAÑO').'',
            'col5' => 'PRECIO',
            'col6' => 'DESCRIPCION',
            'col7' => 'PISOS'
        );

    $this->cezpdf->ezText('', '', array("leading" => 5));

    //$this->cezpdf->ezImage(base_url()."assets/img/logo.jpg", 30, 130, 'full','left','');
	$this->cezpdf->ezText('', '', array("leading" => 0));

         if($stateb==0){$estado='DISPONIBLES'; $left='140';}
         else if($stateb==1){$estado='OCUPADOS'; $left='140';}
         else{$estado='';$left='170';}

	$this->cezpdf->ezText('TOTAL DE CUARTOS :   '.count($listado), 9, array("leading" => -50, 'left' => 200));
	$this->cezpdf->ezText('FECHA DE REPORTE   :   '.date('Y-m-d'), 9, array("leading" => 15, 'left' => 200));

	$this->cezpdf->ezText('', '', array("leading" => 5));
	$this->cezpdf->ezText(' LISTA DE CUARTOS '.$estado.'', 14, array("leading" => 38, 'left' => $left));
	$this->cezpdf->ezText('', '', array("leading" => 2));
	//$this->cezpdf->ezText('TOTAL DE INQUILINOS:   '.count($listado), 8, array("leading" => 15, 'left' => 40));
	$this->cezpdf->ezText('', '', array("leading" => 8));

        $this->cezpdf->ezTable($db_data, $col_names, '', array(
            'width' => 500,
            'showLines' => 1,
            'shaded' => 1,//FONDO ENTRE LINEAS
            'showHeadings' => 1,
            'xPos' => 'center',
            'fontSize' => 8,
            'cols' => array(
                'col1' => array('width' => 25, 'justification' => 'center'),
                'col2' => array('width' => 75, 'justification' => 'center'),
                'col3' => array('width' => 45, 'justification' => 'center'),
                'col4' => array('width' => 45, 'justification' => 'center'),
                'col5' => array('width' => 60, 'justification' => 'center'),
                'col6' => array('width' => 170, 'justification' => 'center'),
                'col7' => array('width' => 35, 'justification' => 'center')
            )
        ));

        $cabecera = array('Content-Type' => 'application/pdf', 'Content-Disposition' => 'nama_file.pdf', 'Expires' => '0', 'Pragma' => 'cache', 'Cache-Control' => 'private');
        $this->cezpdf->ezStream($cabecera);
    }
}
?>


text:
use rustc_data_structures::fx::FxHashSet;
use rustc_middle::mir::visit::{PlaceContext, Visitor};
use rustc_middle::mir::{
    Local, Location, Place, Statement, StatementKind, Terminator, TerminatorKind,
};

use crate::MirBorrowckCtxt;

impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
    /// Walks the MIR adding to the set of `used_mut` locals that will be ignored for the purposes
    /// of the `unused_mut` lint.
    ///
    /// `temporary_used_locals` should contain locals that were found to be temporary, mutable and
    ///  used from borrow checking. This function looks for assignments into these locals from
    ///  user-declared locals and adds those user-defined locals to the `used_mut` set. This can
    ///  occur due to a rare case involving upvars in closures.
    ///
    /// `never_initialized_mut_locals` should contain the set of user-declared mutable locals
    ///  (not arguments) that have not already been marked as being used.
    ///  This function then looks for assignments from statements or the terminator into the locals
    ///  from this set and removes them from the set. This leaves only those locals that have not
    ///  been assigned to - this set is used as a proxy for locals that were not initialized due to
    ///  unreachable code. These locals are then considered "used" to silence the lint for them.
    ///  See #55344 for context.
    crate fn gather_used_muts(
        &mut self,
        temporary_used_locals: FxHashSet<Local>,
        mut never_initialized_mut_locals: FxHashSet<Local>,
    ) {
        {
            let mut visitor = GatherUsedMutsVisitor {
                temporary_used_locals,
                never_initialized_mut_locals: &mut never_initialized_mut_locals,
                mbcx: self,
            };
            visitor.visit_body(&visitor.mbcx.body);
        }

        // Take the union of the existed `used_mut` set with those variables we've found were
        // never initialized.
        debug!("gather_used_muts: never_initialized_mut_locals={:?}", never_initialized_mut_locals);
        self.used_mut = self.used_mut.union(&never_initialized_mut_locals).cloned().collect();
    }
}

/// MIR visitor for collecting used mutable variables.
/// The 'visit lifetime represents the duration of the MIR walk.
struct GatherUsedMutsVisitor<'visit, 'cx, 'tcx> {
    temporary_used_locals: FxHashSet<Local>,
    never_initialized_mut_locals: &'visit mut FxHashSet<Local>,
    mbcx: &'visit mut MirBorrowckCtxt<'cx, 'tcx>,
}

impl GatherUsedMutsVisitor<'_, '_, '_> {
    fn remove_never_initialized_mut_locals(&mut self, into: Place<'_>) {
        // Remove any locals that we found were initialized from the
        // `never_initialized_mut_locals` set. At the end, the only remaining locals will
        // be those that were never initialized - we will consider those as being used as
        // they will either have been removed by unreachable code optimizations; or linted
        // as unused variables.
        self.never_initialized_mut_locals.remove(&into.local);
    }
}

impl<'visit, 'cx, 'tcx> Visitor<'tcx> for GatherUsedMutsVisitor<'visit, 'cx, 'tcx> {
    fn visit_terminator(&mut self, terminator: &Terminator<'tcx>, location: Location) {
        debug!("visit_terminator: terminator={:?}", terminator);
        match &terminator.kind {
            TerminatorKind::Call { destination: Some((into, _)), .. } => {
                self.remove_never_initialized_mut_locals(*into);
            }
            TerminatorKind::DropAndReplace { place, .. } => {
                self.remove_never_initialized_mut_locals(*place);
            }
            _ => {}
        }

        self.super_terminator(terminator, location);
    }

    fn visit_statement(&mut self, statement: &Statement<'tcx>, location: Location) {
        if let StatementKind::Assign(box (into, _)) = &statement.kind {
            debug!(
                "visit_statement: statement={:?} local={:?} \
                    never_initialized_mut_locals={:?}",
                statement, into.local, self.never_initialized_mut_locals
            );
            self.remove_never_initialized_mut_locals(*into);
        }

        self.super_statement(statement, location);
    }

    fn visit_local(&mut self, local: &Local, place_context: PlaceContext, location: Location) {
        if place_context.is_place_assignment() && self.temporary_used_locals.contains(local) {
            // Propagate the Local assigned at this Location as a used mutable local variable
            for moi in &self.mbcx.move_data.loc_map[location] {
                let mpi = &self.mbcx.move_data.moves[*moi].path;
                let path = &self.mbcx.move_data.move_paths[*mpi];
                debug!(
                    "assignment of {:?} to {:?}, adding {:?} to used mutable set",
                    path.place, local, path.place
                );
                if let Some(user_local) = path.place.as_local() {
                    self.mbcx.used_mut.insert(user_local);
                }
            }
        }
    }
}


text:
{-# htermination foldFM_GE :: ((Ratio Int) -> b -> c -> c) -> c -> (Ratio Int) -> FiniteMap (Ratio Int) b -> c #-}
import FiniteMap


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

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<title>libpqxx: pqxx::in_doubt_error Class Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="navtree.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

libpqxx
    4.0.1

Main Page

Related Pages

Modules

Namespaces

Classes

Class List

Class Index

Class Hierarchy

Class Members

Public Member Functions |
List of all members

pqxx::in_doubt_error Class Reference
Exception classes

"Help, I don't know whether transaction was committed successfully!"
 More...

#include <except.hxx>

Inheritance diagram for pqxx::in_doubt_error:

  <map id="pqxx::in_doubt_error_map" name="pqxx::in_doubt_error_map">
<area href="a00038.html" title="Run-time failure encountered by libpqxx, similar to std::runtime_error." alt="pqxx::failure" shape="rect" coords="0,56,129,80"/>
<area href="a00074.html" title="Mixin base class to identify libpqxx-specific exception types." alt="pqxx::pqxx_exception" shape="rect" coords="0,0,129,24"/>
</map>

Public Member Functions

 	in_doubt_error (const std::string &)

 Public Member Functions inherited from pqxx::failure

 	failure (const std::string &)

 Public Member Functions inherited from pqxx::pqxx_exception

virtual 	~pqxx_exception ()=0  throw ()

 	Support run-time polymorphism, and keep this class abstract.

virtual const PQXX_CONST

std::exception & 	base () const =0  throw ()

 	Return std::exception base-class object.

Detailed Description

"Help, I don't know whether transaction was committed successfully!"

Exception that might be thrown in rare cases where the connection to the database is lost while finishing a database transaction, and there's no way of telling whether it was actually executed by the backend. In this case the database is left in an indeterminate (but consistent) state, and only manual inspection will tell which is the case.

Constructor & Destructor Documentation

          pqxx::in_doubt_error::in_doubt_error
          (
          const std::string &
          whatarg	)

explicit

The documentation for this class was generated from the following files:

except.hxx

except.cxx

pqxx

in_doubt_error

Generated on Sun Jan 20 2013 13:09:10 for libpqxx by

     1.8.1.2


text:
package engine.expressions.parser;

/**
* User: Oleksiy Pylypenko
* Date: 3/5/13
* Time: 3:42 PM
*/
public enum ClauseType {
    EQUATIONS,
    EQUATION, // T
    ADDITIVE_EXPRESSION, // T
    MULTIPLICATIVE_EXPRESSION, // T
    PRIMARY_EXPRESSION, //
    MATH_FUNCTION, // T
    ARGUMENTS, // T
    PARENTHESES, // T
    VARIABLE, // T
    CONSTANT; // T

    public <T> T accept(ClauseTypeVisitor<T> visitor) throws Exception {
        switch (this) {
            case EQUATIONS: return visitor.equations();
            case EQUATION: return visitor.equation();
            case ADDITIVE_EXPRESSION: return visitor.additiveExpression();
            case MULTIPLICATIVE_EXPRESSION: return visitor.multiplicativeExpression();
            case PRIMARY_EXPRESSION: return visitor.primaryExpression();
            case PARENTHESES: return visitor.parentheses();
            case CONSTANT: return visitor.constant();
            case VARIABLE: return visitor.variable();
            case ARGUMENTS: return visitor.arguments();
            case MATH_FUNCTION: return visitor.mathFunction();
        }
        throw new UnsupportedOperationException(this + ".accept(" + visitor + ")");
    }
}


text:
PDFtoAudioBook
==============

This is a prototype of an Android app which takes a pdf and creates an
AudioBook.

Dependancies on the Device
----------------------------
* [Android 2.2] the device should be running 2.2 or better
* [TextToSpeech] is turned on (see Settings)
* to have comercial quality audio you can use
Loquendo it's a commercial voice which costs about 5-6$ (search Market)
* [Voice Recognition] is turned on (see Settings)
* [Internet Connection] You need an internet connection to use the Voice
Recognizer, and to extract the text from the PDF.
* [File Manager] a file manager such as OI File Manager (search Market)
* [Mind Mapping] a mind mapping app such as Thinking Space (search market)

Library Dependancies
--------------------
* None

Contributing
-------------

Want to contribute? Great!

1. Fork it
2. Create a branch (git checkout -b my_copy)
3. Commit your changes (git commit -am "added some more regex to the text
cleaner")
4. Push to the branch (git push origin my_copy)
5. Create an Issue with a link to your branch

Instalation using Eclipse
-------------------------
* Download the source code
* Create an Android project and import the source files
* Install it onto your device

Using the application
---------------------
* Check the device settings for Voice input & output to be sure that TextToSpeech
and VoiceRecognition are enabled
* Save some PDFs onto your device via the internet or SDCARD
* Open the file manager, browse to your pdf, click on it and a menu will appear
allowing you to register the pdf into your audio book list
* Alternatively, you can open the application and listen to the instructions

PDFtoAudioBook is released under the Apache License.


text:
require 'faye'
require 'bbc_service_map'

class FayeRelay
  include Radiodan::Logging

  def initialize(*config)
    @options  = config.shift
    @port     = @options[:port]
  end

  def call(player)
    faye_url = "http://localhost:#{@port}/faye"
    @player = player
    @client = Faye::Client.new(faye_url)

    logger.info "Client on #{faye_url}"

    @client.subscribe('/power') do
      logger.info "/power"
      @player.trigger_event :toggle_power
    end

    @client.subscribe('/volume') do |value|
      logger.info "/volume #{value}"
      @player.trigger_event :change_volume, value
    end

    @client.subscribe('/station') do |action_or_id|
      case action_or_id
      when "next"
        action_or_id = :next
      when "previous"
        action_or_id = :previous
      end

      logger.info "/station #{action_or_id}"

      @player.trigger_event :change_station, action_or_id
    end

    @client.subscribe('/avoid') do |type|
      logger.info "/avoid #{type}"
      @player.trigger_event :avoid, type.to_sym
    end

    player.register_event :sync do |playlist|
      # Lookup the stream name from the playlist and convert
      # to a BBC Programmes service id e.g. 'BBC Radio 2' -> 'radio2'
      begin
        bbc_service = BBCRD::ServiceMap.lookup(playlist.tracks.first.attributes[:Name])
        playlist.tracks.first.attributes[:id] = bbc_service.programmes_id if bbc_service
        @client.publish('/info', playlist.attributes)
      rescue
        logger.error "Error publishing playlist attributes at Sync"
      end
    end

    player.register_event :now_playing do |info|
      @client.publish('/now_playing', info)
    end

  end
end


text:
<?php

/**
 * Provides flexible input validation for form and model input. Also see
 * the `Form` class for examples on implementing matching client-side
 * validation through Elefant's `jquery.verify_values.js` jQuery plugin.
 *
 * Usage:
 *
 *     <?php
 *
 *     // single value
 *     if (! Validator::validate ($_POST['email'], 'email')) {
 *         // failed
 *     }
 *
 *     // list of values
 *     $failed = Validator::validate_list (
 *         $_POST,
 *         'apps/myapp/forms/myform.php'
 *     );
 *
 *     if (count ($failed) > 0) {
 *         // failed
 *     }
 */
class Validator {
	/**
	 * The full details of which rules failed in a call to
	 * `Validator::validate_list()`.
	 */
	public static $invalid = array ();

	/**
	 * Verifies the specified value, useful for input validation.
	 * Pass the value, a type of validation, and a validator.
	 * Types include:
	 *
	 * - `skip_if_empty` - a special verifier that tells `validate_list()` to skip
	 *                   validation on the field if it's been left blank.
	 * - `file` - a special verifier that tells `validate_list()` to check if it's
	 *          a valid uploaded file.
	 * - `filetype` - a special verifier that tells `validate_list()` to check if the
	 *              file name contains one of a list of comma-separated extensions.
	 * - `regex` - calls `preg_match($validator, $value)`
	 * - `type` - calls `is_$validator($value)`
	 * - `callback` - calls `call_user_func($validator, $value)`
	 * - `email` - a valid email address
	 * - `url` - a valid url
	 * - `range` - number within a range e.g., `123-456`
	 * - `length` - string of length, $verifier examples: `6, 6+, 6-12, 12-`
	 * - `gt` - greater than
	 * - `gte` - greater than or equal to
	 * - `lt` - less than
	 * - `lte` - less than or equal to
	 * - `empty` - value is empty
	 * - `not empty` - value is not empty
	 * - `contains` - `stristr($value, $validator)`
	 * - `equals` - equality test
	 * - `date` - date value (`YYYY-MM-DD`)
	 * - `time` - time value (`HH:MM:SS`)
	 * - `datetime` - date and time value (`YYYY-MM-DD HH:MM:SS`)
	 * - `header` - verifies there are no newlines so spammers can't pass headers to `mail()`
	 * - `unique` - verifies it's unique to a table and column in the database,
	 *            `$verifier` should be `'table_name.column_name'`
	 * - `exists` - verifies that a file exists in the specified directory,
	 *            `$verifier` should be a directory path with no trailing /,
	 *            or optionally a file path with `%s` in it for the form value.
	 * - `matches` - Matches another variable, e.g., `"$_POST['name']"`, must be a
	 *             global or superglobal.
	 *
	 * Functions must accept only the value of the variable and return
	 * a boolean value.
	 *
	 * You can also specify 'not' in front of any rule to check for its
	 * opposite, for example "not empty".
	 *
	 * For array elements (e.g., `<input name="name[]" />`), you can also specify
	 * 'each' in front of any rule and the rule will be applied to each element
	 * of the array instead of the array itself. Note that the 'each' must come
	 * before 'not', for example "each email" would make sure each is a valid
	 * email address, and "each not empty" would make sure each is not empty.
	 */
	public static function validate ($value, $type, $validator = false) {
		if ($type === 'default') {
			return true;
		}
		if (preg_match ('/^each (.+)$/i', $type, $regs)) {
			if (! is_array ($value)) {
				// can't specify each on non-array value
				return false;
			}
			foreach ($value as $val) {
				if (! Validator::validate ($val, $regs[1], $validator)) {
					return false;
				}
			}
			return true;
		}
		if (preg_match ('/^not (.+)$/i', $type, $regs)) {
			return ! Validator::validate ($value, $regs[1], $validator);
		}
		switch ($type) {
			case 'matches':
				if (preg_match ('/\$(_[a-z]+|GLOBALS)\[[\'"]?([a-z0-9_-]+)[\'"]?\]/i', $validator, $regs)) {
					// Can't dynamically reference superglobals, so instead...
					switch ($regs[1]) {
						case '_POST':
							return ($value === $_POST[$regs[2]]);
						case '_GET':
							return ($value === $_GET[$regs[2]]);
						case '_REQUEST':
							return ($value === $_REQUEST[$regs[2]]);
						case '_SERVER':
							return ($value === $_SERVER[$regs[2]]);
						case '_FILES':
							return ($value === $_FILES[$regs[2]]);
						case '_COOKIE':
							return ($value === $_COOKIE[$regs[2]]);
						case '_SESSION':
							return ($value === $_SESSION[$regs[2]]);
						case '_ENV':
							return ($value === $_ENV[$regs[2]]);
						case 'GLOBALS':
							return ($value === $GLOBALS[$regs[2]]);
					}
				}
				return false;

			case 'regex':
				return (bool) preg_match ($validator, $value);

			case 'type':
				return call_user_func ('is_' . $validator, $value);

			case 'callback':
				return call_user_func ($validator, $value);

			case 'range':
				list ($min, $max) = explode ('-', $validator);
				return (($min <= $value) && ($value <= $max));

			case 'empty':
				if ($value === '0') {
					return false;
				}
				return empty ($value);

			case 'length':
				if (preg_match ('/^([0-9]+)([+-]?)([0-9]*)$/', $validator, $regs)) {
					if (! empty ($regs[3])) {
						if (strlen ($value) < $regs[1] || strlen ($value) > $regs[3]) {
							return false;
						}
					} elseif ($regs[2] === '+' && strlen ($value) < $regs[1]) {
						return false;
					} elseif ($regs[2] === '-' && strlen ($value) > $regs[1]) {
						return false;
					} elseif (empty ($regs[2]) && strlen ($value) != $regs[1]) {
						return false;
					}
				}
				return true;

			case 'contains':
				return (bool) stristr ($value, $validator);

			case 'equals':
				return ($value == $validator);

			case 'gt':
				return ($value > $validator);

			case 'gte':
				return ($value >= $validator);

			case 'lt':
				return ($value < $validator);

			case 'lte':
				return ($value <= $validator);

			case 'email':
				if (! filter_var ($value, FILTER_VALIDATE_EMAIL)) {
					return false;
				}

				// also verify that the domain isn't just 'localhost'
				// which would allow garbage in
				list ($one, $two) = explode ('@', $value);
				if (strpos ($two, '.') === false) {
					return false;
				}
				return true;

			case 'url':
				if (! filter_var ($value, FILTER_VALIDATE_URL)) {
					return false;
				}
				if (strpos ($value, '.') === false) {
					return false;
				}
				return true;

			case 'header':
				return ! (bool) preg_match ('/[\r\n]/s', $value);

			case 'date':
				return (bool) preg_match ('/^[0-9]{4}-[0-9]{2}-[0-9]{2}$/', $value);

			case 'time':
				return (bool) preg_match ('/^[0-9]{2}:[0-9]{2}:[0-9]{2}$/', $value);

			case 'datetime':
				return (bool) preg_match ('/^[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}$/', $value);

			case 'unique':
				list ($table, $column) = preg_split ('/[\.:\/]/', $validator);
				$res = DB::shift ('select ' . $column . ' from ' . $table . ' where ' . $column . ' = ?', $value);
				if ($res == $value) {
					return false;
				}
				return true;

			case 'exists':
				if (strpos ($validator, '%s') !== false) {
					return file_exists (sprintf ($validator, $value));
				}
				return file_exists ($validator . '/' . $value);
		}
		// If tests fail, be safe and fail by default
		return false;
	}

	/**
	 * Validate a list of values, such as `$_GET` or `$_POST` data against
	 * a list of validation rules. If the rules are a string, it will
	 * look for a file and parse it using `parse_ini_file()` for the rules.
	 * The format is as follows:
	 *
	 *     [field1]
	 *     email = 1
	 *
	 *     [field2]
	 *     type = string
	 *     regex = "/^[a-z]+$/i"
	 *
	 *     [field3]
	 *     skip_if_empty = 1
	 *     unique = "table.column"
	 *
	 * Returns an array of failed fields. If the array is empty, everything
	 * passed.
	 */
	public static function validate_list ($values, $validations = array ()) {
		if (is_string ($validations) && file_exists ($validations)) {
			$validations = parse_ini_file ($validations, true);
		}
		$failed = array ();
		self::$invalid = array ();
		foreach ($validations as $n => $validators) {
			if (strpos ($n, ':') !== false) {
				list ($name, $rule) = explode (':', $n);
			} else {
				$name = $n;
				$rule = $n;
			}

			if (in_array ($name, $failed)) {
				continue;
			}

			foreach ($validators as $type => $validator) {
				if ($type === 'file') {
					if (! is_uploaded_file ($_FILES[$name]['tmp_name'])) {
						$failed[] = $rule;
						self::$invalid[$name] = array (
							'field' => $name,
							'type'  => $type,
							'validator' => $validator,
							'value' => $_FILES[$name]['name']
						);
						break;
					} else {
						continue;
					}
				}
				if ($type === 'filetype') {
					$extensions = preg_split ('/, ?/', trim (strtolower ($validator)));
					if ($extensions === false) {
						$extensions = array ($validator);
					}
					$extension = strtolower (pathinfo ($_FILES[$name]['name'], PATHINFO_EXTENSION));
					if (! in_array ($extension, $extensions)) {
						$failed[] = $rule;
						self::$invalid[$name] = array (
							'field' => $name,
							'type'  => $type,
							'validator' => $validator,
							'value' => $_FILES[$name]['name']
						);
						break;
					} else {
						continue;
					}
				}
				if ($type === 'skip_if_empty') {
					if (is_array ($values[$name])) {
						foreach ($values[$name] as $k => $v) {
							if (empty ($v)) {
								// Unset empty array values so they're not checked against the other rules
								unset ($values[$name][$k]);
							}
						}
						continue;
					} elseif (empty ($values[$name]) && (! isset ($_FILES[$name]) || $_FILES[$name]['error'] === 4)) {
						break;
					} else {
						continue;
					}
				}
				if ($type === 'validate_on_change') {
					continue;
				}
				if (! isset ($values[$name]) || ! Validator::validate ($values[$name], $type, $validator)) {
					$failed[] = $rule;
					self::$invalid[$name] = array (
						'field' => $name,
						'type'  => $type,
						'validator' => $validator,
						'value' => isset ($values[$name]) ? $values[$name] : null
					);
					break;
				}
			}
		}
		return $failed;
	}
}


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

namespace RecSys.Core
{
    /// <summary>
    /// This class implements some special functions.
    /// </summary>
    public class SpecialFunctions
    {
        /// <summary>
        /// The inverse-logit function, i.e. Logistic function
        /// See http://en.wikipedia.org/wiki/Logistic_function
        /// and http://en.wikipedia.org/wiki/Logit
        /// </summary>
        /// <param name="alpha"></param>
        /// <returns>The inverse-logit output [0,1] of the intput value.</returns>
        public static double InverseLogit(double alpha)
        {
            double expOfAlpha = Math.Exp(alpha);
            return expOfAlpha / (1 + expOfAlpha);
        }
    }
}


text:
package sgl.glfw.error;

import static org.lwjgl.glfw.GLFW.GLFW_OUT_OF_MEMORY;

/**
 * @author link
 */
public class GLFWOutOfMemoryError extends GLFWError {
	public GLFWOutOfMemoryError(long description) {
		super(GLFW_OUT_OF_MEMORY, description);
	}
}


text:
<?php namespace Wireshell\Tests\Commands\Common;

use Symfony\Component\Console\Tester\CommandTester;
use Symfony\Component\Console\Question\Question;
use Ofbeaton\Console\Tester\QuestionTester;
use Ofbeaton\Console\Tester\UnhandledQuestionException;
use Wireshell\Tests\BaseTestCase as Base;
use Wireshell\Commands\Common\NewCommand;

class NewCommandTest extends Base {
   use QuestionTester;

    /**
     * @field array default config values
     */
    protected $defaults = array(
        '--timezone' => 'Europe\Berlin',
        '--httpHosts' => 'pwtest.dev',
        '--username' => 'admin',
        '--userpass' => 'password',
        '--useremail' => 'test@wireshell.pw'
    );

    /**
     * @before
     */
    public function setupCommand() {
        $this->app->add(new NewCommand());
        $this->command = $this->app->find('new');
        $this->tester = new CommandTester($this->command);

        $credentials = array(
            '--dbUser' => $GLOBALS['DB_USER'],
            '--dbPass' => $GLOBALS['DB_PASSWD'],
            '--dbName' => $GLOBALS['DB_DBNAME']
        );

        $this->extends = array(
            'command'  => $this->command->getName(),
            'directory' => Base::INSTALLATION_FOLDER,
        );

        $this->defaults = array_merge($this->defaults, $credentials, $this->extends);
    }

    public function testDownload() {
        $this->checkInstallation();
        $options = array('--no-install' => true, '--src' => Base::INSTALLATION_ARCHIVE);
        $this->tester->execute(array_merge($this->defaults, $options));

        $this->assertDirectoryExists(Base::INSTALLATION_FOLDER);
        $this->assertDirectoryExists(Base::INSTALLATION_FOLDER . '/wire');
        $this->assertDirectoryNotExists(Base::INSTALLATION_FOLDER . '/site');
    }

    /**
      * @depends testDownload
      * @expectedException RuntimeException
      * @expectedExceptionMessageRegExp /(Database connection information did not work)./
      */
    public function testInstallWrongPassword() {
        // check ProcessWire has not been installed yet
        if ($this->fs->exists(Base::INSTALLATION_FOLDER . '/site/config.php')) return;

        // return the input you want to answer the question with
        $this->mockQuestionHelper($this->command, function($text, $order, Question $question) {
            if (strpos($text, 'database user name') !== false) return 'whatever';
            if (strpos($text, 'database password') !== false) return 'wrong';

            throw new UnhandledQuestionException();
        });

        $options = array(
            '--src' => Base::INSTALLATION_ARCHIVE,
            '--dbPass' => 'wrong'
        );

        $this->tester->execute(array_merge($this->defaults, $options));
    }

    /**
      * @depends testDownload
      * @expectedExceptionMessageRegExp /(enter a valid email address)/
      */
    public function testInstallInvalidEmailAddress() {
        // check ProcessWire has not been installed yet
        if ($this->fs->exists(Base::INSTALLATION_FOLDER . '/site/config.php')) return;

        // return the input you want to answer the question with
        $this->mockQuestionHelper($this->command, function($text, $order, Question $question) {
            if (strpos($text, 'admin email address') !== false) return 'whatever';

            throw new UnhandledQuestionException();
        });

        $options = array(
            '--src' => Base::INSTALLATION_ARCHIVE,
            '--useremail' => 'invalid'
        );

        $this->tester->execute(array_merge($this->defaults, $options));
    }

    /**
     * @depends testDownload
     */
    public function testInstall() {
        // check ProcessWire has not been installed yet
        if ($this->fs->exists(Base::INSTALLATION_FOLDER . '/site/config.php')) return;

        $this->tester->execute($this->defaults);
        $output = $this->tester->getDisplay();

        $this->assertDirectoryExists(Base::INSTALLATION_FOLDER . '/site');
        $this->assertFileExists(Base::INSTALLATION_FOLDER . '/site/config.php');
        $this->assertContains('Congratulations, ProcessWire has been successfully installed.', $output);
    }

    /**
     * @depends testInstall
     * @expectedExceptionMessageRegExp /(There is already a \')(.*)(\' project)/
     */
    public function testIsInstalled() {
        $this->tester->execute($this->defaults);
    }
}