text:
kernel.userspace = setmetatable({}, {__index = kernel._K})

kernel.userspace.computer = {}

kernel.userspace.computer.address = kernel._K.computer.address
kernel.userspace.computer.tmpAddress = kernel._K.computer.tmpAddress
kernel.userspace.computer.freeMemory = kernel._K.computer.freeMemory
kernel.userspace.computer.totalMemory = kernel._K.computer.totalMemory
kernel.userspace.computer.energy = kernel._K.computer.energy
kernel.userspace.computer.maxEnergy = kernel._K.computer.maxEnergy
kernel.userspace.computer.isAvailable = kernel._K.computer.isAvailable
kernel.userspace.computer.users = kernel._K.computer.users
kernel.userspace.computer.addUser = kernel._K.computer.addUser
kernel.userspace.computer.removeUser = kernel._K.computer.removeUser
kernel.userspace.computer.pushSignal = kernel._K.computer.pushSignal
kernel.userspace.computer.uptime = kernel._K.computer.uptime
kernel.userspace.computer.getBootAddress = kernel._K.computer.getBootAddress

kernel.userspace.computer.shutdown = kernel.modules.gc.shutdown

kernel.userspace.computer.pullSignal = function(timeout)
    kernel.modules.threading.currentThread.deadline = computer.uptime() + (timeout or math.huge)
    return coroutine.yield("signal")
end

kernel.userspace.computer.hasSignal = function(sigType)
    for _,v in ipairs(kernel.modules.threading.currentThread.eventQueue) do
        if v[1] == (sigType or "signal") then
            return true
        end
    end
    return false
end

kernel.userspace.coroutine = {}

kernel.userspace.os = setmetatable({}, {__index = kernel._K.os})

kernel.userspace.os.remove = kernel.modules.vfs.remove
kernel.userspace.os.rename = kernel.modules.vfs.rename

function kernel.userspace.os.spawn(prog, ...)
    local isThread = type(prog) == "function"
    local name = isThread and kernel.modules.threading.currentThread.name or "unknown"
    if type(prog) == "string" then
        name = kernel.modules.vfs.resolve(prog)
        prog, reason = kernel._G.loadfile(prog, nil, kernel._G)
        if not prog then
            error(tostring(reason) .. ": " .. tostring(prog))
        end
    end
    local thread = kernel.modules.threading.spawn(prog, 0, name, isThread, _, ...)
    thread.io_output = kernel.modules.threading.currentThread.io_output
    thread.io_input = kernel.modules.threading.currentThread.io_input
    thread.io_error = kernel.modules.threading.currentThread.io_error
    return thread.pid
end

function kernel.userspace.os.spawnp(prog, stdin, stdout, stderr, ...)
    local isThread = type(prog) == "function"
    local name = isThread and kernel.modules.threading.currentThread.name or "unknown"
    if type(prog) == "string" then
        name = kernel.modules.vfs.resolve(prog)
        prog, reason = kernel._G.loadfile(prog, nil, kernel._G)
        if not prog then
            error(tostring(reason) .. ": " .. tostring(prog))
        end
    end
    local thread = kernel.modules.threading.spawn(prog, 0, name, isThread, _, ...)
    thread.env["_"] = name
    thread.io_output = stdout --todo: check types!
    thread.io_error = stderr --todo: check types!
    thread.io_input = stdin
    return thread.pid
end

function kernel.userspace.os.kill(pid, signal)
    return kernel.modules.threadUtil.userKill(pid, signal or "terminate")
end

function kernel.userspace.os.exit()
    kernel.modules.threading.kill(kernel.modules.threading.currentThread.pid)
    coroutine.yield("yield")
end

function kernel.userspace.os.sleep(time)
    kernel.modules.threading.currentThread.deadline = computer.uptime() + (time or 0)
    coroutine.yield("yield")
end

function kernel.userspace.os.getenv(name)
    return kernel.modules.threading.currentThread.env[name]
end

function kernel.userspace.os.setenv(name, value)
    kernel.modules.threading.currentThread.env[name] = value
end

function kernel.userspace.dofile(filename, env)
  local program, reason = kernel.userspace.loadfile(filename, nil, env or kernel._G)
  if not program then
    return error(reason, 0)
  end
  return program()
end

function kernel.userspace.loadfile(filename, mode, env)
  local file, reason = kernel.modules.io.io.open(filename)
  if not file then
    return nil, reason
  end
  local source, reason = file:read("*a")
  file:close()
  if not source then
    return nil, reason
  end
  if string.sub(source, 1, 1) == "#" then
    local endline = string.find(source, "\n", 2, true)
    if endline then
      source = string.sub(source, endline + 1)
    else
      source = ""
    end
  end
  return kernel._G.load(source, "=" .. filename, mode, env or kernel._G)
end

function kernel.userspace.load(ld, source, mode, env)
    return load(ld, source, mode, env or kernel._G)
end

function kernel.userspace.print(...)
  local args = table.pack(...)
  kernel.modules.io.io.stdout:setvbuf("line")
  for i = 1, args.n do
    local arg = tostring(args[i])
    if i > 1 then
      arg = "\t" .. arg
    end
    kernel.modules.io.io.stdout:write(arg)
  end
  kernel.modules.io.io.stdout:write("\n")
  kernel.modules.io.io.stdout:setvbuf("no")
  kernel.modules.io.io.stdout:flush()
end

kernel.userspace.coroutine = {}

--lua 5.3 <-> 5.2 compat
kernel.userspace.bit32 = bit32 or load([[return {
    band = function(a, b) return a & b end,
    bor = function(a, b) return a | b end,
    bxor = function(a, b) return a ~ b end,
    bnot = function(a) return ~a end,
    rshift = function(a, n) return a >> n end,
    lshift = function(a, n) return a << n end,
}]])()


text:
"use strict";

module.exports = function(sequelize, DataTypes) {
  var students_classes = sequelize.define("students_classes", {
    id: {
      type: DataTypes.INTEGER,
      primaryKey: true,
      autoIncrement: true
    }
  }, {
    timestamps: false,
    classMethods: {
      associate: function(models) {
        students_classes.belongsTo(models.students, {
          foreignKey: 'student_id',
          onDelete: 'set null',
          onUpdate: 'cascade'
        });
        students_classes.belongsTo(models.classes, {
          foreignKey: 'class_id',
          onDelete: 'set null',
          onUpdate: 'cascade'
        });
      }
    }
  });
  return students_classes;
};

redpajama_set_name: RedPajamaGithub


text:
import os

import nipype.algorithms.rapidart as ra
import nipype.interfaces.spm as spm
import nipype.interfaces.utility as niu
import nipype.pipeline.engine as pe
logger = pe.logger
from ....interfaces.matlab import no_matlab

from ...smri.freesurfer.utils import create_getmask_flow

def create_spm_preproc(name='preproc'):
    """Create an spm preprocessing workflow with freesurfer registration and
    artifact detection.

    The workflow realigns and smooths and registers the functional images with
    the subject's freesurfer space.

    Example
    -------

    >>> preproc = create_spm_preproc()
    >>> preproc.base_dir = '.'
    >>> preproc.inputs.inputspec.fwhm = 6
    >>> preproc.inputs.inputspec.subject_id = 's1'
    >>> preproc.inputs.inputspec.subjects_dir = '.'
    >>> preproc.inputs.inputspec.functionals = ['f3.nii', 'f5.nii']
    >>> preproc.inputs.inputspec.norm_threshold = 1
    >>> preproc.inputs.inputspec.zintensity_threshold = 3

    Inputs::

         inputspec.functionals : functional runs use 4d nifti
         inputspec.subject_id : freesurfer subject id
         inputspec.subjects_dir : freesurfer subjects dir
         inputspec.fwhm : smoothing fwhm
         inputspec.norm_threshold : norm threshold for outliers
         inputspec.zintensity_threshold : intensity threshold in z-score

    Outputs::

         outputspec.realignment_parameters : realignment parameter files
         outputspec.smoothed_files : smoothed functional files
         outputspec.outlier_files : list of outliers
         outputspec.outlier_stats : statistics of outliers
         outputspec.outlier_plots : images of outliers
         outputspec.mask_file : binary mask file in reference image space
         outputspec.reg_file : registration file that maps reference image to
                                 freesurfer space
         outputspec.reg_cost : cost of registration (useful for detecting misalignment)
    """

    """
    Initialize the workflow
    """

    workflow = pe.Workflow(name=name)

    """
    Define the inputs to this workflow
    """

    inputnode = pe.Node(niu.IdentityInterface(fields=['functionals',
                                                      'subject_id',
                                                      'subjects_dir',
                                                      'fwhm',
                                                      'norm_threshold',
                                                      'zintensity_threshold']),
                        name='inputspec')

    """
    Setup the processing nodes and create the mask generation and coregistration
    workflow
    """

    poplist = lambda x: x.pop()
    realign = pe.Node(spm.Realign(), name='realign')
    workflow.connect(inputnode, 'functionals', realign, 'in_files')
    maskflow = create_getmask_flow()
    workflow.connect([(inputnode, maskflow, [('subject_id','inputspec.subject_id'),
                                             ('subjects_dir', 'inputspec.subjects_dir')])])
    maskflow.inputs.inputspec.contrast_type = 't2'
    workflow.connect(realign, 'mean_image', maskflow, 'inputspec.source_file')
    smooth = pe.Node(spm.Smooth(), name='smooth')
    workflow.connect(inputnode, 'fwhm', smooth, 'fwhm')
    workflow.connect(realign, 'realigned_files', smooth, 'in_files')
    artdetect = pe.Node(ra.ArtifactDetect(mask_type='file',
                                          parameter_source='SPM',
                                          use_differences=[True,False],
                                          use_norm=True,
                                          save_plot=True),
                        name='artdetect')
    workflow.connect([(inputnode, artdetect,[('norm_threshold', 'norm_threshold'),
                                             ('zintensity_threshold',
                                              'zintensity_threshold')])])
    workflow.connect([(realign, artdetect, [('realigned_files', 'realigned_files'),
                                            ('realignment_parameters',
                                             'realignment_parameters')])])
    workflow.connect(maskflow, ('outputspec.mask_file', poplist), artdetect, 'mask_file')

    """
    Define the outputs of the workflow and connect the nodes to the outputnode
    """

    outputnode = pe.Node(niu.IdentityInterface(fields=["realignment_parameters",
                                                       "smoothed_files",
                                                       "mask_file",
                                                       "reg_file",
                                                       "reg_cost",
                                                       'outlier_files',
                                                       'outlier_stats',
                                                       'outlier_plots'
                                                       ]),
                         name="outputspec")
    workflow.connect([
            (maskflow, outputnode, [("outputspec.reg_file", "reg_file")]),
            (maskflow, outputnode, [("outputspec.reg_cost", "reg_cost")]),
            (maskflow, outputnode, [(("outputspec.mask_file", poplist), "mask_file")]),
            (realign, outputnode, [('realignment_parameters', 'realignment_parameters')]),
            (smooth, outputnode, [('smoothed_files', 'smoothed_files')]),
            (artdetect, outputnode,[('outlier_files', 'outlier_files'),
                                    ('statistic_files','outlier_stats'),
                                    ('plot_files','outlier_plots')])
            ])
    return workflow

def create_vbm_preproc(name='vbmpreproc'):
    """Create a vbm workflow that generates DARTEL-based warps to MNI space

    Based on: http://www.fil.ion.ucl.ac.uk/~john/misc/VBMclass10.pdf

    Example
    -------

    >>> preproc = create_vbm_preproc()
    >>> preproc.inputs.inputspec.fwhm = 8
    >>> preproc.inputs.inputspec.structural_files = [os.path.abspath('s1.nii'), os.path.abspath('s3.nii')]
    >>> preproc.inputs.inputspec.template_prefix = 'Template'
    >>> preproc.run() # doctest: +SKIP

    Inputs::

         inputspec.structural_files : structural data to be used to create templates
         inputspec.fwhm: single of triplet for smoothing when normalizing to MNI space
         inputspec.template_prefix : prefix for dartel template

    Outputs::

         outputspec.normalized_files : normalized gray matter files
         outputspec.template_file : DARTEL template
         outputspec.icv : intracranial volume (cc - assuming dimensions in mm)

    """

    workflow = pe.Workflow(name=name)

    """
    Define the inputs to this workflow
    """

    inputnode = pe.Node(niu.IdentityInterface(fields=['structural_files',
                                                      'fwhm',
                                                      'template_prefix']),
                        name='inputspec')

    dartel_template = create_DARTEL_template()

    workflow.connect(inputnode, 'template_prefix', dartel_template, 'inputspec.template_prefix')
    workflow.connect(inputnode, 'structural_files', dartel_template, 'inputspec.structural_files')

    norm2mni = pe.Node(spm.DARTELNorm2MNI(modulate=True), name='norm2mni')
    workflow.connect(dartel_template, 'outputspec.template_file', norm2mni, 'template_file')
    workflow.connect(dartel_template, 'outputspec.flow_fields', norm2mni, 'flowfield_files')

    def getclass1images(class_images):
        class1images = []
        for session in class_images:
            class1images.extend(session[0])
        return class1images

    workflow.connect(dartel_template, ('segment.native_class_images', getclass1images), norm2mni, 'apply_to_files')
    workflow.connect(inputnode, 'fwhm', norm2mni, 'fwhm')

    def compute_icv(class_images):
        from nibabel import load
        from numpy import prod
        icv = []
        for session in class_images:
            voxel_volume = prod(load(session[0][0]).get_header().get_zooms())
            img = load(session[0][0]).get_data() + \
                load(session[1][0]).get_data() + \
                load(session[2][0]).get_data()
            img_icv = (img>0.5).astype(int).sum()*voxel_volume*1e-3
            icv.append(img_icv)
        return icv

    calc_icv = pe.Node(niu.Function(function=compute_icv,
                                    input_names=['class_images'],
                                    output_names=['icv']),
                       name='calc_icv')

    workflow.connect(dartel_template, 'segment.native_class_images', calc_icv, 'class_images')

    """
    Define the outputs of the workflow and connect the nodes to the outputnode
    """

    outputnode = pe.Node(niu.IdentityInterface(fields=["normalized_files",
                                                       "template_file",
                                                       "icv"
                                                       ]),
                         name="outputspec")
    workflow.connect([(dartel_template, outputnode, [('outputspec.template_file','template_file')]),
                      (norm2mni, outputnode, [("normalized_files", "normalized_files")]),
                      (calc_icv, outputnode, [("icv", "icv")]),
                      ])

    return workflow

def create_DARTEL_template(name='dartel_template'):
    """Create a vbm workflow that generates DARTEL-based template

    Example
    -------

    >>> preproc = create_DARTEL_template()
    >>> preproc.inputs.inputspec.structural_files = [os.path.abspath('s1.nii'), os.path.abspath('s3.nii')]
    >>> preproc.inputs.inputspec.template_prefix = 'Template'
    >>> preproc.run() # doctest: +SKIP

    Inputs::

         inputspec.structural_files : structural data to be used to create templates
         inputspec.template_prefix : prefix for dartel template

    Outputs::

         outputspec.template_file : DARTEL template
         outputspec.flow_fields : warps from input struct files to the template

    """

    workflow = pe.Workflow(name=name)

    inputnode = pe.Node(niu.IdentityInterface(fields=['structural_files', 'template_prefix']),
                        name='inputspec')

    segment = pe.MapNode(spm.NewSegment(),
                             iterfield=['channel_files'],
                             name='segment')
    workflow.connect(inputnode, 'structural_files', segment, 'channel_files')
    if not no_matlab:
        version = spm.Info.version()
        if version and version['name'] == 'SPM8':
            spm_path = version['path']
            tissue1 = ((os.path.join(spm_path,'toolbox/Seg/TPM.nii'), 1), 2, (True,True), (False, False))
            tissue2 = ((os.path.join(spm_path,'toolbox/Seg/TPM.nii'), 2), 2, (True,True), (False, False))
            tissue3 = ((os.path.join(spm_path,'toolbox/Seg/TPM.nii'), 3), 2, (True,False), (False, False))
            tissue4 = ((os.path.join(spm_path,'toolbox/Seg/TPM.nii'), 4), 3, (False,False), (False, False))
            tissue5 = ((os.path.join(spm_path,'toolbox/Seg/TPM.nii'), 5), 4, (False,False), (False, False))
            tissue6 = ((os.path.join(spm_path,'toolbox/Seg/TPM.nii'), 6), 2, (False,False), (False, False))
            segment.inputs.tissues = [tissue1, tissue2, tissue3, tissue4, tissue5, tissue6]
        else:
            logger.critical('SPM8 not found: DARTEL not available')
    else:
        logger.critical('MATLAB not found: DARTEL not setting tissue templates')
    dartel = pe.Node(spm.DARTEL(), name='dartel')

    """Get the gray and white segmentation classes generated by NewSegment
    """

    def get2classes(dartel_files):
        class1images = []
        class2images = []
        for session in dartel_files:
            class1images.extend(session[0])
            class2images.extend(session[1])
        return [class1images, class2images]

    workflow.connect(segment, ('dartel_input_images', get2classes), dartel, 'image_files')
    workflow.connect(inputnode, 'template_prefix', dartel, 'template_prefix')

    outputnode = pe.Node(niu.IdentityInterface(fields=["template_file",
                                                       "flow_fields"
                                                       ]),
                         name="outputspec")
    workflow.connect([
            (dartel, outputnode, [('final_template_file','template_file'),
                                  ('dartel_flow_fields', 'flow_fields')]),
            ])

    return workflow


text:
/**
 * Module dependencies.
 */

var express = require('express')
  , path = require('path');

var app = express();

app.configure(function(){
  app.use(express.favicon());
  app.use(express.logger('dev'));
  app.use(express.static(path.join(__dirname, 'public')));
  app.use('/db', require('../../'));
});

app.listen(3000);
console.log("Express server listening on port " + 3000);


text:
<?php
class m000000_000000_blog_base extends CDbMigration
{
    public function safeUp()
    {
        $db = $this->getDbConnection();

        // blog

        $tableName = $db->tablePrefix.'blog';
        $this->createTable($tableName, array(
            'id' => 'pk',
            'name' => 'varchar(300) NOT NULL',
            'description' => "text",
            'icon' => "varchar(300) NOT NULL DEFAULT ''",
            'slug' => 'varchar(150) NOT NULL',
            'lang' => 'char(2) DEFAULT NULL',
            'type' => "tinyint(4) unsigned NOT NULL DEFAULT '1'",
            'status' => "tinyint(4) unsigned NOT NULL DEFAULT '1'",
            'create_user_id' => 'integer NOT NULL',
            'update_user_id' => 'integer NOT NULL',
            'create_date' => 'integer unsigned NOT NULL',
            'update_date' => 'integer unsigned NOT NULL',
        ),"ENGINE=InnoDB DEFAULT CHARSET=utf8");

        $this->createIndex("blog_slug_uniq",$tableName,"slug,lang", true);
        $this->createIndex("blog_create_user_id",$tableName,"create_user_id", false);
        $this->createIndex("blog_update_user_id",$tableName,"update_user_id", false);
        $this->createIndex("blog_status",$tableName,"status", false);
        $this->createIndex("blog_type",$tableName,"type", false);
        $this->createIndex("blog_create_date",$tableName,"create_date", false);
        $this->createIndex("blog_update_date",$tableName,"update_date", false);
        $this->createIndex("blog_lang",$tableName,"lang", false);
        $this->createIndex("blog_slug",$tableName,"slug", false);

        $this->addForeignKey("blog_create_user_fk",$tableName,'create_user_id',$db->tablePrefix.'user','id','CASCADE','CASCADE');
        $this->addForeignKey("blog_update_user_fk",$tableName,'update_user_id',$db->tablePrefix.'user','id','CASCADE','CASCADE');

        // post

        $tableName = $db->tablePrefix.'post';
        $this->createTable($tableName, array(
              'id' => 'pk',
              'blog_id' => 'integer NOT NULL',
              'create_user_id' => 'integer NOT NULL',
              'update_user_id' => 'integer NOT NULL',
              'create_date' => 'integer NOT NULL',
              'update_date' => 'integer NOT NULL',
              'publish_date' => 'integer NOT NULL',
              'slug' => 'string NOT NULL',
              'lang' => 'char(2) DEFAULT NULL',
              'title' => 'string NOT NULL',
              'quote' => "varchar(300) NOT NULL DEFAULT ''",
              'content' => 'text NOT NULL',
              'link' => "string NOT NULL DEFAULT ''",
              'status' => "tinyint(4) unsigned NOT NULL DEFAULT '0'",
              'comment_status' => "tinyint(4) unsigned NOT NULL DEFAULT '1'",
              'access_type' => "tinyint(4) unsigned NOT NULL DEFAULT '1'",
              'keywords' => "string NOT NULL DEFAULT ''",
              'description' => "varchar(300) NOT NULL DEFAULT ''",
            ),"ENGINE=InnoDB DEFAULT CHARSET=utf8");

        $this->createIndex("blog_post_slug_uniq",$tableName,"slug,lang", true);
        $this->createIndex("blog_post_blog_id",$tableName,"blog_id", true);
        $this->createIndex("blog_post_create_user_id",$tableName,"create_user_id", false);
        $this->createIndex("blog_post_update_user_id",$tableName,"update_user_id", false);
        $this->createIndex("blog_post_status",$tableName,"status", false);
        $this->createIndex("blog_post_access_type",$tableName,"access_type", false);
        $this->createIndex("blog_post_comment_status",$tableName,"comment_status", false);
        $this->createIndex("blog_lang",$tableName,"lang", false);
        $this->createIndex("blog_slug",$tableName,"slug", false);

        $this->addForeignKey("blog_post_blog_fk",$tableName,'blog_id',$db->tablePrefix.'blog','id','CASCADE','CASCADE');
        $this->addForeignKey("blog_post_create_user_fk",$tableName,'create_user_id',$db->tablePrefix.'user','id','CASCADE','CASCADE');
        $this->addForeignKey("blog_post_update_user_fk",$tableName,'update_user_id',$db->tablePrefix.'user','id','CASCADE','CASCADE');

        // user to blog

        $tableName = $db->tablePrefix.'user_to_blog';
        $this->createTable($tableName, array(
                'id' => 'pk',
                'user_id' => 'integer NOT NULL',
                'blog_id' => 'integer NOT NULL',
                'create_date' => 'integer NOT NULL',
                'update_date' => 'integer NOT NULL',
                'role' => "tinyint(3) unsigned NOT NULL DEFAULT '1'",
                'status' => "smallint(5) unsigned NOT NULL DEFAULT '1'",
                'note' => "varchar(300) NOT NULL DEFAULT ''",
            ),"ENGINE=InnoDB DEFAULT CHARSET=utf8");

        $this->createIndex("blog_user_to_blog_uniq",$tableName,"user_id,blog_id", true);
        $this->createIndex("blog_user_to_blog_uid",$tableName,"user_id", false);
        $this->createIndex("blog_user_to_blog_blogid",$tableName,"blog_id", false);
        $this->createIndex("blog_user_to_blog_status",$tableName,"status", false);
        $this->createIndex("blog_user_to_blog_role",$tableName,"role", false);

        $this->addForeignKey("blog_user_to_blog_user_id",$tableName,'user_id',$db->tablePrefix.'user','id','CASCADE','CASCADE');
        $this->addForeignKey("blog_user_to_blog_blog_id",$tableName,'blog_id',$db->tablePrefix.'blog','id','CASCADE','CASCADE');

        // tags

        $tableName = $db->tablePrefix.'tag';
        $this->createTable($tableName, array(
                'id' => 'pk',
                'name' => 'string NOT NULL',
            ),"ENGINE=InnoDB DEFAULT CHARSET=utf8");

        $this->createIndex("blog_tag_name_uniq",$tableName,"name", true);

        // post to tag

        $tableName = $db->tablePrefix.'post_to_tag';
        $this->createTable($tableName, array(
                'post_id' => 'integer NOT NULL',
                'tag_id' => 'integer NOT NULL',
                'PRIMARY KEY (post_id, tag_id)'
            ),"ENGINE=InnoDB DEFAULT CHARSET=utf8");

        $this->createIndex("blog_post_to_tag_postid",$tableName,"post_id", false);
        $this->createIndex("blog_post_to_tag_tagid",$tableName,"tag_id", false);

        $this->addForeignKey("blog_post_to_tag_postid_fk",$tableName,'post_id',$db->tablePrefix.'post','id','CASCADE','CASCADE');
        $this->addForeignKey("blog_post_to_tag_tagid_fk",$tableName,'tag_id',$db->tablePrefix.'tag','id','CASCADE','CASCADE');

    }

    public function safeDown()
    {
        $db = $this->getDbConnection();

        $this->dropTable($db->tablePrefix.'post_to_tag');
        $this->dropTable($db->tablePrefix.'tag');
        $this->dropTable($db->tablePrefix.'user_to_blog');
        $this->dropTable($db->tablePrefix.'post');
        $this->dropTable($db->tablePrefix.'blog');
    }
}


text:
<!DOCTYPE html>

  <meta charset="utf-8">

  <link rel="stylesheet" href="../core.css">
  <link rel="stylesheet" href="style.css">
  <link rel="stylesheet" href="../../other/buttons/style.css">


text:
package org.springframework.boot.autoconfigure.security.servlet;

import java.util.EnumSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import javax.servlet.http.HttpServletRequest;

import org.springframework.boot.autoconfigure.security.StaticResourceLocation;
import org.springframework.boot.autoconfigure.web.servlet.WebMvcProperties;
import org.springframework.boot.security.servlet.ApplicationContextRequestMatcher;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.security.web.util.matcher.OrRequestMatcher;
import org.springframework.security.web.util.matcher.RequestMatcher;
import org.springframework.util.Assert;

/**
 * Used to create a {@link RequestMatcher} for static resources in commonly used
 * locations. Returned by {@link PathRequest#toStaticResources()}.
 *
 * @author Madhura Bhave
 * @author Phillip Webb
 * @since 2.0.0
 * @see PathRequest
 */
public final class StaticResourceRequest {

	static final StaticResourceRequest INSTANCE = new StaticResourceRequest();

	private StaticResourceRequest() {
	}

	/**
	 * Returns a matcher that includes all commonly used {@link StaticResourceLocation
	 * Locations}. The
	 * {@link StaticResourceRequestMatcher#excluding(StaticResourceLocation, StaticResourceLocation...)
	 * excluding} method can be used to remove specific locations if required. For
	 * example:

	 * StaticResourceRequest.atCommonLocations().excluding(StaticResourceLocation.CSS)
	 *

	 * @return the configured {@link RequestMatcher}
	 */
	public StaticResourceRequestMatcher atCommonLocations() {
		return at(EnumSet.allOf(StaticResourceLocation.class));
	}

	/**
	 * Returns a matcher that includes the specified {@link StaticResourceLocation
	 * Locations}. For example:

	 * StaticResourceRequest.at(StaticResourceLocation.CSS, StaticResourceLocation.JAVA_SCRIPT)
	 *

	 * @param first the first location to include
	 * @param rest additional locations to include
	 * @return the configured {@link RequestMatcher}
	 */
	public StaticResourceRequestMatcher at(StaticResourceLocation first,
			StaticResourceLocation... rest) {
		return at(EnumSet.of(first, rest));
	}

	/**
	 * Returns a matcher that includes the specified {@link StaticResourceLocation
	 * Locations}. For example:

	 * StaticResourceRequest.at(locations)
	 *

	 * @param locations the locations to include
	 * @return the configured {@link RequestMatcher}
	 */
	public StaticResourceRequestMatcher at(Set<StaticResourceLocation> locations) {
		Assert.notNull(locations, "Locations must not be null");
		return new StaticResourceRequestMatcher(new LinkedHashSet<>(locations));
	}

	/**
	 * The request matcher used to match against resource {@link StaticResourceLocation
	 * Locations}.
	 */
	public static final class StaticResourceRequestMatcher
			extends ApplicationContextRequestMatcher<WebMvcProperties> {

		private final Set<StaticResourceLocation> locations;

		private volatile RequestMatcher delegate;

		private StaticResourceRequestMatcher(Set<StaticResourceLocation> locations) {
			super(WebMvcProperties.class);
			this.locations = locations;
		}

		/**
		 * Return a new {@link StaticResourceRequestMatcher} based on this one but
		 * excluding the specified locations.
		 * @param first the first location to exclude
		 * @param rest additional locations to exclude
		 * @return a new {@link StaticResourceRequestMatcher}
		 */
		public StaticResourceRequestMatcher excluding(StaticResourceLocation first,
				StaticResourceLocation... rest) {
			return excluding(EnumSet.of(first, rest));
		}

		/**
		 * Return a new {@link StaticResourceRequestMatcher} based on this one but
		 * excluding the specified locations.
		 * @param locations the locations to exclude
		 * @return a new {@link StaticResourceRequestMatcher}
		 */
		public StaticResourceRequestMatcher excluding(
				Set<StaticResourceLocation> locations) {
			Assert.notNull(locations, "Locations must not be null");
			Set<StaticResourceLocation> subset = new LinkedHashSet<>(this.locations);
			subset.removeAll(locations);
			return new StaticResourceRequestMatcher(subset);
		}

		@Override
		protected void initialized(Supplier<WebMvcProperties> serverProperties) {
			this.delegate = new OrRequestMatcher(
					getDelegateMatchers(serverProperties.get()));
		}

		private List<RequestMatcher> getDelegateMatchers(
				WebMvcProperties serverProperties) {
			return getPatterns(serverProperties).map(AntPathRequestMatcher::new)
					.collect(Collectors.toList());
		}

		private Stream<String> getPatterns(WebMvcProperties serverProperties) {
			return this.locations.stream().flatMap(StaticResourceLocation::getPatterns)
					.map(serverProperties.getServlet()::getPath);
		}

		@Override
		protected boolean matches(HttpServletRequest request,
				Supplier<WebMvcProperties> context) {
			return this.delegate.matches(request);
		}

	}

}


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
  package="me.footlights.android" android:versionCode="1" android:versionName="HEAD">

  <application android:icon="@drawable/icon" android:label="@string/app_name" android:debuggable="true" android:name="Footlights" android:theme="@android:style/Theme.Black.NoTitleBar.Fullscreen">
    <activity android:name=".FootlightsActivity">
      <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
      </intent-filter>
    </activity>
  </application>

</manifest>


text:
'use strict';

const groups = require.main.require('./src/groups');

const Controllers = {};

Controllers.renderAdminPage = async (req, res) => {
	const groupData = await groups.getGroupsFromSet('groups:visible:createtime', 0, -1);
	res.render('admin/plugins/session-sharing', { groups: groupData });
};

Controllers.retrieveUser = async (req, res) => {
	const main = module.parent.exports;
	const remoteId = req.query.id;

	if (!remoteId) {
		return res.status(400).json({
			error: 'no-id-supplied',
		});
	}

	try {
		const userObj = await main.getUser(remoteId);

		if (!userObj) {
			return res.sendStatus(404);
		}

		return res.status(200).json(userObj);
	} catch (error) {
		return res.status(500).json({
			error: error.message,
		});
	}
};

Controllers.process = async (req, res) => {
	const main = module.parent.exports;

	if (!req.body || !req.body.token) {
		return res.status(400).json({
			error: 'no-token-provided',
		});
	}

	try {
		const uid = await main.process(req.body.token);

		return res.status(200).json({
			uid,
		});
	} catch (error) {
		return res.status(500).json({
			error: error.message,
		});
	}
};

module.exports = Controllers;


text:
namespace tinympl {

template<bool ... Args> struct or_b;
template<bool Head,bool ... Tail> struct or_b<Head,Tail...> : std::integral_constant<bool, Head || or_b<Tail...>::value> {};
template<bool Head> struct or_b<Head> : std::integral_constant<bool,Head> {};

} // namespace tinympl

#endif // TINYMPL_OR_B_HPP


text:
{% extends "wiki/base.html" %}
{% load wikify wiki_tags i18n %}
{% block pagetitle %}{{ page.slug }} {{ block.super }}{% endblock %}

{% block content %}
	{% if preview %}

{% blocktrans with page.slug as name %}Preview: {{ name }}{% endblocktrans %}

		{{ page.content|restructuredtext|wikify|safe }}
	{% endif %}

{% blocktrans with page.slug as name %}Edit: {{ name }}{% endblocktrans %}

	<form action="{{ page.get_absolute_url }}edit/" method="post">
		<textarea style="font-family:monospace" name="content" cols="96" rows="30">{{ page.content }}</textarea>

		<input type="submit" name="save" value="{% trans "Save" %}" />
		<input type="submit" name="preview" value="{% trans "Preview" %}" />
		<input type="button" value="{% trans "Cancel" %}" onclick="window.location='{{ page.get_absolute_url }}'" />
	</form>
{% endblock %}


text:
package com.google.api.codegen.config;

import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableMap;

import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * Generator for language settings section. Currently the only language setting is the package
 * name.
 */
public class LanguageGenerator {

  private static final String DEFAULT_PACKAGE_SEPARATOR = "\\.";

  private static final String CONFIG_KEY_PACKAGE_NAME = "package_name";

  private static final Map<String, LanguageFormatter> LANGUAGE_FORMATTERS =
      ImmutableMap.<String, LanguageFormatter>builder()
          .put("java", new LanguageFormatter(".", "com", false))
          .put("python", new LanguageFormatter(".", null, false))
          .put("go", new LanguageFormatter("/", "google.golang.org", false))
          .put("csharp", new LanguageFormatter(".", null, true))
          .put("ruby", new LanguageFormatter("::", null, true))
          .put("php", new LanguageFormatter("\\", null, true))
          .build();

  public static Map<String, Object> generate(String packageName) {
    String[] packageNameComponents = packageName.split(DEFAULT_PACKAGE_SEPARATOR);

    Map<String, Object> languages = new LinkedHashMap<>();
    for (String language : LANGUAGE_FORMATTERS.keySet()) {
      LanguageFormatter formatter = LANGUAGE_FORMATTERS.get(language);
      String formattedPackageName = formatter.getFormattedPackageName(packageNameComponents);

      Map<String, Object> packageNameMap = new LinkedHashMap<>();
      packageNameMap.put(CONFIG_KEY_PACKAGE_NAME, formattedPackageName);
      languages.put(language, packageNameMap);
    }
    return languages;
  }

  private static String firstCharToUpperCase(String string) {
    return Character.toUpperCase(string.charAt(0)) + string.substring(1);
  }

  private static class LanguageFormatter {

    private final String separator;
    private final String prefix;
    private final boolean capitalize;

    public LanguageFormatter(String separator, String prefix, boolean capitalize) {
      this.separator = separator;
      this.prefix = prefix;
      this.capitalize = capitalize;
    }

    public String getFormattedPackageName(String[] nameComponents) {
      List<String> elements = new LinkedList<>();
      if (prefix != null) {
        elements.add(prefix);
      }
      for (String component : nameComponents) {
        if (capitalize) {
          elements.add(firstCharToUpperCase(component));
        } else {
          elements.add(component);
        }
      }
      return Joiner.on(separator).join(elements);
    }
  }
}


text:
package converters

import (
	"k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/runtime"

	"github.com/projectcalico/libcalico-go/lib/apis/v1/unversioned"
	"github.com/projectcalico/libcalico-go/lib/backend/model"
)

// Resource is implemented by all Calico resources.
type Resource interface {
	runtime.Object
	v1.ObjectMetaAccessor
}

type Converter interface {
	// APIV1ToBackendV1 converts unversioned resource (v1 API) to v1 KVPair.
	APIV1ToBackendV1(unversioned.Resource) (*model.KVPair, error)

	// BackendV1ToAPIV3 converts v1 KVPair to v3 resource (v3 API)
	BackendV1ToAPIV3(*model.KVPair) (Resource, error)
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
    Copyright 2005-2006 The Apache Software Foundation or its licensors, as applicable

    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.
-->
<!DOCTYPE Test SYSTEM "test.dtd">
<!--
Author:  Alexander D. Shipilov
Version: $Revision: 1.3 $
-->
<Test
  ID="newarray0401"
  date-of-creation="2005-1-12"
  timeout="1"
  >
  <Author value="Alexander D. Shipilov"/>
  <Description>
    Tests newarray java virtual machine instruction.
    Creating int array.

    Covered assertions assert_instr210a023
  </Description>

  <Source name="newarray0401p.j"/>

  <Runner ID="Runtime">
    <Param name="toRun" value="org.apache.harmony.vts.test.vm.jvms.instructions.reftypes.newarray.newarray04.newarray0401.newarray0401p"/>
  </Runner>
</Test>


text:
import React from 'react'
import ReactDOM from 'react-dom'
import TestUtils from 'react-dom/test-utils'
import {describe, before, it} from 'mocha'
import expect from 'expect'
import {createStore, applyMiddleware} from 'redux'
import {combineReducers} from 'redux-immutablejs'
import thunk from 'redux-thunk'
import {Provider} from 'react-redux'

import I18n from '../immutable'
import {i18nState} from '../immutable'
import {setLanguage, setTranslations} from '../dist/actions'

import TransWithoutParams from './components/TransWithoutParams'

describe('translations in reducer (immutable)', function() {
  before('rendering component', function() {
    this.store = createStore(
      combineReducers({i18nState}),
      applyMiddleware(thunk)
    )

    this.component = ReactDOM.findDOMNode(TestUtils.renderIntoDocument(
      <Provider store={this.store}>
        <I18n translations={{}} useReducer={true}>
          <TransWithoutParams/>
        </I18n>
      </Provider>
    ))

  })

  it('set all translations object', function() {
    expect(this.store.getState().getIn(['i18nState', 'translations'])).toEqual({})
    this.store.dispatch(setLanguage('es'))
    expect(this.component.textContent).toEqual('Hello')

    const trans = {
      'es': {
        'Hello': 'Hola'
      }
    }

    this.store.dispatch(setTranslations(trans))
    expect(this.store.getState().getIn(['i18nState', 'translations'])['es']['Hello']).toEqual('Hola')
    expect(this.component.textContent).toEqual('Hola')
  })

  it('add only one new language in translations', function() {
    const trans = {
      'es': {
        'Hello': 'Hola'
      }
    }
    this.store.dispatch(setTranslations(trans))
    expect(this.store.getState().getIn(['i18nState', 'translations'])).toEqual(trans)
    this.store.dispatch(setLanguage('es'))
    expect(this.component.textContent).toEqual('Hola')

    this.store.dispatch(setLanguage('de'))
    expect(this.component.textContent).toEqual('Hello')

    this.store.dispatch(setTranslations({'Hello': 'Hallo'}, 'de'))
    expect(this.component.textContent).toEqual('Hallo')
  })

  describe('options', function() {
    it('add only one new language in translations', function() {
      const trans = {
        'es': {
          'Hello': 'Hola'
        }
      }
      this.store.dispatch(setTranslations(trans))
      this.store.dispatch(setLanguage('de'))
      this.store.dispatch(setTranslations({'Hello': 'Hallo'}, {language: 'de'}))
      expect(this.component.textContent).toEqual('Hallo')
    });

    it('preserve existing translations', function() {
      const trans = {
        'es': {
          'Hello': 'Hola'
        }
      }

      const newTranslations = {
        'de': {
          'Hello': 'Hallo'
        }
      }
      this.store.dispatch(setTranslations(trans))
      this.store.dispatch(setTranslations(newTranslations, {preserveExisting: true}))
      this.store.dispatch(setLanguage('es'))
      expect(this.component.textContent).toEqual('Hola')
      this.store.dispatch(setLanguage('de'))
      expect(this.component.textContent).toEqual('Hallo')
    });

    it('preserve translations in only one language', function() {
      const trans = {
        'es': {
          'Hello': 'Hola'
        }
      }

      const newTranslations = {
        'Goodbye': 'Adiós'
      }

      this.store.dispatch(setTranslations(trans))
      this.store.dispatch(setTranslations(newTranslations, {language: 'es', preserveExisting: true}))
      expect(this.store.getState().getIn(['i18nState', 'translations'])['es']).toEqual({
        'Hello': 'Hola',
        'Goodbye': 'Adiós'
      })
    })
  })
})


text:
<?php

namespace Admin\MedBundle\Entity;

use Doctrine\ORM\EntityRepository;

/**
 * ProyectoiRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class ProyectoiRepository extends EntityRepository
{
 public function findByUser($user){
    $em = $this->getEntityManager();

    $query = $em->createQuery(
       'SELECT p.id, p.nombre
        FROM Admin\MedBundle\Entity\Proyectoi p
        WHERE p.user = :user'
    )->setParameter('user', $user);
    // returns an array of Product objects
    return $query->execute();
}

 public function porUsuario($user){
  return $this->createQueryBuilder('proyectos_inv')
            ->where('proyectos_inv.user = :user')
            ->setParameter('user', $user)
            ->orderBy('proyectos_inv.nombre', 'ASC');
 }

public function findByUsuario($user)
{
    $conn = $this->getEntityManager()->getConnection();

    $sql = '
        SELECT p.id, p.nombre FROM proyectos_inv p
        WHERE p.user_id = '.$user.'
        ';
    $stmt = $conn->prepare($sql);

    $stmt->execute();

    // returns an array of arrays (i.e. a raw data set)
    return $stmt->fetchAll();
}

}


text:
package edu.umd.cs.findbugs.classfile.engine;

import org.objectweb.asm.AnnotationVisitor;
import org.objectweb.asm.Attribute;
import org.objectweb.asm.Label;
import org.objectweb.asm.MethodVisitor;

/**
 * @author pwilliam
 */
public abstract class AbstractMethodVisitor implements MethodVisitor {

    public void visitSomeInsn() {
    }

    /*
     * (non-Javadoc)
     *
     * @see org.objectweb.asm.MethodVisitor#visitAnnotationDefault()
     */
    public AnnotationVisitor visitAnnotationDefault() {
        // TODO Auto-generated method stub
        return null;
    }

    /*
     * (non-Javadoc)
     *
     * @see
     * org.objectweb.asm.MethodVisitor#visitAttribute(org.objectweb.asm.Attribute
     * )
     */
    public void visitAttribute(Attribute attr) {
        // TODO Auto-generated method stub
    }

    /*
     * (non-Javadoc)
     *
     * @see org.objectweb.asm.MethodVisitor#visitCode()
     */
    public void visitCode() {
        // TODO Auto-generated method stub

    }

    /*
     * (non-Javadoc)
     *
     * @see org.objectweb.asm.MethodVisitor#visitFieldInsn(int,
     * java.lang.String, java.lang.String, java.lang.String)
     */
    public void visitFieldInsn(int opcode, String owner, String name, String desc) {
        visitSomeInsn();

    }

    /*
     * (non-Javadoc)
     *
     * @see org.objectweb.asm.MethodVisitor#visitFrame(int, int,
     * java.lang.Object[], int, java.lang.Object[])
     */
    public void visitFrame(int type, int local, Object[] local2, int stack, Object[] stack2) {
        // TODO Auto-generated method stub

    }

    /*
     * (non-Javadoc)
     *
     * @see org.objectweb.asm.MethodVisitor#visitIincInsn(int, int)
     */
    public void visitIincInsn(int var, int increment) {
        visitSomeInsn();

    }

    /*
     * (non-Javadoc)
     *
     * @see org.objectweb.asm.MethodVisitor#visitInsn(int)
     */
    public void visitInsn(int opcode) {
        visitSomeInsn();

    }

    /*
     * (non-Javadoc)
     *
     * @see org.objectweb.asm.MethodVisitor#visitIntInsn(int, int)
     */
    public void visitIntInsn(int opcode, int operand) {
        visitSomeInsn();

    }

    /*
     * (non-Javadoc)
     *
     * @see org.objectweb.asm.MethodVisitor#visitJumpInsn(int,
     * org.objectweb.asm.Label)
     */
    public void visitJumpInsn(int opcode, Label label) {
        visitSomeInsn();

    }

    /*
     * (non-Javadoc)
     *
     * @see org.objectweb.asm.MethodVisitor#visitLabel(org.objectweb.asm.Label)
     */
    public void visitLabel(Label label) {
        // TODO Auto-generated method stub

    }

    /*
     * (non-Javadoc)
     *
     * @see org.objectweb.asm.MethodVisitor#visitLdcInsn(java.lang.Object)
     */
    public void visitLdcInsn(Object cst) {
        visitSomeInsn();

    }

    /*
     * (non-Javadoc)
     *
     * @see org.objectweb.asm.MethodVisitor#visitLineNumber(int,
     * org.objectweb.asm.Label)
     */
    public void visitLineNumber(int line, Label start) {
        // TODO Auto-generated method stub

    }

    /*
     * (non-Javadoc)
     *
     * @see org.objectweb.asm.MethodVisitor#visitLocalVariable(java.lang.String,
     * java.lang.String, java.lang.String, org.objectweb.asm.Label,
     * org.objectweb.asm.Label, int)
     */
    public void visitLocalVariable(String name, String desc, String signature, Label start, Label end, int index) {
        // TODO Auto-generated method stub

    }

    /*
     * (non-Javadoc)
     *
     * @see
     * org.objectweb.asm.MethodVisitor#visitLookupSwitchInsn(org.objectweb.asm
     * .Label, int[], org.objectweb.asm.Label[])
     */
    public void visitLookupSwitchInsn(Label dflt, int[] keys, Label[] labels) {
        visitSomeInsn();

    }

    /*
     * (non-Javadoc)
     *
     * @see org.objectweb.asm.MethodVisitor#visitMaxs(int, int)
     */
    public void visitMaxs(int maxStack, int maxLocals) {
        // TODO Auto-generated method stub

    }

    /*
     * (non-Javadoc)
     *
     * @see org.objectweb.asm.MethodVisitor#visitMethodInsn(int,
     * java.lang.String, java.lang.String, java.lang.String)
     */
    public void visitMethodInsn(int opcode, String owner, String name, String desc) {
        visitSomeInsn();

    }

    /*
     * (non-Javadoc)
     *
     * @see
     * org.objectweb.asm.MethodVisitor#visitMultiANewArrayInsn(java.lang.String,
     * int)
     */
    public void visitMultiANewArrayInsn(String desc, int dims) {
        visitSomeInsn();

    }

    /*
     * (non-Javadoc)
     *
     * @see org.objectweb.asm.MethodVisitor#visitTableSwitchInsn(int, int,
     * org.objectweb.asm.Label, org.objectweb.asm.Label[])
     */
    public void visitTableSwitchInsn(int min, int max, Label dflt, Label[] labels) {
        // TODO Auto-generated method stub

    }

    /*
     * (non-Javadoc)
     *
     * @see
     * org.objectweb.asm.MethodVisitor#visitTryCatchBlock(org.objectweb.asm.
     * Label, org.objectweb.asm.Label, org.objectweb.asm.Label,
     * java.lang.String)
     */
    public void visitTryCatchBlock(Label start, Label end, Label handler, String type) {
        // TODO Auto-generated method stub

    }

    /*
     * (non-Javadoc)
     *
     * @see org.objectweb.asm.MethodVisitor#visitTypeInsn(int, java.lang.String)
     */
    public void visitTypeInsn(int opcode, String type) {
        visitSomeInsn();

    }

    /*
     * (non-Javadoc)
     *
     * @see org.objectweb.asm.MethodVisitor#visitVarInsn(int, int)
     */
    public void visitVarInsn(int opcode, int var) {
        visitSomeInsn();

    }

}


text:
extern "Java"
{
  namespace gnu
  {
    namespace javax
    {
      namespace print
      {
        namespace ipp
        {
          namespace attribute
          {
              class NaturalLanguageSyntax;
          }
        }
      }
    }
  }
}

class gnu::javax::print::ipp::attribute::NaturalLanguageSyntax : public ::java::lang::Object
{

public: // actually protected
  NaturalLanguageSyntax(::java::lang::String *);
public:
  virtual ::java::lang::String * getValue();
  virtual jint hashCode();
  virtual jboolean equals(::java::lang::Object *);
  virtual ::java::lang::String * toString();
private:
  ::java::lang::String * __attribute__((aligned(__alignof__( ::java::lang::Object)))) value;
public:
  static ::java::lang::Class class$;
};

#endif // __gnu_javax_print_ipp_attribute_NaturalLanguageSyntax__


text:
package cz.nudz.www.trainingapp.training;

import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import java.util.Collections;
import java.util.List;

import cz.nudz.www.trainingapp.R;
import cz.nudz.www.trainingapp.utils.CollectionUtils;
import cz.nudz.www.trainingapp.utils.Utils;

public class ColorParadigmFragment extends TrainingFragment {

    private List<Integer> colors;
    private String shapeName;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        // Setup stimuli/probe colors..
        // The color count covers entirely stimuli count even for hardest difficulty + 1 for color change.
        colors = CollectionUtils.toList(getResources().getIntArray(R.array.trialColors));
        shapeName = Utils.getShapeName(R.drawable.square);

        return super.onCreateView(inflater, container, savedInstanceState);
    }

    @Override
    protected void performChange(ImageView changingStim) {
        // take last color (reserved for change)
        final int changeColor = colors.get(colors.size() - 1);
        changingStim.setColorFilter(changeColor);
        changingStim.setTag(new Pair<>(changeColor, shapeName));
    }

    @Override
    protected void initStimuli(List<ImageView> stimuli) {
        Collections.shuffle(colors);

        for (int i = 0; i < stimuli.size(); ++i) {
            ImageView v = stimuli.get(i);
            // 'clone' drawable so that we can alter color for each.
            Drawable drawable = getResources().getDrawable(R.drawable.square).mutate();
            final Integer color = colors.get(i);
            v.setTag(new Pair<>(color, shapeName));
            v.setImageDrawable(drawable);
            v.setColorFilter(color);
        }
    }
}


text:
layout: default
---

software developer with a creative spirit


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Mcategory extends CI_Model {

		function findAll(){
		return $this->db->get('sh_category')->result();
	}
	function find($id){
		$this->db->where('id', $id);
		return $this->db->get('sh_category')->row();
	}
	function insert($category = array()){
		$this->db->insert('sh_category',$category);
	}
	function delete($id){
		$this->db->where('id', $id);
		$this->db->delete('sh_category');
	}
	function update($id, $category = array()){
		$this->db->where('id', $id);
		$this->db->update('sh_category', $category);
	}

}

/* End of file Category.php */
/* Location: ./application/models/Category.php */


text: This page has an iframe.


text:
<!DOCTYPE html>

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

        <link rel="stylesheet" href="css/normalize.css">
        <link rel="stylesheet" href="css/main.css">

  <form action="add_class.php" method="get">
  <form>

UCSC Class Watcher

Add Class

Register your number for a class that is currently closed on myUCSC and we'll text you when the class status changes to open.

      Enter your cell phone number

        <input type="text" maxlength="20" name="phone" value="" />

      Enter class department

        <select name="dept">
          <option value=""  selected="selected"> </option>
          <option value = "AMST">American Studies</option>
          <option value = "ANTH">Anthropology</option>
          <option value = "AMS">Applied Math and Statistics</option>
          <option value = "ARAB">Arabic</option>
          <option value = "ART">Art</option>
          <option value = "ASTR">Astronomy and Astrophysics</option>
          <option value = "BIOC">Biochemistry and Molecular Bio</option>
          <option value = "BIOL">Biology: Molecular Cell & Dev</option>
          <option value = "BIOE">Biology:Ecology & Evolutionary</option>
          <option value = "BME">Biomolecular Engineering</option>
          <option value = "CHEM">Chemistry and Biochemistry</option>
          <option value = "CHIN">Chinese</option>
          <option value = "CLEI">College Eight</option>
          <option value = "CLNI">College Nine</option>
          <option value = "CLTE">College Ten</option>
          <option value = "CMMU">Community Studies</option>
          <option value = "CMPE">Computer Engineering</option>
          <option value = "CMPS">Computer Science</option>
          <option value = "COWL">Cowell College</option>
          <option value = "LTCR">Creative Writing</option>
          <option value = "CRWN">Crown College</option>
          <option value = "DANM">Digital Arts and New Media</option>
          <option value = "EART">Earth Sciences</option>
          <option value = "ECON">Economics</option>
          <option value = "EDUC">Education</option>
          <option value = "EE">Electrical Engineering</option>
          <option value = "ENGR">Engineering</option>
          <option value = "LTEL">English-Language Literatures</option>
          <option value = "ENVS">Environmental Studies</option>
          <option value = "ETOX">Environmental Toxicology</option>
          <option value = "FMST">Feminist Studies</option>
          <option value = "FILM">Film and Digital Media</option>
          <option value = "FREN">French</option>
          <option value = "LTFR">French Literature</option>
          <option value = "GERM">German</option>
          <option value = "LTGE">German Literature</option>
          <option value = "GREE">Greek</option>
          <option value = "LTGR">Greek Literature</option>
          <option value = "HEBR">Hebrew</option>
          <option value = "HNDI">Hindi</option>
          <option value = "HIS">History</option>
          <option value = "HAVC">History of Art&Visual Culture</option>
          <option value = "HISC">History of Consciousness</option>
          <option value = "HUMN">Humanities</option>
          <option value = "ISM">Information Systems Management</option>
          <option value = "ITAL">Italian</option>
          <option value = "LTIT">Italian Literature</option>
          <option value = "JAPN">Japanese</option>
          <option value = "JWST">Jewish Studies</option>
          <option value = "KRSG">Kresge College</option>
          <option value = "LAAD">Languages</option>
          <option value = "LATN">Latin</option>
          <option value = "LALS">Latin American&Latino Studies</option>
          <option value = "LTIN">Latin Literature</option>
          <option value = "LGST">Legal Studies</option>
          <option value = "LING">Linguistics</option>
          <option value = "LIT">Literature</option>
          <option value = "MATH">Mathematics</option>
          <option value = "MERR">Merrill College</option>
          <option value = "METX">Microbiol & Environ Toxicology</option>
          <option value = "LTMO">Modern Literary Studies</option>
          <option value = "MUSC">Music</option>
          <option value = "OAKS">Oakes College</option>
          <option value = "OCEA">Ocean Sciences</option>
          <option value = "PHIL">Philosophy</option>
          <option value = "PHYE">Physical Education</option>
          <option value = "PHYS">Physics</option>
          <option value = "POLI">Politics</option>
          <option value = "PRTR">Porter College</option>
          <option value = "PORT">Portuguese</option>
          <option value = "LTPR">Pre & Early Modern Literature</option>
          <option value = "PSYC">Psychology</option>
          <option value = "PUNJ">Punjabi</option>
          <option value = "RUSS">Russian</option>
          <option value = "SCIC">Science Communication</option>
          <option value = "SOCD">Social Documentation</option>
          <option value = "SOCS">Social Sciences</option>
          <option value = "SOCY">Sociology</option>
          <option value = "SPAN">Spanish</option>
          <option value = "SPHS">Spanish for Heritage Speakers</option>
          <option value = "SPSS">Spanish for Spanish Speakers</option>
          <option value = "LTSP">Spanish/Latin Amer/Latino Lit</option>
          <option value = "STEV">Stevenson College</option>
          <option value = "TIM">Technology & Info Management</option>
          <option value = "THEA">Theater Arts</option>
          <option value = "WMST">Women's Studies</option>
          <option value = "LTWL">World Lit & Cultural Studies</option>
          <option value = "WRIT">Writing</option>
          <option value = "YIDD">Yiddish</option>
        </select>

      Enter class number

        <input type="text" maxlength="5" name="num" value="" />

      <button type="submit" disabled="disabled">Submit</button>

  </form>


text:
package quibit

import (
	"fmt"
	"net"
	"strconv"
	"time"
)

type Peer struct {
	IP   net.IP // Standard 16-byte IP Address
	Port uint16 // Standard 2-byte TCP Port
	conn *net.Conn
	external bool
}

func peerFromConn(conn *net.Conn, external bool) Peer {
	var p Peer
	if conn == nil {
		return p
	}

	addr := (*conn).RemoteAddr()
	if addr.Network() != "tcp" {
		return p
	}
	ip, portStr, err := net.SplitHostPort(addr.String())
	port, _ := strconv.Atoi(portStr)
	if err != nil {
		return p
	}

	// Create New Peer
	p.IP = net.ParseIP(ip)
	p.Port = uint16(port)

	p.conn = conn
	p.external = external
	return p
}

// String returns the <IP>:<Host> Identifier of Peer
func (p *Peer) String() string {
	if p == nil {
		return ""
	}
	return net.JoinHostPort(p.IP.String(), strconv.Itoa(int(p.Port)))
}

// Returns the connection status of Peer
func (p *Peer) IsConnected() bool {
	if p == nil {
		return false
	}
	return (p.conn != nil)
}

func (p *Peer) connect() error {
	// Check for sane peer object
	if p == nil {
		return QuibitError(eNILOBJ)
	}
	if p.conn != nil {
		return nil
	}

	var err error
	lConn, err := net.DialTimeout("tcp", p.String(), 10 * time.Second)
	p.conn = &lConn
	if err != nil {
		p.conn = nil
		return err
	}

	// Set Keep-Alives
	(*p.conn).(*net.TCPConn).SetKeepAlive(true)
	(*p.conn).(*net.TCPConn).SetKeepAlivePeriod(time.Second)

	if p.external {
		incomingConnections++
	}

	return nil
}

// Forces Disconnect from Peer and closes all incoming connections.
func (p *Peer) Disconnect() {
	if p.conn == nil {
		return
	}
	(*p.conn).Close()
	p.conn = nil
	if p.external {
		incomingConnections--
	}
}

func (p *Peer) sendFrame(frame Frame) error {
	if p == nil {
		return QuibitError(eNILOBJ)
	}
	if p.conn == nil {
		return QuibitError(eNILOBJ)
	}

	var err error

	headerBytes, err := frame.Header.ToBytes()
	if err != nil {
		return QuibitError(eHEADER)
	}

	_, err = (*p.conn).Write(append(headerBytes, frame.Payload...))
	if err != nil {
		return err
	}

	return nil
}

func (p *Peer) receive(recvChan chan Frame, log chan string) {
	if p.conn == nil {
		return
	}
	for {
		// So now we have a connection.  Let's start receiving
		frame, err := recvAll(*p.conn, log)

		if err != nil {
			log <- fmt.Sprintln("Error receiving from Peer: ", err)
			KillPeer(p.String())
			break
		} else {
			frame.Peer = p.String()
			recvChan <- frame
		}
	} // End for
} // End receive()


text:
ActiveRecord::Schema.define(version: 20160714090144) do

  # These are extensions that must be enabled in order to support this database
  enable_extension "plpgsql"

  create_table "mail_sweeper_email_blacklists", force: :cascade do |t|
    t.string   "email",                               null: false
    t.integer  "block_counter",       default: 0,     null: false
    t.datetime "blocked_until"
    t.boolean  "permanently_blocked", default: false
    t.datetime "created_at",                          null: false
    t.datetime "updated_at",                          null: false
  end

  add_index "mail_sweeper_email_blacklists", ["email"], name: "index_mail_sweeper_email_blacklists_on_email", unique: true, using: :btree

end


text:
BOOST_FIXTURE_TEST_SUITE(base64_tests, BasicTestingSetup)

BOOST_AUTO_TEST_CASE(base64_testvectors)
{
    static const std::string vstrIn[]  = {"","f","fo","foo","foob","fooba","foobar"};
    static const std::string vstrOut[] = {"","Zg==","Zm8=","Zm9v","Zm9vYg==","Zm9vYmE=","Zm9vYmFy"};
    for (unsigned int i=0; i<sizeof(vstrIn)/sizeof(vstrIn[0]); i++)
    {
        std::string strEnc = EncodeBase64(vstrIn[i]);
        BOOST_CHECK_EQUAL(strEnc, vstrOut[i]);
        std::string strDec = DecodeBase64(strEnc);
        BOOST_CHECK_EQUAL(strDec, vstrIn[i]);
    }

    // Decoding strings with embedded NUL characters should fail
    bool failure;
    (void)DecodeBase64(std::string("invalid", 7), &failure);
    BOOST_CHECK_EQUAL(failure, true);
    (void)DecodeBase64(std::string("nQB/pZw=", 8), &failure);
    BOOST_CHECK_EQUAL(failure, false);
    (void)DecodeBase64(std::string("nQB/pZw=\0invalid", 16), &failure);
    BOOST_CHECK_EQUAL(failure, true);
    (void)DecodeBase64(std::string("nQB/pZw=invalid", 15), &failure);
    BOOST_CHECK_EQUAL(failure, true);
}

BOOST_AUTO_TEST_SUITE_END()


text:
package io.iyyel.celestialoutbreak.ui.screen.player_options;

import io.iyyel.celestialoutbreak.controller.GameController;
import io.iyyel.celestialoutbreak.data.dao.interfaces.IPlayerDAO;
import io.iyyel.celestialoutbreak.ui.screen.AbstractNavigationScreen;
import io.iyyel.celestialoutbreak.ui.screen.component.Button;

import java.awt.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public final class PlayerDeleteScreen extends AbstractNavigationScreen {

    private Button[] buttons;
    private int playerAmount = 0;
    private List<String> playerList;

    private final String origToolTip = "Press " + textHandler.BTN_CONTROL_AUX + " to mark a player for deletion. Press " + textHandler.BTN_CONTROL_OK + " to delete marked players.";
    private String tooltipString = origToolTip;

    private boolean isDeleting = false;
    private boolean[] deleteMarkings;

    public PlayerDeleteScreen(NavStyle navStyle, int btnAmount,
                              int btnWrapAmount, GameController gameController) {
        super(navStyle, btnAmount, btnWrapAmount, gameController);
    }

    protected void updateNavAux(int index) {
        if (isAuxPressed(index)) {
            String selectedPlayer = playerList.get(index);
            try {
                if (selectedPlayer.equals(playerDAO.getSelectedPlayer())) {
                    menuBadClip.play(false);
                } else {
                    menuAuxClip.play(false);
                    // invert
                    deleteMarkings[index] = !deleteMarkings[index];
                }
            } catch (IPlayerDAO.PlayerDAOException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    protected void updateNavOK(int index) {
        if (isOKPressed(index)) {
            if (isDeleting) {
                if (isAnyMarkedPlayers()) {
                    resetInputTimer();
                    selectedIndex = 0;
                    tooltipString = origToolTip;
                    isDeleting = false;
                    menuNavClip.play(false);
                    deletePlayers();
                    updatePlayerData();
                } else {
                    menuBadClip.play(false);
                }
            } else {
                if (isAnyMarkedPlayers()) {
                    resetInputTimer();
                    menuNavClip.play(false);
                    tooltipString = "Are you sure you want to delete marked players?";
                    isDeleting = true;
                } else {
                    menuBadClip.play(false);
                }
            }
        }
    }

    @Override
    public void update() {
        super.update();
        updateNavUp();
        updateNavDown();
        updateNavLeft();
        updateNavRight();
        updateNavOK(selectedIndex);
        updateNavCancel(gameController.getPrevState());
        updateNavAux(selectedIndex);
        updatePlayerColors();
        updateSelectedButtonColor(buttons);
    }

    @Override
    public void render(Graphics2D g) {
        if (isFirstRender) {
            isFirstRender = false;
            selectedIndex = 0;
            updatePlayerData();
            tooltipString = origToolTip;
            isDeleting = false;
            resetDeletions();
        }

        /* Render game title */
        drawScreenTitles(textHandler.TITLE_DELETE_PLAYER_SCREEN, g);

        /* Render buttons  */
        g.setFont(inputBtnFont);

        renderButtons(buttons, g);

        drawToolTip(tooltipString, g);
        drawInfoPanel(g);
    }

    private boolean isAnyMarkedPlayers() {
        for (boolean isDeleted : deleteMarkings) {
            if (isDeleted) {
                return true;
            }
        }
        return false;
    }

    private void resetDeletions() {
        Arrays.fill(deleteMarkings, false);
    }

    private void updatePlayerColors() {
        for (int i = 0; i < playerAmount; i++) {
            try {
                String player = playerList.get(i);
                String selectedPlayer = playerDAO.getSelectedPlayer();

                if (deleteMarkings[i]) {
                    buttons[i].setFgColor(menuBtnPlayerDeletedColor);
                } else if (player.equals(selectedPlayer)) {
                    buttons[i].setFgColor(menuBtnPlayerSelectedColor);
                } else {
                    buttons[i].setFgColor(menuBtnColor);
                }

            } catch (IPlayerDAO.PlayerDAOException e) {
                e.printStackTrace();
            }
        }
    }

    private void updatePlayerData() {
        try {
            playerDAO.loadPlayerDTO();
        } catch (IPlayerDAO.PlayerDAOException e) {
            e.printStackTrace();
        }

        playerList = new ArrayList<>(playerDAO.getPlayers());
        playerAmount = playerList.size();
        setNewButtonAmount(playerAmount);

        // default value = false
        deleteMarkings = new boolean[playerAmount];

        // Update rectangles
        buttons = new Button[playerAmount];

        int initialX = 240;
        int initialY = 230;
        int x = initialX;
        int y = initialY;
        int xInc = 200;
        int yInc = 80;

        for (int i = 0; i < playerAmount; i++) {

            if (i % 5 == 0 && i != 0) {
                x += xInc;
                y = initialY;
            }
            String player = playerDAO.getPlayers().get(i);
            buttons[i] = new Button(new Point(x, y), new Dimension(150, 50),
                    player, false, inputBtnFont, screenFontColor, menuBtnColor,
                    new Point(75, 0), new Point(70, -5), screenWidth, screenHeight);
            y += yInc;
        }
    }

    private void deletePlayers() {
        for (int i = 0; i < deleteMarkings.length; i++) {
            boolean isDeleted = deleteMarkings[i];
            String player = playerList.get(i);
            if (isDeleted) {
                try {
                    playerDAO.removePlayer(player);
                } catch (IPlayerDAO.PlayerDAOException e) {
                    e.printStackTrace();
                }
            }
        }

        try {
            playerDAO.savePlayerDTO();
        } catch (IPlayerDAO.PlayerDAOException e) {
            e.printStackTrace();
        }
    }

}


text:
package org.apache.spark.sql.execution.python

import org.apache.spark.api.python.PythonEvalType
import org.apache.spark.sql.catalyst.expressions._
import org.apache.spark.sql.execution.SparkPlan

/**
 * A relation produced by applying a function that takes an iterator of pandas DataFrames
 * and outputs an iterator of pandas DataFrames.
 */
case class MapInPandasExec(
    func: Expression,
    output: Seq[Attribute],
    child: SparkPlan)
  extends MapInBatchExec {

  override protected val pythonEvalType: Int = PythonEvalType.SQL_MAP_PANDAS_ITER_UDF

  override protected def withNewChildInternal(newChild: SparkPlan): MapInPandasExec =
    copy(child = newChild)
}


text:
package org.apache.flink.table.runtime.aggregate

import org.apache.flink.configuration.Configuration
import org.apache.flink.streaming.api.functions.ProcessFunction
import org.apache.flink.types.Row
import org.apache.flink.util.Collector
import org.apache.flink.api.common.state.ValueStateDescriptor
import org.apache.flink.api.java.typeutils.RowTypeInfo
import org.apache.flink.api.common.state.ValueState
import org.apache.flink.table.codegen.{GeneratedAggregationsFunction, Compiler}
import org.slf4j.LoggerFactory

/**
  * Process Function for processing-time unbounded OVER window
  *
  * @param genAggregations Generated aggregate helper function
  * @param aggregationStateType     row type info of aggregation
  */
class ProcTimeUnboundedPartitionedOver(
    genAggregations: GeneratedAggregationsFunction,
    aggregationStateType: RowTypeInfo)
  extends ProcessFunction[Row, Row]
    with Compiler[GeneratedAggregations] {

  private var output: Row = _
  private var state: ValueState[Row] = _
  val LOG = LoggerFactory.getLogger(this.getClass)
  private var function: GeneratedAggregations = _

  override def open(config: Configuration) {
    LOG.debug(s"Compiling AggregateHelper: $genAggregations.name \n\n " +
                s"Code:\n$genAggregations.code")
    val clazz = compile(
      getRuntimeContext.getUserCodeClassLoader,
      genAggregations.name,
      genAggregations.code)
    LOG.debug("Instantiating AggregateHelper.")
    function = clazz.newInstance()

    output = function.createOutputRow()
    val stateDescriptor: ValueStateDescriptor[Row] =
      new ValueStateDescriptor[Row]("overState", aggregationStateType)
    state = getRuntimeContext.getState(stateDescriptor)
  }

  override def processElement(
    input: Row,
    ctx: ProcessFunction[Row, Row]#Context,
    out: Collector[Row]): Unit = {

    var accumulators = state.value()

    if (null == accumulators) {
      accumulators = function.createAccumulators()
    }

    function.setForwardedFields(input, output)

    function.accumulate(accumulators, input)
    function.setAggregationResults(accumulators, output)

    state.update(accumulators)

    out.collect(output)
  }

}


text:
package net.runelite.client.plugins.kingdomofmiscellania;

import java.awt.image.BufferedImage;
import net.runelite.client.ui.overlay.infobox.Counter;
import net.runelite.client.util.QuantityFormatter;

public class KingdomCounter extends Counter
{
	private final KingdomPlugin plugin;

	KingdomCounter(BufferedImage image, KingdomPlugin plugin)
	{
		super(image, plugin, plugin.getFavor());
		this.plugin = plugin;
	}

	@Override
	public String getText()
	{
		return KingdomPlugin.getFavorPercent(plugin.getFavor()) + "%";
	}

	@Override
	public String getTooltip()
	{
		return "Favor: " + plugin.getFavor() + "/127" + "</br>"
			+ "Coffer: " + QuantityFormatter.quantityToStackSize(plugin.getCoffer());
	}
}


text:
package org.jboss.as.quickstart.xml;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import javax.enterprise.context.SessionScoped;
import javax.enterprise.inject.Produces;
import javax.inject.Named;

/**
 * Stores parsing errors
 *
 * @author baranowb
 *
 */
@SuppressWarnings("serial")
@SessionScoped
public class Errors implements Serializable {

    private List<Error> errorsList = new ArrayList<Error>();

    public void addErrorMessage(String severity, Exception e) {
        Error error = new Error(severity, e);
        this.errorsList.add(error);
    }

    @Produces
    @Named
    public List<Error> getErrorMessages() {
        return errorsList;
    }
}


text:
module Detail
  class My::NotesController < My::BaseController
    before_action :set_note

    def show
    end

    def edit
    end

    def update
      @note.assign_attributes note_params

      if @note.save
        render 'update'
      else
        render :edit, locals: { model: @note }, status: :unprocessable_entity
      end
    end

    def destroy
      @content.destroy
    end

    private
    def set_note
      @note = Note.find_or_initialize_by(detail_type: params[:detail_type], detail_id: params[:detail_id])
    end

    def note_params
      params[:note].permit(
        :title,
        :body,
        :key,
        :type
      )
    end

  end
end


text:
DROP FUNCTION IF EXISTS fn_calculateWinner;

Delimiter $$

CREATE DEFINER=`inqsports`@`%` FUNCTION fn_calculateWinner (nHomeTeamID int, nHomeScore int, nAwayTeamID int, nAwayScore int, nSpread double(8,2), sSpreadFavor varchar(5)) RETURNS int
NOT DETERMINISTIC
CONTAINS SQL
BEGIN

DECLARE nWinner int;
DECLARE nFavoriteScore int;
DECLARE nUnderdogScore int;

IF sSpreadFavor = 'home' THEN
    SET nFavoriteScore = nHomeScore;

    SET nUnderdogScore = nAwayScore;
    IF nFavoriteScore > (nUnderdogScore + nSpread) THEN
        SET nWinner = nHomeTeamID;
    ELSE
        SET nWinner = nAwayTeamID;
    END IF;

ELSE
    SET nFavoriteScore = nAwayScore;
    SET nUnderdogScore = nHomeScore;
    IF nFavoriteScore > (nUnderdogScore + nSpread) THEN
        SET nWinner = nAwayTeamID;
    ELSE
        SET nWinner = nHomeTeamID;
    END IF;
END IF;

RETURN nWinner;

END$$
DELIMITER ;


text:
StrongLink Installation Guide
=============================

Warning: Not for the faint of heart! This process will be streamlined over time. The eventual goal is to have native GUI apps and one-click web hosting. For now, it will take some elbow grease.

Dependencies
------------

Most of the dependencies are included. You might need to install Git to clone the repository, or you can use GitHub's ZIP download.

Additional dependencies:

Ubuntu / Debian / Linux Mint: `sudo apt-get install gcc g++ gobjc cmake automake autoconf libtool pkg-config`

Fedora / RedHat: `sudo yum install gcc gcc-c++ gcc-objc cmake automake autoconf libtool`

OS X: Install the developer tools from the App Store and cmake from Homebrew. [TODO]

Windows: untested, probably needs work

You can substitute Clang for GCC if you prefer.

A semi-recent version of [Node.js](https://nodejs.org/) or [io.js](https://iojs.org/) is required for the Node example scripts including `sln-pipe`.

Basic Installation
------------------

1. `cd deps/libressl-portable && ./update.sh` (TODO: make this step go away)
2. `./configure && make`
3. `sudo make install`
4. `stronglink /repo-dir`

If you don't want to run `make install`, you will need to manually symlink or copy the `res/blog` directory into the repo directory before running. For example: `ln -s res/blog /repo-dir/`

Server Configuration
--------------------

Right now there is no configuration interface whatsoever (not even a config file). That means you need to edit the code and recompile to change any settings.

- Port number: set `SERVER_PORT_RAW` and `SERVER_PORT_TLS` in `src/blog/main.c`
- Server access: set `SERVER_ADDRESS` in `src/blog/main.c`
- Database backend: use `DB=xx make` where `xx` is empty (for MDB), `leveldb`, `rocksdb`, or `hyper`
- Guest access: set `repo->pub_mode` from `0` to `SLN_RDONLY` or `SLN_RDWR`
- Number of results per page: `RESULTS_MAX` in `src/blog/Blog.c`
- Repo name: by default the name of the directory, but override `reponame` in `src/blog/main.c`
- Internal algorithm: `SLN_INTERNAL_ALGO` in `src/StrongLink.h` (only change for new repos!)
- Number of bcrypt rounds: `BCRYPT_ROUNDS` in `src/util/pass.c` (default 13)
- Logging: `SERVER_LOG_FILE` in `src/blog/main.c` (`stdout` or `NULL` for disabled)

Database Backends
-----------------

StrongLink supports several database backends including MDB (the default), LevelDB, RocksDB, and HyperLevelDB. MDB is the smallest and most stable, and it has the best read performance (making it good for public-facing sites). LevelDB has better write performance and compression (so the database storage can take 1/5th the space).

RocksDB is not recommended but might be useful for specialized applications since it has a lot of tuning options. HyperLevelDB is not recommended since it's generally worse than LevelDB.

The backend can be chosen at build time by setting the `DB` environment variable (see above). This might become a runtime option in the future.

It's not too difficult to add support for any transactional (ACID) key-value store. Embedded, write-optimized stores and distributed stores are the most interesting.

MDB and LevelDB are included in the Git repository. Other backends need to be installed separately to be used.

Client Configuration
--------------------

Clients (for example the Node example scripts) are configured through a JSON file located at `~/.config/stronglink/client.json`. That config file looks something like this:

```json
{
	"repos": {
		"main": {
			"url": "http://localhost:8000/",
			"session": "[...]"
		}
	}
}
```

Currently there is no interface for managing session keys. The only way to get one is by logging into the blog interface using a web browser or a tool like cURL and checking the cookie that is sent back.

You can set up any number of repositories and the names (like "main" above) are up to you.

You can also use URLs instead of pre-configured names. The session will be `null` (public access).

Feedback
--------

If you need any help installing, configuring or using StrongLink, feel free to open a GitHub issue, even if it's not a "bug" per se. Updates or corrections on the documentation are also welcome.


text:
namespace chromeos {

namespace secure_channel {

// Fields describing a connection attempt. At any given time, at most one
// connection attempt with a given set of ConnectionAttemptDetails should exist.
class ConnectionAttemptDetails {
 public:
  ConnectionAttemptDetails(const DeviceIdPair& device_id_pair,
                           ConnectionMedium connection_medium,
                           ConnectionRole connection_role);
  ConnectionAttemptDetails(const std::string& remote_device_id,
                           const std::string& local_device_id,
                           ConnectionMedium connection_medium,
                           ConnectionRole connection_role);
  ~ConnectionAttemptDetails();

  const std::string& remote_device_id() const {
    return device_id_pair_.remote_device_id();
  }
  const std::string& local_device_id() const {
    return device_id_pair_.local_device_id();
  }
  const DeviceIdPair& device_id_pair() const { return device_id_pair_; }
  ConnectionMedium connection_medium() const { return connection_medium_; }
  ConnectionRole connection_role() const { return connection_role_; }

  // Returns the ConnectionDetails associated with these
  // ConnectionAttemptDetails. Each host device (i.e., Android phone) uses a
  // single device ID for all accounts on the device, so this return value
  // indicates the intrinsic properties of a connection to that device (i.e.,
  // which device it is, and what medium the connection is).
  ConnectionDetails GetAssociatedConnectionDetails() const;

  // Returns whether |connection_details| is associated with these
  // ConnectionAttemptDetails.
  bool CorrespondsToConnectionDetails(
      const ConnectionDetails& connection_details) const;

  bool operator==(const ConnectionAttemptDetails& other) const;
  bool operator!=(const ConnectionAttemptDetails& other) const;
  bool operator<(const ConnectionAttemptDetails& other) const;

 private:
  DeviceIdPair device_id_pair_;
  ConnectionMedium connection_medium_;
  ConnectionRole connection_role_;
};

std::ostream& operator<<(std::ostream& stream,
                         const ConnectionAttemptDetails& details);

}  // namespace secure_channel

}  // namespace chromeos

#endif  // CHROMEOS_SERVICES_SECURE_CHANNEL_CONNECTION_ATTEMPT_DETAILS_H_


text:
package org.jkiss.dbeaver.model.sql.generator;

import org.jkiss.dbeaver.model.runtime.DBRProgressMonitor;
import org.jkiss.dbeaver.model.struct.DBSEntityAttribute;
import org.jkiss.dbeaver.model.struct.rdb.DBSProcedure;

import java.util.Collection;
import java.util.Collections;

public abstract class SQLGeneratorProcedure extends SQLGeneratorBase<DBSProcedure> {

    protected Collection<? extends DBSEntityAttribute> getAllAttributes(DBRProgressMonitor monitor, DBSProcedure object) {
        return Collections.emptyList();
    }

    protected Collection<? extends DBSEntityAttribute> getKeyAttributes(DBRProgressMonitor monitor, DBSProcedure object) {
        return Collections.emptyList();
    }
}


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

  <groupId>com.w11k.lsql</groupId>
  <artifactId>lsql-parent</artifactId>
  <version>0.36.2</version>
  <packaging>pom</packaging>

  <modules>
    <module>lsql-core</module>
    <module>lsql-guice</module>
    <module>lsql-generation-tests</module>
    <module>lsql-doc</module>
  </modules>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <github.global.server>github</github.global.server>
  </properties>

  <dependencyManagement>
    <dependencies>
      <!-- compile -->
      <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-api</artifactId>
        <version>1.7.7</version>
      </dependency>

      <dependency>
        <groupId>com.google.inject</groupId>
        <artifactId>guice</artifactId>
        <version>3.0</version>
      </dependency>
      <dependency>
        <groupId>com.google.guava</groupId>
        <artifactId>guava</artifactId>
        <version>23.0</version>
      </dependency>

      <dependency>
        <groupId>io.reactivex.rxjava2</groupId>
        <artifactId>rxjava</artifactId>
        <version>2.1.8</version>
      </dependency>

      <dependency>
        <groupId>joda-time</groupId>
        <artifactId>joda-time</artifactId>
        <version>2.2</version>
      </dependency>

      <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-core</artifactId>
        <version>2.2.2</version>
      </dependency>
      <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.2.2</version>
      </dependency>
      <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-annotations</artifactId>
        <version>2.2.2</version>
      </dependency>
      <dependency>
        <groupId>com.fasterxml.jackson.datatype</groupId>
        <artifactId>jackson-datatype-joda</artifactId>
        <version>2.3.1</version>
      </dependency>

      <!-- for dialect -->
      <dependency>
        <groupId>org.postgresql</groupId>
        <artifactId>postgresql</artifactId>
        <version>42.2.1</version>
      </dependency>

      <!-- test -->
      <dependency>
        <groupId>org.testng</groupId>
        <artifactId>testng</artifactId>
        <version>6.8.5</version>
        <scope>test</scope>
      </dependency>
      <dependency>
        <groupId>commons-dbcp</groupId>
        <artifactId>commons-dbcp</artifactId>
        <version>1.4</version>
        <scope>test</scope>
      </dependency>
      <dependency>
        <groupId>com.googlecode.flyway</groupId>
        <artifactId>flyway-core</artifactId>
        <version>2.2</version>
        <scope>test</scope>
      </dependency>
      <dependency>
        <groupId>com.h2database</groupId>
        <artifactId>h2</artifactId>
        <version>1.3.172</version>
        <scope>test</scope>
      </dependency>
      <dependency>
        <groupId>net.sourceforge.jtds</groupId>
        <artifactId>jtds</artifactId>
        <version>1.3.0</version>
        <scope>test</scope>
      </dependency>
    </dependencies>
  </dependencyManagement>

  <build>
    <testResources>
      <testResource>
        <directory>src/test/java</directory>
      </testResource>
      <testResource>
        <directory>src/test/resources</directory>
      </testResource>
    </testResources>
    <resources>
      <resource>
        <directory>src/main/java</directory>
      </resource>
      <resource>
        <directory>src/main/resources</directory>
      </resource>
    </resources>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>2.3.2</version>
        <configuration>
          <source>1.8</source>
          <target>1.8</target>
          <compilerArgument>-Xlint:unchecked</compilerArgument>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-resources-plugin</artifactId>
        <version>2.5</version>
        <configuration>
          <encoding>UTF-8</encoding>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-source-plugin</artifactId>
        <version>2.2.1</version>
        <executions>
          <execution>
            <id>attach-sources</id>
            <goals>
              <goal>jar</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>

  <distributionManagement>
    <repository>
      <id>bintray-w11k-lsql</id>
      <name>w11k-lsql</name>
      <url>https://api.bintray.com/maven/w11k/lsql/releases/;publish=1</url>
    </repository>
  </distributionManagement>

</project>


text:
package org.apache.spark.ml.feature

import org.apache.spark.SparkFunSuite
import org.apache.spark.ml.attribute.{Attribute, AttributeGroup, NumericAttribute}
import org.apache.spark.ml.param.ParamsSuite
import org.apache.spark.mllib.linalg.{Vector, Vectors}
import org.apache.spark.mllib.util.MLlibTestSparkContext
import org.apache.spark.sql.types.StructType
import org.apache.spark.sql.{DataFrame, Row, SQLContext}
/**
 * VectorSlicer是一个转换器输入特征向量,输出原始特征向量子集.
 * 向量切分,单词向量它用1和0分别表示是否存在某个词
 */
class VectorSlicerSuite extends SparkFunSuite with MLlibTestSparkContext {

  test("params") {//参数
    val slicer = new VectorSlicer
    ParamsSuite.checkParams(slicer)
    //指数
    assert(slicer.getIndices.length === 0)
    //名称
    assert(slicer.getNames.length === 0)
    withClue("VectorSlicer should not have any features selected by default") {
      intercept[IllegalArgumentException] {
        slicer.validateParams()
      }
    }
  }

  test("feature validity checks") {//特征有效性检查
    import VectorSlicer._
    //如果给定的特征索引是有效的,返回true
    assert(validIndices(Array(0, 1, 8, 2)))
    assert(validIndices(Array.empty[Int]))
    assert(!validIndices(Array(-1)))
    assert(!validIndices(Array(1, 2, 1)))
    //如果给定的特征名称有效,返回true
    assert(validNames(Array("a", "b")))
    assert(validNames(Array.empty[String]))
    assert(!validNames(Array("", "b")))
    assert(!validNames(Array("a", "b", "a")))
  }

  test("Test vector slicer") {//测试向量机
    val sqlContext = new SQLContext(sc)

    val data = Array(
      Vectors.sparse(5, Seq((0, -2.0), (1, 2.3))),
      Vectors.dense(-2.0, 2.3, 0.0, 0.0, 1.0),
      Vectors.dense(0.0, 0.0, 0.0, 0.0, 0.0),
      Vectors.dense(0.6, -1.1, -3.0, 4.5, 3.3),
      Vectors.sparse(5, Seq())
    )

    // Expected after selecting indices 1, 4
    //预计在选择指数1,4
    val expected = Array(
      Vectors.sparse(2, Seq((0, 2.3))),
      Vectors.dense(2.3, 1.0),
      Vectors.dense(0.0, 0.0),
      Vectors.dense(-1.1, 3.3),
      Vectors.sparse(2, Seq())
    )

    val defaultAttr = NumericAttribute.defaultAttr
    val attrs = Array("f0", "f1", "f2", "f3", "f4").map(defaultAttr.withName)
    val attrGroup = new AttributeGroup("features", attrs.asInstanceOf[Array[Attribute]])

    val resultAttrs = Array("f1", "f4").map(defaultAttr.withName)
    val resultAttrGroup = new AttributeGroup("expected", resultAttrs.asInstanceOf[Array[Attribute]])

    val rdd = sc.parallelize(data.zip(expected)).map { case (a, b) => Row(a, b) }

    val df = sqlContext.createDataFrame(rdd,
        StructType(Array(attrGroup.toStructField(), resultAttrGroup.toStructField())))
    //VectorSlicer是一个转换器输入特征向量,输出原始特征向量子集.
    val vectorSlicer = new VectorSlicer().setInputCol("features").setOutputCol("result")

    def validateResults(df: DataFrame): Unit = {
      df.select("result", "expected").collect().foreach { case Row(vec1: Vector, vec2: Vector) =>
        assert(vec1 === vec2)
      }
      val resultMetadata = AttributeGroup.fromStructField(df.schema("result"))
      val expectedMetadata = AttributeGroup.fromStructField(df.schema("expected"))
      assert(resultMetadata.numAttributes === expectedMetadata.numAttributes)
      resultMetadata.attributes.get.zip(expectedMetadata.attributes.get).foreach { case (a, b) =>
        assert(a === b)
      }
    }

    vectorSlicer.setIndices(Array(1, 4)).setNames(Array.empty)
    validateResults(vectorSlicer.transform(df))//transform主要是用来把 一个 DataFrame 转换成另一个 DataFrame

    vectorSlicer.setIndices(Array(1)).setNames(Array("f4"))
    //transform主要是用来把 一个 DataFrame 转换成另一个 DataFrame

    validateResults(vectorSlicer.transform(df))

    vectorSlicer.setIndices(Array.empty).setNames(Array("f1", "f4"))
    //transform主要是用来把 一个 DataFrame 转换成另一个 DataFrame

    validateResults(vectorSlicer.transform(df))
  }
}


text:
import posixpath

from django.conf import settings
from django.core.exceptions import MultipleObjectsReturned, PermissionDenied
from django.db.models import Q
from django.db.transaction import on_commit
from django.http import Http404, HttpResponseRedirect
from django.utils._os import safe_join
from guardian.shortcuts import get_objects_for_user
from knox.auth import TokenAuthentication
from rest_framework.exceptions import AuthenticationFailed

from grandchallenge.cases.models import Image
from grandchallenge.components.models import ComponentInterfaceValue
from grandchallenge.core.storage import internal_protected_s3_storage
from grandchallenge.evaluation.models import Submission
from grandchallenge.serving.tasks import create_download

def protected_storage_redirect(*, name):
    # Get the storage with the internal redirect and auth. This will prepend
    # settings.PROTECTED_S3_STORAGE_KWARGS['endpoint_url'] to the url
    if not internal_protected_s3_storage.exists(name=name):
        raise Http404("File not found.")

    if settings.PROTECTED_S3_STORAGE_USE_CLOUDFRONT:
        response = HttpResponseRedirect(
            internal_protected_s3_storage.cloudfront_signed_url(name=name)
        )
    else:
        url = internal_protected_s3_storage.url(name=name)
        response = HttpResponseRedirect(url)

    return response

def serve_images(request, *, pk, path, pa="", pb=""):
    document_root = safe_join(
        f"/{settings.IMAGE_FILES_SUBDIRECTORY}", pa, pb, str(pk)
    )
    path = posixpath.normpath(path).lstrip("/")
    name = safe_join(document_root, path)

    try:
        image = Image.objects.get(pk=pk)
    except Image.DoesNotExist:
        raise Http404("Image not found.")

    try:
        user, _ = TokenAuthentication().authenticate(request)
    except (AuthenticationFailed, TypeError):
        user = request.user

    if user.has_perm("view_image", image):
        on_commit(
            lambda: create_download.apply_async(
                kwargs={"creator_id": user.pk, "image_id": image.pk}
            )
        )
        return protected_storage_redirect(name=name)

    raise PermissionDenied

def serve_submissions(request, *, submission_pk, **_):
    try:
        submission = Submission.objects.get(pk=submission_pk)
    except Submission.DoesNotExist:
        raise Http404("Submission not found.")

    if request.user.has_perm("view_submission", submission):
        on_commit(
            lambda: create_download.apply_async(
                kwargs={
                    "creator_id": request.user.pk,
                    "submission_id": submission.pk,
                }
            )
        )
        return protected_storage_redirect(
            name=submission.predictions_file.name
        )

    raise PermissionDenied

def serve_component_interface_value(
    request, *, component_interface_value_pk, **_
):
    try:
        user, _ = TokenAuthentication().authenticate(request)
    except (AuthenticationFailed, TypeError):
        user = request.user

    try:
        # output should only be connected to a single job; throw error if not?
        civ = ComponentInterfaceValue.objects.get(
            pk=component_interface_value_pk
        )
    except (MultipleObjectsReturned, ComponentInterfaceValue.DoesNotExist):
        raise Http404("No ComponentInterfaceValue found.")

    if (
        get_objects_for_user(user=user, perms="algorithms.view_job")
        .filter(
            Q(outputs__pk=component_interface_value_pk)
            | Q(inputs__pk=component_interface_value_pk)
        )
        .exists()
    ):
        return protected_storage_redirect(name=civ.file.name)

    raise PermissionDenied


text:
using UnityEngine;

namespace BehaviorDesigner.Runtime.Tasks.Basic.UnityQuaternion
{
    [TaskCategory("Basic/Quaternion")]
    [TaskDescription("Stores the rotation which rotates the specified degrees around the specified axis.")]
    public class AngleAxis : Action
    {
        [Tooltip("The number of degrees")]
        public SharedFloat degrees;
        [Tooltip("The axis direction")]
        public SharedVector3 axis;
        [Tooltip("The stored result")]
        [RequiredField]
        public SharedQuaternion storeResult;

        public override TaskStatus OnUpdate()
        {
            storeResult.Value = Quaternion.AngleAxis(degrees.Value, axis.Value);
            return TaskStatus.Success;
        }

        public override void OnReset()
        {
            degrees = 0;
            axis = Vector3.zero;
            storeResult = Quaternion.identity;
        }
    }
}


text:
\section{Hive}

To start hive in CLI mode, type \verb$hive$ or

\begin{verbatim}
beeline -u jdbc:hive2://
\end{verbatim}

Check built-in functions:

Hive Function Meta commands

\begin{itemize}
  \item
SHOW FUNCTIONS– lists Hive functions and operators
  \item
DESCRIBE FUNCTION [function name]– displays short description of the function
  \item
DESCRIBE FUNCTION EXTENDED [function name]– access extended description of the function
\end{itemize}

\url{https://www.qubole.com/resources/cheatsheet/hive-function-cheat-sheet/}

\subsection{basic commands}

Database/Schema create:

\begin{verbatim}
  create database NAME;
\end{verbatim}

Table create:
\begin{verbatim}
CREATE EXTERNAL TABLE test_p(
id int,
name string
)
partitioned by (date STRING)
ROW FORMAT DELIMITED FIELDS TERMINATED BY '\,' LINES TERMINATED BY '\n'
STORED AS TEXTFILE;
\end{verbatim}

Data loading:

\begin{verbatim}
LOAD DATA [LOCAL] INPATH 'filepath' [OVERWRITE] INTO TABLE tablename [PARTITION (partcol1=val1, partcol2=val2 ...)]
\end{verbatim}

Data insert:
\begin{verbatim}
insert overwrite table session_hour_partition_save PARTITION (date='20170101',hour='01') select ....
\end{verbatim}

From Hive to HDFS:
\begin{verbatim}
insert overwrite  directory '/user/hive/tmp' select * from test;
\end{verbatim}

\subsection{Mapjoin: a trick to accelerate small table joins}

  Mapjoin is a little-known feature of Hive.
  It allows a table to be loaded into memory so that a (very fast) join could be performed entirely within a mapper without having to use a Map/Reduce step.
  If your queries frequently rely on small table joins (e.g. cities or countries, etc.) you might see a very substantial speed-up from using mapjoins.
There are two ways to enable it.
First is by using a hint, which looks like \verb$/*+ MAPJOIN(aliasname), MAPJOIN(anothertable) */$.
This C-style comment should be placed immediately following the SELECT.
It directs Hive to load aliasname (which is a table or alias of the query) into memory.

\begin{verbatim}
  SELECT /*+ MAPJOIN(c) */ * FROM orders o JOIN cities c ON (o.city_id = c.id);
\end{verbatim}

Another (better, in my opinion) way to turn on mapjoins is to let Hive do it automatically.
 Simply set hive.auto.convert.join to true in your config,
 and Hive will automatically use mapjoins for any tables smaller than hive.mapjoin.smalltable.filesize (default is 25MB).

Mapjoins have a limitation in that the same table or alias cannot be used to join on different columns in the same query.
(This makes sense because presumably Hive uses a HashMap keyed on the column(s) used in the join, and such a HashMap would be of no use for a join on different keys).
The workaround is very simple - do not use the same aliases in your query.