text:
using System;
using System.Collections.Generic;
using System.IO;

namespace FastQuant
{
    public class FileOrderServer : OrderServer
    {
        private DataFile dataFile;

        private DataSeries dataSeries;

        private IdArray<DataSeries> serieses = new IdArray<DataSeries>();

        private int count;

        public string Host { get; }

        public int Port { get; }

        public FileOrderServer(Framework framework, string fileName, string host = null, int port = -1) : base(framework)
        {
            Host = host;
            Port = port;
            this.dataFile = host == null ? new DataFile(fileName, framework.StreamerManager) : new NetDataFile(fileName, host, port, framework.StreamerManager);
        }

        public override void Open()
        {
            if (!this.isOpen)
            {
                this.dataFile.Open(FileMode.OpenOrCreate);
                this.isOpen = true;
            }
        }

        public override void Close()
        {
            if (this.isOpen)
            {
                this.dataFile.Close();
                this.isOpen = false;
            }
        }

        public override void Clear()
        {
        }

        public override void Delete(string name)
        {
            this.dataFile.Delete(name);
            if (name == this.seriesName)
                this.dataSeries = null;
        }

        public override void Flush()
        {
            if (this.isOpen)
            {
                this.dataFile.Flush();
            }
        }

        public override int Get(string seriesName)
        {
            if (this.idByName.ContainsKey(seriesName))
                return this.idByName[seriesName];

            var dataSeries = (DataSeries)this.dataFile.Get(seriesName);
            if (dataSeries == null)
            {
                dataSeries = Host == null ? new DataSeries(seriesName) : new NetDataSeries(seriesName);
                this.dataFile.Write(seriesName, dataSeries);
            }
            int num = this.count++;
            this.idByName[seriesName] = num;
            this.nameById[num] = seriesName;
            this.serieses[num] = dataSeries;
            return num;
        }

        public override List<ExecutionMessage> Load(string name = null)
        {
            if (name == null)
                name = this.seriesName;
            var list = new List<ExecutionMessage>();
            var series = (DataSeries)this.dataFile.Get(name);
            if (series != null)
            {
                for (long i = 0; i < series.Count; i++)
                {
                    var message = (ExecutionMessage)series[i];
                    message.IsLoaded = true;
                    list.Add(message);
                }
            }
            return list;
        }

        public override void Save(ExecutionMessage message, int id = -1)
        {
            DataSeries series;
            if (id == -1)
            {
                if (this.dataSeries == null)
                {
                    int id2 = Get(this.seriesName);
                    this.dataSeries = this.serieses[id2];
                    series = this.dataSeries;
                }
                else
                {
                    series = this.dataSeries;
                }
            }
            else
            {
                series = this.serieses[id];
                if (series == null)
                {
                    Console.WriteLine($"FileOrderServer::Save Error. Series with id does not exist : {id}");
                    return;
                }
            }
            series.Add(message);
        }
    }
}


text:
from flask import jsonify, render_template
import random
from maraschino.noneditable import *
from maraschino.modules import *
from maraschino.tools import requires_auth, get_setting_value
import maraschino
from maraschino import logger

@app.route('/')
@requires_auth
def index():
    from maraschino.models import Module, Application, PlexServer

    unorganised_modules = Module.query.order_by(Module.position)

    num_columns = get_setting_value('num_columns')

    try:
        num_columns = int(num_columns)

    except:
        logger.log('Could not retrieve number of columns settings. Defaulting to 3.' , 'WARNING')
        num_columns = 3

    modules = []

    for i in range(num_columns):
        modules.append([])

    for module in unorganised_modules:
        module_info = get_module_info(module.name)
        module.template = '%s.html' % (module.name)
        module.static = module_info['static']

        if module.column <= num_columns:
            modules[module.column - 1].append(module)

        else:
            modules[num_columns - 1].append(module) # if in a column out of range, place in last column

    applications = []

    try:
        applications = Application.query.order_by(Application.position)

    except:
        pass

    new_tab = get_setting_value('app_new_tab') == '1'

    # display random background when not watching media (if setting enabled)
    # only changes on page refresh

    background = None

    if get_setting_value('random_backgrounds') == '1':
        try:
            backgrounds = []
            custom_dir = 'static/images/backgrounds/custom/'

            if os.path.exists(os.path.dirname(custom_dir)):
                # use user-defined custom background
                backgrounds.extend(get_file_list(custom_dir, ['.jpg', '.png']))

                # if no images in directory, use default background that is set in stylesheet
                if len(backgrounds) == 0:
                    backgrounds = None

            else:
                # use backgrounds bundled with Maraschino
                backgrounds.extend(get_file_list('static/images/backgrounds/', ['.jpg', '.png']))

            # select random background
            background = backgrounds[random.randrange(0, len(backgrounds))]
            if maraschino.WEBROOT:
                background = maraschino.WEBROOT + '/' + background

        except:
            background = None

    # get list of servers
    servers = PlexServer.query.order_by(PlexServer.id)
    active_server = get_setting_value('active_server')
    if active_server:
        active_server = int(active_server)

    return render_template('index.html',
        modules=modules,
        num_columns=num_columns,
        search_enabled=get_setting_value('search') == '1',
        background=background,
        applications=applications,
        show_tutorial=unorganised_modules.count() == 0,
        webroot=maraschino.WEBROOT,
        kiosk=maraschino.KIOSK,
        new_tab=new_tab,
        title_color=get_setting_value('title_color'),
        servers=servers,
        active_server=active_server,
    )

@app.route('/xhr/shutdown')
@requires_auth
def maraschino_shutdown():
    maraschino.stop()
    return jsonify(shutdown_complete=True)

@app.route('/xhr/restart')
@requires_auth
def xhr_restart():
    maraschino.restart()
    return jsonify(restart_complete=True)

@app.route('/shutdown')
@requires_auth
def shutdown_url():
    return render_template('power.html', shutdown=True)

@app.route('/restart')
@requires_auth
def restart_url():
    return render_template('power.html', restart=True)

redpajama_set_name: RedPajamaGithub


text:
    <canvas baseChart
            [datasets]="lineChartData"
            [options]="lineChartOptions"
            [legend]="lineChartLegend"
            type="line">
    </canvas>


text:
package org.yi.spider.pool2;

import org.apache.commons.pool2.impl.GenericKeyedObjectPool;
import org.yi.spider.service.IChapterService;

public class ChapterObjectPool {

	private static GenericKeyedObjectPool<String, IChapterService> chapterPool;

	private ChapterObjectPool() {

	}

	public static GenericKeyedObjectPool<String, IChapterService> getPool() {
		if(chapterPool == null) {
			synchronized (ChapterObjectPool.class) {
				if(chapterPool == null) {
					chapterPool = new GenericKeyedObjectPool<String, IChapterService>(new ChapterPooledObjectFactory());
				}
			}
		}
		return chapterPool;
	}

}


text:
package com.jcwhatever.nucleus.internal.managed.items.meta;

import com.jcwhatever.nucleus.managed.items.meta.IItemMetaHandler;
import com.jcwhatever.nucleus.managed.items.meta.ItemMetaValue;
import com.jcwhatever.nucleus.utils.PreCon;
import com.jcwhatever.nucleus.utils.text.TextUtils;
import org.bukkit.Material;
import org.bukkit.inventory.ItemStack;

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

/**
 * Handles {@link org.bukkit.inventory.ItemStack} potion ID.
 *
 * @see InternalItemMetaHandlers
 */
public class ItemPotion implements IItemMetaHandler {

    @Override
    public String getMetaName() {
        return "potionId";
    }

    @Override
    public boolean canHandle(ItemStack itemStack) {
        PreCon.notNull(itemStack);

        return itemStack.getType() == Material.POTION && itemStack.getDurability() != 0;
    }

    @Override
    public boolean apply(ItemStack itemStack, ItemMetaValue meta) {
        PreCon.notNull(itemStack);
        PreCon.notNull(meta);

        if (!meta.getName().equals(getMetaName()))
            return false;

        short potionId = TextUtils.parseShort(meta.getRawData(), (short)0);

        itemStack.setDurability(potionId);

        return true;
    }

    @Override
    public List<ItemMetaValue> getMeta(ItemStack itemStack) {
        PreCon.notNull(itemStack);

        if (!canHandle(itemStack))
            return new ArrayList<>(0);

        List<ItemMetaValue> result = new ArrayList<>(1);

        result.add(new ItemMetaValue(getMetaName(), String.valueOf(itemStack.getDurability())));

        return result;
    }
}


text:
'use strict';
var async = require('async'),
	path = require('path'),
	fs = require('fs'),
	debug = require('debug')('bundler'),
	shell = require('shelljs'),
	archiver = require('archiver'),
	logger = require('./util/logger').getLogger();
/**
 *
 * @param options
 * sample
 * {
 *      taskname : bundle
 *      config : [Object] //Json 'bundle' config
 *      metrics : [Object] //metrics object
 * }
 * @param callback
 */
function execBundle (options, callback) {

	debug('start bundle : ' + JSON.stringify(options));

	var taskname = options.taskname,
		bundleConfig = options.config,
		metrics = options.metrics,
		execConfig = bundleConfig[taskname];

	logger.info("Bundle format : " + execConfig.format);

	if (execConfig.format === "custom") {
		return callback(null, bundleConfig);
	}

	var rand = Math.floor((Math.random()*10000)+1),
		source = execConfig.source || path.join(shell.tempdir(), 'sourcetemp' + rand),
		excludeSource = path.relative(process.cwd(), source) || source;

	//Clean up the Target Directory
	if (fs.existsSync(execConfig.target)) {
		shell.rm('-rf', execConfig.target);
	}
	//Create source dir it does not exists
	if (!fs.existsSync(source)) {
		shell.mkdir('-p', source);
	}
    /**
     *  Invoke the Rsync
     */
    var cmd = 'rsync -arl --exclude ' + excludeSource + ' --exclude ' + execConfig.target +
		 ' ' + getIgnoreList(execConfig) + ' ' + process.cwd() + '/' +
		 ' ' + source;

    debug("Rsync command " + cmd);

	shell.exec(cmd, function (code, output) {

		if ( code !== 0) {
			return callback(output, bundleConfig);
		} else {
			//If its just copy with excludes then exit it immediately the copy is done.
			if (execConfig.format === "copy") {
				logger.info("Copied files to " + source);
				return callback(null, bundleConfig);
			}
			// success
			if (!fs.existsSync(execConfig.target)) {
				shell.mkdir('-p', execConfig.target);
			}
			var outfile = path.join(execConfig.target, metrics.application + "." + execConfig.format),
				bundleOut = fs.createWriteStream(outfile),
				archive = archievers[execConfig.format]();

			bundleOut.on('close', function() {
				logger.info(archive.pointer() + ' total bytes');
				logger.info('Completed archive and the output file created ' + outfile);
				shell.rm('-rf', source);
				callback(null, bundleConfig);
			});

			archive.on('error', function(err) {
				logger.error('ERROR during Bundling');
				logger.error(err);
				callback(err, bundleConfig);
			});

			archive.pipe(bundleOut);

			archive.bulk([

				{ expand: true, cwd: source, src: ['**'], dest : execConfig.target }
			]);

			archive.finalize();
		}
	});
}
/**
 *
 * @param execConfig
 * @returns {Array}
 */
function getIgnoreList(execConfig) {
	var files = [];
	var ignoreFiles = execConfig.ignorefile,
		defaultFile = path.join(process.cwd(), '.defaultignore');
	if (!ignoreFiles || ignoreFiles.length === 0) {
		ignoreFiles = [];
	}
	if (!fs.existsSync(defaultFile)){
		shell.cp(path.join(__dirname, '..', 'config', '.defaultignore'), defaultFile);
	}

	ignoreFiles.unshift(defaultFile);
	debug("Ignore Files : " + ignoreFiles);

	ignoreFiles = ignoreFiles.map(function(file){

		if (fs.existsSync(file)){
			return "--exclude-from " + file;
		} else {
			return "";
		}

	});
	return ignoreFiles.join(" ");
}

/**
 *
 * @type {{tar: tar, tgz: tgz, zip: zip}}
 */
var archievers = {
	tar : function () {
		return archiver('tar');
	},
	tgz : function () {

		return archiver('tar', {
			gzip: true,
			gzipOptions: {
				level: 1
			}
		});
	},
	zip : function () {
		return archiver('zip');
	}
};

module.exports = {
	bundle: execBundle
};


text:
namespace SharpDX.Toolkit.Graphics
{
    /// <summary>
    /// The <see cref="A:SharpDX.Toolkit.Graphics"/> assembly provides a high level Direct3D11 API.
    /// </summary>
    [System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
    class AssemblyDoc
    {
    }
}


text:
<?php

namespace OVGS\TestBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * User
 *
 * @ORM\Table(name="administrators")
 * @ORM\Entity
 */
class Users
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer", nullable=false)
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="NONE")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="first_name", type="string", length=15, nullable=false)
     */
    private $firstName;

    /**
     * @var string
     *
     * @ORM\Column(name="last_name", type="string", length=15, nullable=false)
     */
    private $lastName;

    /**
     * @var string
     *
     * @ORM\Column(name="user_name", type="string", length=10, nullable=false)
     */
    private $userName;

    /**
     * @var string
     *
     * @ORM\Column(name="email", type="string", length=100, nullable=false)
     */
    private $email;

    /**
     * @var string
     *
     * @ORM\Column(name="salt", type="string", length=32, nullable=true)
     */
    private $salt;

    /**
     * @var string
     *
     * @ORM\Column(name="password", type="string", length=32, nullable=true)
     */
    private $password;

    /**
     * @var boolean
     *
     * @ORM\Column(name="is_active", type="boolean", nullable=true)
     */
    private $isActive;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="last_login", type="datetime", nullable=true)
     */
    private $lastLogin;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="created_at", type="datetime", nullable=true)
     */
    private $createdAt;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="modified_at", type="datetime", nullable=true)
     */
    private $modifiedAt;

    /**
     * @var \Role
     *
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="NONEDENTITY")
     * @ORM\OneToOne(targetEntity="Role")
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="role_id", referencedColumnName="id")
     * })
     */
    private $role;

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set firstName
     *
     * @param string $firstName
     * @return Users
     */
    public function setFirstName($firstName)
    {
        $this->firstName = $firstName;

        return $this;
    }

    /**
     * Get firstName
     *
     * @return string
     */
    public function getFirstName()
    {
        return $this->firstName;
    }

    /**
     * Set lastName
     *
     * @param string $lastName
     * @return Users
     */
    public function setLastName($lastName)
    {
        $this->lastName = $lastName;

        return $this;
    }

    /**
     * Get lastName
     *
     * @return string
     */
    public function getLastName()
    {
        return $this->lastName;
    }

    /**
     * Set userName
     *
     * @param string $userName
     * @return Users
     */
    public function setUserName($userName)
    {
        $this->userName = $userName;

        return $this;
    }

    /**
     * Get userName
     *
     * @return string
     */
    public function getUserName()
    {
        return $this->userName;
    }

    /**
     * Set email
     *
     * @param string $email
     * @return Users
     */
    public function setEmail($email)
    {
        $this->email = $email;

        return $this;
    }

    /**
     * Get email
     *
     * @return string
     */
    public function getEmail()
    {
        return $this->email;
    }

    /**
     * Set salt
     *
     * @param string $salt
     * @return Users
     */
    public function setSalt($salt)
    {
        $this->salt = $salt;

        return $this;
    }

    /**
     * Get salt
     *
     * @return string
     */
    public function getSalt()
    {
        return $this->salt;
    }

    /**
     * Set password
     *
     * @param string $password
     * @return Users
     */
    public function setPassword($password)
    {
        $this->password = $password;

        return $this;
    }

    /**
     * Get password
     *
     * @return string
     */
    public function getPassword()
    {
        return $this->password;
    }

    /**
     * Set isActive
     *
     * @param boolean $isActive
     * @return Users
     */
    public function setIsActive($isActive)
    {
        $this->isActive = $isActive;

        return $this;
    }

    /**
     * Get isActive
     *
     * @return boolean
     */
    public function getIsActive()
    {
        return $this->isActive;
    }

    /**
     * Set lastLogin
     *
     * @param \DateTime $lastLogin
     * @return Users
     */
    public function setLastLogin($lastLogin)
    {
        $this->lastLogin = $lastLogin;

        return $this;
    }

    /**
     * Get lastLogin
     *
     * @return \DateTime
     */
    public function getLastLogin()
    {
        return $this->lastLogin;
    }

    /**
     * Set createdAt
     *
     * @param \DateTime $createdAt
     * @return Users
     */
    public function setCreatedAt($createdAt)
    {
        $this->createdAt = $createdAt;

        return $this;
    }

    /**
     * Get createdAt
     *
     * @return \DateTime
     */
    public function getCreatedAt()
    {
        return $this->createdAt;
    }

    /**
     * Set modifiedAt
     *
     * @param \DateTime $modifiedAt
     * @return Users
     */
    public function setModifiedAt($modifiedAt)
    {
        $this->modifiedAt = $modifiedAt;

        return $this;
    }

    /**
     * Get modifiedAt
     *
     * @return \DateTime
     */
    public function getModifiedAt()
    {
        return $this->modifiedAt;
    }

    /**
     * Set role
     *
     * @param \OVGS\TestBundle\Entity\Role $role
     * @return Users
     */
    public function setRole(\OVGS\TestBundle\Entity\Role $role)
    {
        $this->role = $role;

        return $this;
    }

    /**
     * Get role
     *
     * @return \OVGS\TestBundle\Entity\Role
     */
    public function getRole()
    {
        return $this->role;
    }
}


text:
namespace HstWbInstaller.Imager.Core.Commands
{
    using System.Collections.Generic;
    using System.IO;
    using System.Threading.Tasks;
    using HstWbInstaller.Core;
    using HstWbInstaller.Core.IO.RigidDiskBlocks;
    using Models;

    public interface ICommandHelper
    {
        Result<Media> GetReadableMedia(IEnumerable<IPhysicalDrive> physicalDrives, string path, bool allowPhysicalDrive = true);
        Result<Media> GetWritableMedia(IEnumerable<IPhysicalDrive> physicalDrives, string path, long? size = null,
            bool allowPhysicalDrive = true);
        long GetVhdSize(long size);
        bool IsVhd(string path);
        Task<RigidDiskBlock> GetRigidDiskBlock(Stream stream);
    }
}


text:
typedef void (*IDT_InterruptHandler)(void);

typedef struct IDT_Descriptor
{
    u16 HandlerLo; // Interrupt routine

    u16 GDTSelector;
    u8	 Reserved; // TODO: Skip this byte

    u8	 Flags;

    u16 HandlerHi;
} IDT_Descriptor;

typedef struct IDT_Data
{
    u16 Limit;
    u32 Base;
} IDT_Data;

void IDT_Install();

IDT_Descriptor* IDT_GetIR(u32 i);
void IDT_InstallIR(u32 i, u16 flags, u16 sel, IDT_InterruptHandler irq);

void IDT_Initialize();

#endif


text:
package v1beta1

import (
	"fmt"
	"reflect"

	"regexp"

	"github.com/kubeflow/kfserving/pkg/utils"
	"k8s.io/apimachinery/pkg/runtime"
	logf "sigs.k8s.io/controller-runtime/pkg/log"
	"sigs.k8s.io/controller-runtime/pkg/webhook"
)

// regular expressions for validation of isvc name
const (
	IsvcNameFmt string = "[a-z]([-a-z0-9]*[a-z0-9])?"
)

var (
	// logger for the validation webhook.
	validatorLogger = logf.Log.WithName("inferenceservice-v1beta1-validation-webhook")
	// regular expressions for validation of isvc name
	IsvcRegexp = regexp.MustCompile("^" + IsvcNameFmt + "$")
)

// +kubebuilder:webhook:verbs=create;update,path=/validate-inferenceservices,mutating=false,failurePolicy=fail,groups=serving.kubeflow.org,resources=inferenceservices,versions=v1beta1,name=inferenceservice.kfserving-webhook-server.validator
var _ webhook.Validator = &InferenceService{}

// ValidateCreate implements webhook.Validator so a webhook will be registered for the type
func (isvc *InferenceService) ValidateCreate() error {
	validatorLogger.Info("validate create", "name", isvc.Name)

	if err := validateInferenceServiceName(isvc); err != nil {
		return err
	}

	for _, component := range []Component{
		&isvc.Spec.Predictor,
		isvc.Spec.Transformer,
		isvc.Spec.Explainer,
	} {
		if !reflect.ValueOf(component).IsNil() {
			if err := validateExactlyOneImplementation(component); err != nil {
				return err
			}
			if err := utils.FirstNonNilError([]error{
				component.GetImplementation().Validate(),
				component.GetExtensions().Validate(),
			}); err != nil {
				return err
			}
		}
	}
	return nil
}

// ValidateUpdate implements webhook.Validator so a webhook will be registered for the type
func (isvc *InferenceService) ValidateUpdate(old runtime.Object) error {
	validatorLogger.Info("validate update", "name", isvc.Name)

	return isvc.ValidateCreate()
}

// ValidateDelete implements webhook.Validator so a webhook will be registered for the type
func (isvc *InferenceService) ValidateDelete() error {
	validatorLogger.Info("validate delete", "name", isvc.Name)
	return nil
}

// GetIntReference returns the pointer for the integer input
func GetIntReference(number int) *int {
	num := number
	return &num
}

// Validation of isvc name
func validateInferenceServiceName(isvc *InferenceService) error {
	if !IsvcRegexp.MatchString(isvc.Name) {
		return fmt.Errorf(InvalidISVCNameFormatError, isvc.Name, IsvcNameFmt)
	}
	return nil
}


text:
"""
NAME
    agm_magic.py

DESCRIPTION
    converts MicroMag agm files to magic format

SYNTAX
    agm_magic.py [-h] [command line options]

OPTIONS
    -bak:  this is a IRM backfield curve
    -f FILE, specify input file, required
    -xy the file format is in B, M with both in cgs units
    -spn SPEC, specimen name, default is base of input file name, e.g. SPEC.agm
    -spc NUM, specify number of characters to designate a  specimen, default = 0
    -ncn NCON,: specify naming convention: default is #1 below
    -loc LOCNAME: specify location/study name.
    -ins INST : specify which instrument was used (e.g, SIO-Maud), default is ""
    -u units:  [cgs,SI], default is cgs
    -F MFILE, specify measurements formatted output file, default is SPECNAME.magic
    -Fsp SPECFILE, specify specimens.txt file relating specimen to the sample; default is SPEC_specimens.txt
    -Fsa SAMPFILE, specify samples.txt file relating samples to  site; default is SPEC_samples.txt
    -Fsi SITEFILE, specify sites.txt file relating site to location; default is SPEC_sites.txt
    -Flo LOCFILE, specify locations.txt file; default is SPEC_locations.txt
    -old : infile is in old format

OUTPUT
    MagIC format files: measurements, specimens, sample, site
"""
import sys
from pmagpy import convert_2_magic as convert

def do_help():
    return __doc__

def main():
    kwargs = {}
    if "-h" in sys.argv:
        help(__name__)
        sys.exit()
    if '-bak' in sys.argv:
        kwargs['bak'] = 1
    if '-new' in sys.argv:
        kwargs['fmt'] = 'new'
    if '-xy' in sys.argv:
        kwargs['fmt'] = 'xy'
    if '-WD' in sys.argv:
        ind = sys.argv.index("-WD")
        kwargs['dir_path'] = sys.argv[ind + 1]
    if '-F' in sys.argv:
        ind = sys.argv.index("-F")
        kwargs['meas_outfile'] = sys.argv[ind + 1]
    if '-Fsp' in sys.argv:
        ind = sys.argv.index("-Fsp")
        kwargs['spec_outfile'] = sys.argv[ind + 1]
    if '-Fsa' in sys.argv:
        ind = sys.argv.index("-Fsa")
        kwargs['samp_outfile'] = sys.argv[ind + 1]
    if '-Fsi' in sys.argv:
        ind = sys.argv.index("-Fsi")
        kwargs['site_outfile'] = sys.argv[ind + 1]
    if '-Flo' in sys.argv:
        ind = sys.argv.index("-Flo")
        kwargs['loc_outfile'] = sys.argv[ind + 1]
    if '-f' in sys.argv:
        ind = sys.argv.index("-f")
        kwargs['agm_file'] = sys.argv[ind + 1]
    if "-spc" in sys.argv:
        ind = sys.argv.index("-spc")
        kwargs['specnum'] = int(sys.argv[ind + 1])
    if "-spn" in sys.argv:
        ind = sys.argv.index("-spn")
        kwargs['specimen'] = sys.argv[ind + 1]
    if "-loc" in sys.argv:
        ind = sys.argv.index("-loc")
        kwargs['location'] = sys.argv[ind + 1]
    if "-fsa" in sys.argv:
        ind = sys.argv.index("-fsa")
        kwargs['samp_infile'] = sys.argv[ind + 1]
    if '-syn' in sys.argv:
        syn = 1
        ind = sys.argv.index("-syn")
        kwargs['institution'] = sys.argv[ind + 1]
        kwargs['syntype'] = sys.argv[ind + 2]
        if '-fsy' in sys.argv:
            ind = sys.argv.index("-fsy")
            synfile = sys.argv[ind + 1]
    if "-ins" in sys.argv:
        ind = sys.argv.index("-ins")
        kwargs['ins'] = sys.argv[ind + 1]
    if "-ncn" in sys.argv:
        ind = sys.argv.index("-ncn")
        kwargs['samp_con'] = sys.argv[ind + 1]
    if "-u" in sys.argv:
        ind = sys.argv.index("-u")
        units = sys.argv[ind + 1]
        kwargs['units'] = units
    if "-old" in sys.argv:
        kwargs['fmt'] = 'old'
    else:
        kwargs['fmt'] = 'new'

    convert.agm(**kwargs)

if __name__ == "__main__":
    main()


text:
const appConfig =  {
   "apiurl": "http://someurl"
};

export {
    appConfig as
        default
};


text:
require 'test_helper'

class ConfigFileTest < MiniTest::Unit::TestCase
  def test_should_load_a_config_from_a_file
    with_config_file( { 'common' => {'a' => '1', 'b' => '2' } }, 'app_config' ) do |file, hash|
      configfile = Configy::ConfigFile.new(file, 'development')
      assert_equal hash, configfile.load_file
    end
  end

  def test_should_create_an_instance_of_config_store
    with_config_file( { 'common' => {'a' => '1', 'b' => '2' } }, 'app_config' ) do |file, hash|
      configfile = Configy::ConfigFile.new(file, 'development')
      assert_instance_of Configy::ConfigStore, configfile.config
    end
  end

  def test_should_be_aware_of_a_files_mtime
    configfile = Configy::ConfigFile.new('nonexistent/file', 'development')
    assert_equal Time.at(0), configfile.mtime

    with_config_file( { 'common' => {'a' => '1', 'b' => '2' } }, 'app_config' ) do |file, hash|
      configfile = Configy::ConfigFile.new(file, 'development')
      assert_equal File.mtime(file), configfile.mtime
    end
  end

end


text:
const NSUInteger RPC_HEADER_SIZE = 12;

NS_ASSUME_NONNULL_BEGIN

@implementation SDLRPCPayload

- (nullable instancetype)initWithData:(NSData *)data {
    unsigned long dataLength = data.length;

    if (data == nil || dataLength == 0) {
        SDLLogW(@"RPC Payload data is nil");
        return nil;
    }

    if (dataLength < RPC_HEADER_SIZE) {
        SDLLogW(@"RPC Payload error: not enough data to form RPC header");
        return nil;
    }

    if (self = [self init]) {
        @try {
            // Setup our pointers for data access
            UInt8 *bytePointer = (UInt8 *)data.bytes;
            UInt32 *ui32Pointer = (UInt32 *)data.bytes;

            // Extract the parts
            UInt8 rpcType = (bytePointer[0] & 0xF0) >> 4;

            self.rpcType = rpcType;

            UInt32 functionID = ui32Pointer[0];
            functionID = CFSwapInt32BigToHost(functionID) & 0x0FFFFFFF;
            self.functionID = functionID;

            UInt32 correlationID = ui32Pointer[1];
            correlationID = CFSwapInt32BigToHost(correlationID);
            self.correlationID = correlationID;

            UInt32 jsonDataSize = ui32Pointer[2];
            jsonDataSize = CFSwapInt32BigToHost(jsonDataSize);

            NSData *jsonData = nil;
            NSUInteger offsetOfJSONData = RPC_HEADER_SIZE;
            if (jsonDataSize > 0 && jsonDataSize <= dataLength - RPC_HEADER_SIZE) {
                jsonData = [data subdataWithRange:NSMakeRange(offsetOfJSONData, jsonDataSize)];
            }
            self.jsonData = jsonData;

            NSData *binaryData = nil;
            NSUInteger offsetOfBinaryData = RPC_HEADER_SIZE + jsonDataSize;
            NSUInteger binaryDataSize = data.length - jsonDataSize - RPC_HEADER_SIZE;
            if (binaryDataSize > 0) {
                binaryData = [data subdataWithRange:NSMakeRange(offsetOfBinaryData, binaryDataSize)];
            }
            self.binaryData = binaryData;

        } @catch (NSException *e) {
            SDLLogW(@"SDLRPCPayload error: %@", e);
            return nil;
        }
    }

    return self;
}

- (NSData *)data {
    // Header is:
    // RPC Type - first 4 bits
    // RPC Function ID - next 28 bits
    // Correlation ID - next 32 bits
    // JSON size - next 32 bits
    UInt8 headerBuffer[RPC_HEADER_SIZE];
    *(UInt32 *)&headerBuffer[0] = CFSwapInt32HostToBig(self.functionID);
    *(UInt32 *)&headerBuffer[4] = CFSwapInt32HostToBig(self.correlationID);
    *(UInt32 *)&headerBuffer[8] = CFSwapInt32HostToBig((UInt32)self.jsonData.length);
    UInt8 rpcType = (Byte)((self.rpcType & 0x0F) << 4);
    headerBuffer[0] &= 0x0F;
    headerBuffer[0] |= rpcType;

    // Serialize the header, the json data then the binary data
    NSMutableData *dataOut = [NSMutableData dataWithCapacity:[self size]];
    [dataOut appendBytes:&headerBuffer length:12];
    [dataOut appendData:self.jsonData];
    [dataOut appendData:self.binaryData];

    return dataOut;
}

- (NSUInteger)size {
    NSUInteger headerSize = RPC_HEADER_SIZE;
    NSUInteger jsonDataSize = self.jsonData.length;
    NSUInteger binaryDataSize = self.binaryData.length;

    return (headerSize + jsonDataSize + binaryDataSize);
}

- (NSString *)description {
    NSMutableString *description = [[NSMutableString alloc] init];
    [description appendFormat:@" rpcType:%i, functionID:%i, correlationID:%i, json:%lu bytes, binary:%lu bytes", self.rpcType, (unsigned int)self.functionID, (unsigned int)self.correlationID, (unsigned long)self.jsonData.length, (unsigned long)self.binaryData.length];

    return description;
}

+ (nullable id)rpcPayloadWithData:(NSData *)data {
    return [[SDLRPCPayload alloc] initWithData:data];
}
@end

NS_ASSUME_NONNULL_END


text:
@interface SFSInterlacedImageView () <SFSImageDataProviderDelegate>

@property (nonatomic, strong) SFSImageDataProvider *dataProvider;
@property (nonatomic) BOOL transitioning;
@property (nonatomic, strong) UIImage *nextImage;

@end

@implementation SFSInterlacedImageView

#pragma mark - View Lifecycle

- (instancetype)init
{
    self = [super init];
    if (self)
    {
        [self SFSInterlacedImageViewCommonInit];
    }
    return self;
}

- (instancetype)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];
    if (self)
    {
        [self SFSInterlacedImageViewCommonInit];
    }
    return self;
}

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {
        [self SFSInterlacedImageViewCommonInit];
    }
    return self;
}

- (instancetype)initWithImage:(UIImage *)image
{
    self = [super initWithImage:image];
    if (self)
    {
        [self SFSInterlacedImageViewCommonInit];
    }
    return self;
}

- (instancetype)initWithImage:(UIImage *)image highlightedImage:(UIImage *)highlightedImage
{
    self = [super initWithImage:image highlightedImage:highlightedImage];
    if (self)
    {
        [self SFSInterlacedImageViewCommonInit];
    }
    return self;
}

#pragma mark - Properties

- (void)setImageURL:(NSURL *)imageURL
{
    _imageURL = imageURL;
    self.dataProvider.imageURL = imageURL;
    self.image = nil;

    [self.dataProvider cancel];
    [self.dataProvider start];
}

- (void)setFirstPassToGenerate:(NSUInteger)firstPassToGenerate
{
    _firstPassToGenerate = (firstPassToGenerate > 6) ? 6 : firstPassToGenerate;
    self.dataProvider.firstPassToGenerate = _firstPassToGenerate;
}

- (SFSImageDataProvider *)dataProvider
{
    if (!_dataProvider)
    {
        _dataProvider = [[SFSImageDataProvider alloc] initWithImageURL:self.imageURL];
        _dataProvider.delegate = self;
    }
    return _dataProvider;
}

#pragma mark - Private

- (void)SFSInterlacedImageViewCommonInit
{
    _transitioning = NO;
    _firstPassToGenerate = 1;
    _transitionDuration = 1.0f;
}

- (void)animateTransition
{
    UIImage *transitionImage = self.nextImage;
    self.nextImage = nil;

    if (transitionImage)
    {
        self.transitioning = YES;
        [UIView transitionWithView:self duration:self.transitionDuration options:UIViewAnimationOptionTransitionCrossDissolve animations:^{
            self.image = transitionImage;
        } completion:^(BOOL finished) {
            self.transitioning = NO;
            if (finished && self.nextImage)
            {
                [self animateTransition];
            }
        }];
    }
}

#pragma mark - SFSImageDataProviderDelegate

- (void)imageDataProviderCompletedLoading:(SFSImageDataProvider *)dataProvider
{
    if ([self.delegate respondsToSelector:@selector(interlacedImageViewFinishedLoading:)])
    {
        [self.delegate interlacedImageViewFinishedLoading:self];
    }
}

- (void)imageDataProvider:(SFSImageDataProvider *)dataProvider failedWithError:(NSError *)error
{
    if ([self.delegate respondsToSelector:@selector(interlacedImageView:failedWithError:)])
    {
        [self.delegate interlacedImageView:self failedWithError:error];
    }
}

- (void)imageDataProvider:(SFSImageDataProvider *)dataProvider receivedImage:(UIImage *)image
{
    if (!self.image)
    {
        self.image = image;
        return;
    }

    self.nextImage = image;
    if (!self.transitioning)
    {
        [self animateTransition];
    }
}

@end


text:
<?php
/**
 * DeleteListProfileData.php
 *
 * @package app\components\service\jobs
 * @date: 04.11.2015 15:49
 * @author: Dianov German <es_dianoff@yahoo.com>
 */

namespace app\components\service\jobs;

use app\models\amop\commands\LastActiveDate;
use app\models\amop\models\ListProfiler;
use app\models\amop\models\Profiler;
use GearmanJob;
use shakura\yii2\gearman\JobBase;
use app\models\amop\models\ListProfiler\command\DeleteProfilerList;

/**
 * Worker for delete list profile data
 * class DeleteListProfileData
 * @package app\components\service\jobs
 */

class DeleteListProfileData extends JobBase
{

    /**
     * @param GearmanJob|null $job
     * @return mixed
     */
    public function execute(GearmanJob $job = null) {
        $data = $this->getWorkload($job)->getParams()['data'];

        if (!isset($data['id']) or !isset($data['project_id']) or !isset($data['staff_id']) or !is_int($data['staff_id']) or !is_int($data['id']) or !is_int($data['project_id'])) {
            $job->sendStatus(400, 400);
            return false;
        }

        $id = $data['id'];
        $project_id = $data['project_id'];
        $staff = $data['staff_id'];

        // Óäàëåíèå èç êåøà äàòû ïîñëåäíåãî ïðîñìîòðà ïîëüçîâàòåëåì ïðîôàéëåðà
        LastActiveDate::getModel(LastActiveDate::TYPE_PROFILER)
            ->setData($id)
            ->setUserId($staff)
            ->delete();

        // Óäàëåíèå âñåõ äàííûõ ïî ïðîôàéëåðó
        Profiler::deleteAll(['message_id' => $id]);

        // Óäàëåíèå èç êåøà ñïèñêà ïðîôàéëåðîâ ïî ïðîåêòó
        $command = new DeleteProfilerList();
        $command->setData($project_id)->execute();

        $job->sendStatus(200, 200);

        return true;
    }
}


text:
package org.apache.druid.query.aggregation.bloom;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Function;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import org.apache.druid.common.config.NullHandling;
import org.apache.druid.guice.BloomFilterExtensionModule;
import org.apache.druid.guice.BloomFilterSerializersModule;
import org.apache.druid.jackson.DefaultObjectMapper;
import org.apache.druid.java.util.common.StringUtils;
import org.apache.druid.query.aggregation.Aggregator;
import org.apache.druid.query.aggregation.AggregatorFactory;
import org.apache.druid.query.aggregation.BufferAggregator;
import org.apache.druid.query.aggregation.cardinality.CardinalityAggregatorTest;
import org.apache.druid.query.dimension.DefaultDimensionSpec;
import org.apache.druid.query.dimension.DimensionSpec;
import org.apache.druid.query.dimension.ExtractionDimensionSpec;
import org.apache.druid.query.dimension.RegexFilteredDimensionSpec;
import org.apache.druid.query.extraction.RegexDimExtractionFn;
import org.apache.druid.query.filter.BloomKFilter;
import org.apache.druid.query.monomorphicprocessing.RuntimeShapeInspector;
import org.apache.druid.segment.ColumnValueSelector;
import org.apache.druid.segment.DimensionSelector;
import org.apache.druid.segment.DoubleColumnSelector;
import org.apache.druid.segment.FloatColumnSelector;
import org.apache.druid.segment.LongColumnSelector;
import org.apache.druid.testing.InitializedNullHandlingTest;
import org.junit.Assert;
import org.junit.Test;

import javax.annotation.Nullable;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.IntStream;

public class BloomFilterAggregatorTest extends InitializedNullHandlingTest
{
  private static final String NULLISH = NullHandling.replaceWithDefault() ? "" : null;
  private static final List<String[]> VALUES1 = dimensionValues(
      "a",
      "b",
      "c",
      "a",
      "a",
      NULLISH,
      "b",
      "b",
      "b",
      "b",
      "a",
      "a"
  );
  private static final List<String[]> VALUES2 = dimensionValues(
      "a",
      "b",
      "c",
      "x",
      "a",
      "e",
      "b",
      new String[]{NULLISH, "x"},
      new String[]{"x", NULLISH},
      new String[]{"y", "x"},
      new String[]{"x", "y"},
      new String[]{"x", "y", "a"}
  );
  private static final Double[] DOUBLE_VALUES1 = new Double[]{0.1, 1.5, 18.3, 0.1};
  private static final Float[] FLOAT_VALUES1 = new Float[]{0.4f, 0.8f, 23.2f};
  private static final Long[] LONG_VALUES1 = new Long[]{10241L, 12312355L, 0L, 81L};

  private static final int MAX_NUM_VALUES = 15;

  private static BloomKFilter filter1;
  private static BloomKFilter filter2;

  private static String serializedFilter1;
  private static String serializedFilter2;
  private static String serializedCombinedFilter;
  private static String serializedLongFilter;
  private static String serializedDoubleFilter;
  private static String serializedFloatFilter;

  static {
    try {
      filter1 = new BloomKFilter(MAX_NUM_VALUES);
      filter2 = new BloomKFilter(MAX_NUM_VALUES);
      BloomKFilter combinedValuesFilter = new BloomKFilter(MAX_NUM_VALUES);

      createStringFilter(VALUES1, filter1, combinedValuesFilter);
      createStringFilter(VALUES2, filter2, combinedValuesFilter);

      serializedFilter1 = filterToString(filter1);
      serializedFilter2 = filterToString(filter2);
      serializedCombinedFilter = filterToString(combinedValuesFilter);

      BloomKFilter longFilter = new BloomKFilter(MAX_NUM_VALUES);
      for (long val : LONG_VALUES1) {
        longFilter.addLong(val);
      }
      serializedLongFilter = filterToString(longFilter);

      BloomKFilter floatFilter = new BloomKFilter(MAX_NUM_VALUES);
      for (float val : FLOAT_VALUES1) {
        floatFilter.addFloat(val);
      }
      serializedFloatFilter = filterToString(floatFilter);

      BloomKFilter doubleFilter = new BloomKFilter(MAX_NUM_VALUES);
      for (double val : DOUBLE_VALUES1) {
        doubleFilter.addDouble(val);
      }
      serializedDoubleFilter = filterToString(doubleFilter);

    }
    catch (Exception ex) {
      throw new RuntimeException(ex);
    }
  }

  private static void createStringFilter(List<String[]> values, BloomKFilter filter, BloomKFilter combinedValuesFilter)
  {
    for (String[] vals : values) {
      for (String val : vals) {
        if (!NullHandling.replaceWithDefault() && val == null) {
          filter.addBytes(null, 0, 0);
          combinedValuesFilter.addBytes(null, 0, 0);
        } else {
          filter.addString(NullHandling.nullToEmptyIfNeeded(val));
          combinedValuesFilter.addString(NullHandling.nullToEmptyIfNeeded(val));
        }
      }
    }
  }

  private static List<String[]> dimensionValues(Object... values)
  {
    return Lists.transform(
        Lists.newArrayList(values), new Function<Object, String[]>()
        {
          @Nullable
          @Override
          public String[] apply(@Nullable Object input)
          {
            if (input instanceof String[]) {
              return (String[]) input;
            } else {
              return new String[]{(String) input};
            }
          }
        }
    );
  }

  private static void aggregateDimension(List<DimensionSelector> selectorList, Aggregator agg)
  {
    agg.aggregate();

    for (DimensionSelector selector : selectorList) {
      ((CardinalityAggregatorTest.TestDimensionSelector) selector).increment();
    }
  }

  private static void bufferAggregateDimension(
      List<DimensionSelector> selectorList,
      BufferAggregator agg,
      ByteBuffer buf,
      int pos
  )
  {
    agg.aggregate(buf, pos);

    for (DimensionSelector selector : selectorList) {
      ((CardinalityAggregatorTest.TestDimensionSelector) selector).increment();
    }
  }

  private static void aggregateColumn(List<SteppableSelector> selectorList, Aggregator agg)
  {
    agg.aggregate();

    for (SteppableSelector selector : selectorList) {
      selector.increment();
    }
  }

  private static void bufferAggregateColumn(
      List<SteppableSelector> selectorList,
      BufferAggregator agg,
      ByteBuffer buf,
      int pos
  )
  {
    agg.aggregate(buf, pos);

    for (SteppableSelector selector : selectorList) {
      selector.increment();
    }
  }

  static String filterToString(BloomKFilter bloomKFilter) throws IOException
  {
    return StringUtils.encodeBase64String(BloomFilterSerializersModule.bloomKFilterToBytes(bloomKFilter));
  }

  private final DimensionSpec dimSpec = new DefaultDimensionSpec("dim1", "dim1");
  private BloomFilterAggregatorFactory valueAggregatorFactory;

  public BloomFilterAggregatorTest()
  {
    valueAggregatorFactory = new BloomFilterAggregatorFactory(
        "billy",
        dimSpec,
        MAX_NUM_VALUES
    );
  }

  @Test
  public void testAggregateValues() throws IOException
  {
    DimensionSelector dimSelector = new CardinalityAggregatorTest.TestDimensionSelector(VALUES1, null);
    StringBloomFilterAggregator agg = new StringBloomFilterAggregator(dimSelector, MAX_NUM_VALUES, true);

    for (int i = 0; i < VALUES1.size(); ++i) {
      aggregateDimension(Collections.singletonList(dimSelector), agg);
    }

    BloomKFilter bloomKFilter = BloomKFilter.deserialize(
        (ByteBuffer) valueAggregatorFactory.finalizeComputation(agg.get())
    );
    String serialized = filterToString(bloomKFilter);
    Assert.assertEquals(serializedFilter1, serialized);
  }

  @Test
  public void testAggregateLongValues() throws IOException
  {
    TestLongColumnSelector selector = new TestLongColumnSelector(Arrays.asList(LONG_VALUES1));
    LongBloomFilterAggregator agg = new LongBloomFilterAggregator(selector, MAX_NUM_VALUES, true);

    for (Long ignored : LONG_VALUES1) {
      aggregateColumn(Collections.singletonList(selector), agg);
    }

    BloomKFilter bloomKFilter = BloomKFilter.deserialize(
        (ByteBuffer) valueAggregatorFactory.finalizeComputation(agg.get())
    );
    String serialized = filterToString(bloomKFilter);
    Assert.assertEquals(serializedLongFilter, serialized);
  }

  @Test
  public void testAggregateFloatValues() throws IOException
  {
    TestFloatColumnSelector selector = new TestFloatColumnSelector(Arrays.asList(FLOAT_VALUES1));
    FloatBloomFilterAggregator agg = new FloatBloomFilterAggregator(selector, MAX_NUM_VALUES, true);

    for (Float ignored : FLOAT_VALUES1) {
      aggregateColumn(Collections.singletonList(selector), agg);
    }

    BloomKFilter bloomKFilter = BloomKFilter.deserialize(
        (ByteBuffer) valueAggregatorFactory.finalizeComputation(agg.get())
    );
    String serialized = filterToString(bloomKFilter);
    Assert.assertEquals(serializedFloatFilter, serialized);
  }

  @Test
  public void testAggregateDoubleValues() throws IOException
  {
    TestDoubleColumnSelector selector = new TestDoubleColumnSelector(Arrays.asList(DOUBLE_VALUES1));
    DoubleBloomFilterAggregator agg = new DoubleBloomFilterAggregator(selector, MAX_NUM_VALUES, true);

    for (Double ignored : DOUBLE_VALUES1) {
      aggregateColumn(Collections.singletonList(selector), agg);
    }

    BloomKFilter bloomKFilter = BloomKFilter.deserialize(
        (ByteBuffer) valueAggregatorFactory.finalizeComputation(agg.get())
    );
    String serialized = filterToString(bloomKFilter);
    Assert.assertEquals(serializedDoubleFilter, serialized);
  }

  @Test
  public void testBufferAggregateStringValues() throws IOException
  {
    DimensionSelector dimSelector = new CardinalityAggregatorTest.TestDimensionSelector(VALUES2, null);
    StringBloomFilterAggregator agg = new StringBloomFilterAggregator(dimSelector, MAX_NUM_VALUES, true);

    int maxSize = valueAggregatorFactory.getMaxIntermediateSizeWithNulls();
    ByteBuffer buf = ByteBuffer.allocate(maxSize + 64);
    int pos = 10;
    buf.limit(pos + maxSize);

    agg.init(buf, pos);

    for (int i = 0; i < VALUES2.size(); ++i) {
      bufferAggregateDimension(Collections.singletonList(dimSelector), agg, buf, pos);
    }
    BloomKFilter bloomKFilter = BloomKFilter.deserialize(
        (ByteBuffer) valueAggregatorFactory.finalizeComputation(agg.get(buf, pos))
    );
    String serialized = filterToString(bloomKFilter);
    Assert.assertEquals(serializedFilter2, serialized);
  }

  @Test
  public void testBufferAggregateLongValues() throws IOException
  {
    TestLongColumnSelector selector = new TestLongColumnSelector(Arrays.asList(LONG_VALUES1));
    LongBloomFilterAggregator agg = new LongBloomFilterAggregator(selector, MAX_NUM_VALUES, true);

    int maxSize = valueAggregatorFactory.getMaxIntermediateSizeWithNulls();
    ByteBuffer buf = ByteBuffer.allocate(maxSize + 64);
    int pos = 10;
    buf.limit(pos + maxSize);

    agg.init(buf, pos);

    IntStream.range(0, LONG_VALUES1.length)
             .forEach(i -> bufferAggregateColumn(Collections.singletonList(selector), agg, buf, pos));
    BloomKFilter bloomKFilter = BloomKFilter.deserialize(
        (ByteBuffer) valueAggregatorFactory.finalizeComputation(agg.get(buf, pos))
    );
    String serialized = filterToString(bloomKFilter);
    Assert.assertEquals(serializedLongFilter, serialized);
  }

  @Test
  public void testBufferAggregateFloatValues() throws IOException
  {
    TestFloatColumnSelector selector = new TestFloatColumnSelector(Arrays.asList(FLOAT_VALUES1));
    FloatBloomFilterAggregator agg = new FloatBloomFilterAggregator(selector, MAX_NUM_VALUES, true);

    int maxSize = valueAggregatorFactory.getMaxIntermediateSizeWithNulls();
    ByteBuffer buf = ByteBuffer.allocate(maxSize + 64);
    int pos = 10;
    buf.limit(pos + maxSize);

    agg.init(buf, pos);

    IntStream.range(0, FLOAT_VALUES1.length)
             .forEach(i -> bufferAggregateColumn(Collections.singletonList(selector), agg, buf, pos));
    BloomKFilter bloomKFilter = BloomKFilter.deserialize(
        (ByteBuffer) valueAggregatorFactory.finalizeComputation(agg.get(buf, pos))
    );
    String serialized = filterToString(bloomKFilter);
    Assert.assertEquals(serializedFloatFilter, serialized);
  }

  @Test
  public void testBufferAggregateDoubleValues() throws IOException
  {
    TestDoubleColumnSelector selector = new TestDoubleColumnSelector(Arrays.asList(DOUBLE_VALUES1));
    DoubleBloomFilterAggregator agg = new DoubleBloomFilterAggregator(selector, MAX_NUM_VALUES, true);

    int maxSize = valueAggregatorFactory.getMaxIntermediateSizeWithNulls();
    ByteBuffer buf = ByteBuffer.allocate(maxSize + 64);
    int pos = 10;
    buf.limit(pos + maxSize);

    agg.init(buf, pos);

    IntStream.range(0, DOUBLE_VALUES1.length)
             .forEach(i -> bufferAggregateColumn(Collections.singletonList(selector), agg, buf, pos));
    BloomKFilter bloomKFilter = BloomKFilter.deserialize(
        (ByteBuffer) valueAggregatorFactory.finalizeComputation(agg.get(buf, pos))
    );
    String serialized = filterToString(bloomKFilter);
    Assert.assertEquals(serializedDoubleFilter, serialized);
  }

  @Test
  public void testCombineValues() throws IOException
  {
    DimensionSelector dimSelector1 = new CardinalityAggregatorTest.TestDimensionSelector(VALUES1, null);
    DimensionSelector dimSelector2 = new CardinalityAggregatorTest.TestDimensionSelector(VALUES2, null);

    StringBloomFilterAggregator agg1 = new StringBloomFilterAggregator(dimSelector1, MAX_NUM_VALUES, true);
    StringBloomFilterAggregator agg2 = new StringBloomFilterAggregator(dimSelector2, MAX_NUM_VALUES, true);

    for (int i = 0; i < VALUES1.size(); ++i) {
      aggregateDimension(Collections.singletonList(dimSelector1), agg1);
    }
    for (int i = 0; i < VALUES2.size(); ++i) {
      aggregateDimension(Collections.singletonList(dimSelector2), agg2);
    }

    BloomKFilter combined = BloomKFilter.deserialize(
        (ByteBuffer) valueAggregatorFactory.finalizeComputation(
          valueAggregatorFactory.combine(
              agg1.get(),
              agg2.get()
          )
        )
    );

    String serialized = filterToString(combined);
    Assert.assertEquals(serializedCombinedFilter, serialized);
  }

  @Test
  public void testMergeValues() throws IOException
  {
    final TestBloomFilterBufferColumnSelector mergeDim =
        new TestBloomFilterBufferColumnSelector(
            ImmutableList.of(
                ByteBuffer.wrap(BloomFilterSerializersModule.bloomKFilterToBytes(filter1)),
                ByteBuffer.wrap(BloomFilterSerializersModule.bloomKFilterToBytes(filter2))
            )
        );

    BloomFilterMergeAggregator mergeAggregator =
        new BloomFilterMergeAggregator(mergeDim, MAX_NUM_VALUES, true);

    for (int i = 0; i < 2; ++i) {
      aggregateColumn(Collections.singletonList(mergeDim), mergeAggregator);
    }

    BloomKFilter merged = BloomKFilter.deserialize(
        (ByteBuffer) valueAggregatorFactory.getCombiningFactory().finalizeComputation(mergeAggregator.get())
    );
    String serialized = filterToString(merged);
    Assert.assertEquals(serializedCombinedFilter, serialized);
  }

  @Test
  public void testMergeValuesWithBuffersForGroupByV1() throws IOException
  {
    final TestBloomFilterBufferColumnSelector mergeDim =
        new TestBloomFilterBufferColumnSelector(
            ImmutableList.of(
                ByteBuffer.wrap(BloomFilterSerializersModule.bloomKFilterToBytes(filter1)),
                ByteBuffer.wrap(BloomFilterSerializersModule.bloomKFilterToBytes(filter2))
            )
        );

    BloomFilterMergeAggregator mergeAggregator =
        new BloomFilterMergeAggregator(mergeDim, MAX_NUM_VALUES, true);

    for (int i = 0; i < 2; ++i) {
      aggregateColumn(Collections.singletonList(mergeDim), mergeAggregator);
    }

    BloomKFilter merged = BloomKFilter.deserialize(
        (ByteBuffer) valueAggregatorFactory.getCombiningFactory().finalizeComputation(mergeAggregator.get())
    );
    String serialized = filterToString(merged);
    Assert.assertEquals(serializedCombinedFilter, serialized);
  }

  @Test
  public void testBuferMergeValues() throws IOException
  {
    final TestBloomFilterBufferColumnSelector mergeDim =
        new TestBloomFilterBufferColumnSelector(
            ImmutableList.of(
                ByteBuffer.wrap(BloomFilterSerializersModule.bloomKFilterToBytes(filter1)),
                ByteBuffer.wrap(BloomFilterSerializersModule.bloomKFilterToBytes(filter2))
            )
        );

    BloomFilterMergeAggregator mergeAggregator = new BloomFilterMergeAggregator(mergeDim, MAX_NUM_VALUES, false);

    int maxSize = valueAggregatorFactory.getCombiningFactory().getMaxIntermediateSizeWithNulls();
    ByteBuffer buf = ByteBuffer.allocate(maxSize + 64);
    int pos = 10;
    buf.limit(pos + maxSize);

    mergeAggregator.init(buf, pos);

    for (int i = 0; i < 2; ++i) {
      bufferAggregateColumn(Collections.singletonList(mergeDim), mergeAggregator, buf, pos);
    }

    BloomKFilter merged = BloomKFilter.deserialize(
        (ByteBuffer) valueAggregatorFactory.getCombiningFactory().finalizeComputation(mergeAggregator.get(buf, pos))
    );
    String serialized = filterToString(merged);

    Assert.assertEquals(serializedCombinedFilter, serialized);
  }

  @Test
  public void testSerde() throws Exception
  {
    BloomFilterAggregatorFactory factory = new BloomFilterAggregatorFactory(
        "billy",
        new DefaultDimensionSpec("b", "b"),
        MAX_NUM_VALUES
    );
    ObjectMapper objectMapper = new DefaultObjectMapper();
    new BloomFilterExtensionModule().getJacksonModules().forEach(objectMapper::registerModule);
    Assert.assertEquals(
        factory,
        objectMapper.readValue(objectMapper.writeValueAsString(factory), AggregatorFactory.class)
    );

    String fieldNamesOnly = "{"
                            + "\"type\":\"bloom\","
                            + "\"name\":\"billy\","
                            + "\"field\":\"b\","
                            + "\"maxNumEntries\":15"
                            + "}";
    Assert.assertEquals(
        factory,
        objectMapper.readValue(fieldNamesOnly, AggregatorFactory.class)
    );

    BloomFilterAggregatorFactory factory2 = new BloomFilterAggregatorFactory(
        "billy",
        new ExtractionDimensionSpec("b", "b", new RegexDimExtractionFn(".*", false, null)),
        MAX_NUM_VALUES
    );

    Assert.assertEquals(
        factory2,
        objectMapper.readValue(objectMapper.writeValueAsString(factory2), AggregatorFactory.class)
    );

    BloomFilterAggregatorFactory factory3 = new BloomFilterAggregatorFactory(
        "billy",
        new RegexFilteredDimensionSpec(new DefaultDimensionSpec("a", "a"), ".*"),
        MAX_NUM_VALUES
    );
    Assert.assertEquals(
        factory3,
        objectMapper.readValue(objectMapper.writeValueAsString(factory3), AggregatorFactory.class)
    );
  }

  private abstract static class SteppableSelector<T> implements ColumnValueSelector<T>
  {
    List<T> values;
    int pos;

    public SteppableSelector(List<T> values)
    {
      this.values = values;
      this.pos = 0;
    }

    @Nullable
    @Override
    public T getObject()
    {
      return values.get(pos);
    }

    public void increment()
    {
      pos++;
    }

    public void reset()
    {
      pos = 0;
    }

    @Override
    public double getDouble()
    {
      throw new UnsupportedOperationException();
    }

    @Override
    public float getFloat()
    {
      throw new UnsupportedOperationException();
    }

    @Override
    public long getLong()
    {
      throw new UnsupportedOperationException();
    }

    @Override
    public void inspectRuntimeShape(RuntimeShapeInspector inspector)
    {

    }

    @Override
    public Class<T> classOfObject()
    {
      return null;
    }

    @Override
    public boolean isNull()
    {
      return false;
    }
  }

  public static class TestBloomFilterBufferColumnSelector extends SteppableSelector<ByteBuffer>
  {
    public TestBloomFilterBufferColumnSelector(List<ByteBuffer> values)
    {
      super(values);
    }
  }

  public static class TestLongColumnSelector extends SteppableSelector<Long> implements LongColumnSelector
  {
    public TestLongColumnSelector(List<Long> values)
    {
      super(values);
    }

    @Override
    public long getLong()
    {
      return values.get(pos);
    }
  }

  public static class TestFloatColumnSelector extends SteppableSelector<Float> implements FloatColumnSelector
  {
    public TestFloatColumnSelector(List<Float> values)
    {
      super(values);
    }

    @Override
    public float getFloat()
    {
      return values.get(pos);
    }
  }

  public static class TestDoubleColumnSelector extends SteppableSelector<Double> implements DoubleColumnSelector
  {
    public TestDoubleColumnSelector(List<Double> values)
    {
      super(values);
    }

    @Override
    public double getDouble()
    {
      return values.get(pos);
    }
  }
}


text:
<?php

namespace IPG\EventsBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

class IPGEventsBundle extends Bundle
{
}


text:
//*******************************************************************************************//
//                                                                                //
// Download Free Evaluation Version From: https://bytescout.com/download/web-installer       //
//                                                                                //
// Also available as Web API! Get Your Free API Key: https://app.pdf.co/signup               //
//                                                                                //
// Copyright © 2017-2020 ByteScout, Inc. All rights reserved.                                //
// https://www.bytescout.com                                                                 //
// https://pdf.co                                                                            //
//                                                                                //
//*******************************************************************************************//

import java.io.*;
import okhttp3.*;
public class main {
		public static void main(String []args) throws IOException{
				OkHttpClient client = new OkHttpClient().newBuilder()
						.build();
				Request request = new Request.Builder()
						.url("https://api.pdf.co/v1/file/upload/get-presigned-url?name=test.pdf&encrypt=true")
						.method("GET", null)
						.addHeader("x-api-key", "{{x-api-key}}")
						.build();
				Response response = client.newCall(request).execute();
				System.out.println(response.body().string());
		}
}


text:
<?php
namespace Gt\WebEngine\Logic;

use Gt\Config\Config;
use Gt\Cookie\CookieHandler;
use Gt\Database\Database;
use Gt\DomTemplate\HTMLDocument;
use Gt\Http\Header\Headers;
use Gt\Http\ServerInfo;
use Gt\Input\Input;
use Gt\Session\Session;

abstract class PageSetup extends Page {
	/** @var LogicPropertyStore */
	protected $logicProperty;

	public function __construct(
		HTMLDocument $viewModel,
		Config $config,
		ServerInfo $serverInfo,
		Input $input,
		CookieHandler $cookieHandler,
		Session $session,
		Database $database,
		DynamicPath $dynamicPath,
		Headers $headers,
		LogicPropertyStore $logicProperty
	) {
		parent::__construct(
			$viewModel,
			$config,
			$serverInfo,
			$input,
			$cookieHandler,
			$session,
			$database,
			$dynamicPath,
			$headers
		);

		$this->logicProperty = $logicProperty;
	}
}


text:
<?php
namespace App\Model\Table;

use App\Model\Entity\UserLog;
use Cake\ORM\Query;
use Cake\ORM\RulesChecker;
use Cake\ORM\Table;
use Cake\Validation\Validator;

/**
 * UserLogs Model
 *
 * @property \Cake\ORM\Association\BelongsTo $Users
 * @property \Cake\ORM\Association\BelongsTo $UserTypes
 */
class UserLogsTable extends Table
{

    /**
     * Initialize method
     *
     * @param array $config The configuration for the Table.
     * @return void
     */
    public function initialize(array $config)
    {
        $this->table('user_logs');
        $this->displayField('id');
        $this->primaryKey('id');
        $this->addBehavior('Timestamp');
        $this->belongsTo('Users', [
            'foreignKey' => 'user_id'
        ]);
        $this->belongsTo('UserTypes', [
            'foreignKey' => 'user_type_id'
        ]);
    }

    /**
     * Default validation rules.
     *
     * @param \Cake\Validation\Validator $validator Validator instance.
     * @return \Cake\Validation\Validator
     */
    public function validationDefault(Validator $validator)
    {
        $validator
            ->add('id', 'valid', ['rule' => 'uuid'])
            ->allowEmpty('id', 'create');

        return $validator;
    }

    /**
     * Returns a rules checker object that will be used for validating
     * application integrity.
     *
     * @param \Cake\ORM\RulesChecker $rules The rules object to be modified.
     * @return \Cake\ORM\RulesChecker
     */
    public function buildRules(RulesChecker $rules)
    {
        $rules->add($rules->existsIn(['user_id'], 'Users'));
        $rules->add($rules->existsIn(['user_type_id'], 'UserTypes'));
        return $rules;
    }
}


text:
#include <stdlib.h>
#include <stdio.h>
#include <stdarg.h>
#include "files.h"
#include "common.h"

int as3_pass = 0;
int as3_verbosity = 1;

void as3_error(const char*format, ...)
{
    char buf[1024];
    int l;
    va_list arglist;
    if(as3_verbosity<0)
        exit(1);
    va_start(arglist, format);
    vsnprintf(buf, sizeof(buf)-1, format, arglist);
    va_end(arglist);
    fprintf(stderr, "%s:%d:%d: error: %s\n", current_filename, current_line, current_column, buf);
    fprintf(stderr, "%s\n", current_filename_long);
    fflush(stderr);
    exit(1);
}
void as3_warning(const char*format, ...)
{
    char buf[1024];
    int l;
    va_list arglist;
    if(as3_verbosity<1)
        return;
    va_start(arglist, format);
    vsnprintf(buf, sizeof(buf)-1, format, arglist);
    va_end(arglist);
    fprintf(stdout, "%s:%d:%d: warning: %s\n", current_filename, current_line, current_column, buf);
    fflush(stdout);
}
void as3_softwarning(const char*format, ...)
{
    char buf[1024];
    int l;
    va_list arglist;
    if(as3_verbosity<2)
	return;
    va_start(arglist, format);
    vsnprintf(buf, sizeof(buf)-1, format, arglist);
    va_end(arglist);
    fprintf(stderr, "%s:%d:%d: warning: %s\n", current_filename, current_line, current_column, buf);
    fflush(stderr);
}

void internal_error(const char*file, int line, const char*f)
{
    syntaxerror("internal error in %s, %s:%d", f, file, line);
}

int a3_error(char*s)
{
   syntaxerror("%s", s);
   return 0; //make gcc happy
}


text:
using namespace std;

int main(int argc, char* argv[])
{
	int num_args_needed = 11;
	if (argc != num_args_needed)
	{
		// Error on necessary parameters
		cerr << "Invalid number of arguments. Expected " << num_args_needed << " arguments. Received " << argc << " arguments." << endl;
		return -1;
	}

	string run_type = string(argv[1]);
	unsigned int cnnM = atoi(argv[2]);
	unsigned int cnnN = atoi(argv[3]);
	unsigned int numCNNunits = atoi(argv[4]);
	unsigned int interval = atoi(argv[5]);
	string geneName = string(argv[6]);
	string testInputFile = string(argv[7]);
	string order = string(argv[8]);
	string correctOutFile = string(argv[9]);
	string run_param = string(argv[10]);

	CNNGene* gene = CNNGeneFactory::createCNNGene(geneName);

	BWImage testIn, correctOutput;
	testIn.dlmread(testInputFile, " ");
	correctOutput.dlmread(correctOutFile, " ");
	CNNInput* input = gene->getInput(testIn.getImage(), testIn.R(), testIn.C());

	SP_CNN sp_cnn(testIn.R(), testIn.C(),  gene->r(), cnnM, cnnN, numCNNunits);
	SP_CNN::RunData runData;
	if (run_type == "fixed-interval") {
		if (run_param == "slow")
			runData = sp_cnn.fixedIntervalRun(gene, input, interval, order);
		else if (run_param == "fast")
			runData = sp_cnn.fixedIntervalRunFastProp(gene, input, interval, order);
		else if (run_param == "conv")
			runData = sp_cnn.fixedIntervalRunConvOpt(gene, input, interval, order);
		else {
			cerr << "Invalid Run-Parameter" << endl;
			return 0;
		}
	} else if (run_type == "early-finish") {
		if (run_param == "slow")
			runData = sp_cnn.earlyFinishIntervalRun(gene, input, interval, order);
		else if (run_param == "fast")
			runData = sp_cnn.earlyFinishIntervalRunFastProp(gene, input, interval, order);
		else if (run_param == "conv")
			runData = sp_cnn.earlyFinishIntervalRunConvOpt(gene, input, interval, order);
		else {
			cerr << "Invalid Run-Parameter" << endl;
			return 0;
		}
	} else {
		cout << "ERROR" << endl;
		delete gene;
		delete input;
		return 0;
	}

	BWImage sp_cnnOut(testIn.R(), testIn.C());
	sp_cnn.copyOutput(sp_cnnOut.getImage());

	cout << geneName << "(" << testInputFile << "," << numCNNunits << "," << interval << ")";
	cout << ": (" << runData.totalConvTime << "," << runData.virtualConvTime;
	unsigned int numPixelsDiff = correctOutput.numPixelsDiff(&sp_cnnOut);
	double percentDiff = ((double)numPixelsDiff) / ((double)(testIn.R() * testIn.C()));
	cout << "," << numPixelsDiff << "," << percentDiff << ")" << endl;

	if (run_type == "early-finish") {
		cout << "CNN_P conv. Times - " << geneName << "(" << testInputFile << "," << numCNNunits << "," << interval << ")";
		cout << ": (";
		cout << runData.cnnP_convTime[0];
		for (unsigned int i = 1; i < runData.cnnP_convTime.size(); i++) {
			cout << "," << runData.cnnP_convTime[i];
		}
		cout << ")" << endl;
		cout << "Partition conv. Times - " << geneName << "(" << testInputFile << "," << numCNNunits << "," << interval << ")";
		cout << ": (";
		cout << runData.partition_convTime[0];
		for (unsigned int i = 1; i < runData.partition_convTime.size(); i++) {
			cout << "," << runData.partition_convTime[i];
		}
		cout << ")" << endl;
		cout << "Virtual conv. Times - " << geneName << "(" << testInputFile << "," << numCNNunits << "," << interval << ")";
		cout << ": (";
    unsigned int totalTime = runData.virtualConvTime_perIter[0];
		cout << runData.virtualConvTime_perIter[0] << ",";
		for (unsigned int i = 1; i < runData.virtualConvTime_perIter.size(); i++) {
			cout << "," << runData.virtualConvTime_perIter[i];
      totalTime += runData.virtualConvTime_perIter[i];
		}
		cout << totalTime << ")" << endl;
	}

  if (numPixelsDiff > 0)
  	sp_cnnOut.dlmwrite("incorrect_" + testInputFile, " ");

	delete gene;
	delete input;
	return 0;
}


text:
define([
  'dojo/_base/declare', 'dijit/_WidgetBase', 'dojo/on',
  'dojo/dom-class',
  'dojo/text!./templates/SeqComparison.html', './AppBase', 'dojo/dom-construct', 'dijit/registry',
  'dojo/_base/Deferred', 'dojo/aspect', 'dojo/_base/lang', 'dojo/domReady!', 'dijit/form/NumberTextBox',
  'dojo/query', 'dojo/dom', 'dijit/popup', 'dijit/Tooltip', 'dijit/Dialog', 'dijit/TooltipDialog',
  'dojo/NodeList-traverse', '../../WorkspaceManager', 'dojo/store/Memory', 'dojox/widget/Standby', 'dojo/when'
], function (
  declare, WidgetBase, on,
  domClass,
  Template, AppBase, domConstruct, registry,
  Deferred, aspect, lang, domReady, NumberTextBox,
  query, dom, popup, Tooltip, Dialog, TooltipDialog,
  children, WorkspaceManager, Memory, Standby, when
) {
  return declare([AppBase], {
    baseClass: 'App Assembly',
    templateString: Template,
    applicationName: 'GenomeComparison',
    requireAuth: true,
    applicationLabel: 'Proteome Comparison',
    applicationDescription: 'The Proteome Comparison Service performs protein sequence-based genome comparison using bidirectional BLASTP. This service allows users to select genomes and compare them to reference genome.',
    applicationHelp: 'user_guides/services/proteome_comparison_service.html',
    tutorialLink: 'tutorial/proteome_comparison/proteome_comparison.html',
    pageTitle: 'Proteome Comparison',
    defaultPath: '',
    startingRows: 9,
    maxGenomes: 9,

    constructor: function () {
      this._selfSet = true;
      this.addedGenomes = 0;
      this.genomeToAttachPt = ['comp_genome_id'];
      this.fastaToAttachPt = ['user_genomes_fasta'];
      this.featureGroupToAttachPt = ['user_genomes_featuregroup'];
      this.genomeGroupToAttachPt = ['user_genomes_genomegroup'];
      this.userGenomeList = [];
      this.numref = 0;
    },

    startup: function () {
      var _self = this;
      if (this._started) {
        return;
      }
      if (this.requireAuth && (window.App.authorizationToken === null || window.App.authorizationToken === undefined)) {
        return;
      }
      this.inherited(arguments);

      _self.defaultPath = WorkspaceManager.getDefaultFolder() || _self.activeWorkspacePath;
      _self.output_path.set('value', _self.defaultPath);

      this.numref = 0;
      this.emptyTable(this.genomeTable, this.startingRows);
      this.numgenomes.startup();
      this.advrow.turnedOn = (this.advrow.style.display != 'none');
      on(this.advanced, 'click', lang.hitch(this, function () {
        this.advrow.turnedOn = (this.advrow.style.display != 'none');
        if (!this.advrow.turnedOn) {
          this.advrow.turnedOn = true;
          this.advrow.style.display = 'block';
          this.advicon.className = 'fa icon-caret-left fa-1';
        }
        else {
          this.advrow.turnedOn = false;
          this.advrow.style.display = 'none';
          this.advicon.className = 'fa icon-caret-down fa-1';
        }
      }));
      this._started = true;
    },

    emptyTable: function (target, rowLimit) {
      for (var i = 0; i < rowLimit; i++) {
        var tr = target.insertRow(0);// domConstr.create("tr",{},this.genomeTableBody);
        domConstruct.create('td', { innerHTML: "

" }, tr);
        domConstruct.create('td', { innerHTML: "

" }, tr);
        domConstruct.create('td', { innerHTML: "

" }, tr);
      }
    },

    checkDuplicate: function (cur_value, attachType) {
      var success = 1;
      var genomeIds = [];
      var genomeList = query('.genomedata');
      genomeList.forEach(function (item) {
        genomeIds.push(item.genomeRecord[attachType]);
      });
      if (genomeIds.length > 0 && genomeIds.indexOf(cur_value) > -1) { // found duplicate
        success = 0;
      }
      return success;
    },

    ingestAttachPoints: function (input_pts, target, req) {
      req = typeof req !== 'undefined' ? req : true;
      var success = 1;
      input_pts.forEach(function (attachname) {
        var cur_value = null;
        var incomplete = 0;
        var browser_select = 0;
        if (attachname == 'output_path' || attachname == 'ref_user_genomes_fasta' || attachname == 'ref_user_genomes_featuregroup') {
          cur_value = this[attachname].searchBox.value;// ? "/_uuid/"+this[attachname].searchBox.value : "";
          browser_select = 1;
        }
        else if (attachname == 'user_genomes_fasta') {
          cur_value = this[attachname].searchBox.value;// ? "/_uuid/"+this[attachname].searchBox.value : "";
          var compGenomeList = query('.genomedata');
          var genomeIds = [];

          compGenomeList.forEach(function (item) {
            genomeIds.push(item.genomeRecord.user_genomes_fasta);
          });

          if (genomeIds.length > 0 && genomeIds.indexOf(cur_value) > -1)  // no same genome ids are allowed
          {
            success = 0;
          }
        }
        else if (attachname == 'user_genomes_featuregroup') {
          cur_value = this[attachname].searchBox.value;// ? "/_uuid/"+this[attachname].searchBox.value : "";
          var compGenomeList = query('.genomedata');
          var genomeIds = [];

          compGenomeList.forEach(function (item) {
            genomeIds.push(item.genomeRecord.user_genomes_featuregroup);
          });

          if (genomeIds.length > 0 && genomeIds.indexOf(cur_value) > -1)  // no same genome ids are allowed
          {
            success = 0;
          }
        }
        else if (attachname == 'comp_genome_id') {
          var compGenomeList = query('.genomedata');
          var genomeIds = [];

          compGenomeList.forEach(function (item) {
            genomeIds.push(item.genomeRecord.comp_genome_id);
          });

          cur_value = this[attachname].value;

          // console.log("genomeIds = " + genomeIds + " cur_value = " + cur_value + " index = " +genomeIds.indexOf(cur_value));
          if (genomeIds.length > 0 && genomeIds.indexOf(cur_value) > -1)  // no same genome ids are allowed
          {
            success = 0;
          }
        }
        else if (attachname == 'user_genomes_genomegroup') {
          cur_value = this[attachname].searchBox.value;
          var duplicate = this.checkDuplicate(cur_value, 'user_genomes_genomegroup');
          success *= duplicate;
        }
        else {
          cur_value = this[attachname].value;
        }

        // console.log("cur_value=" + cur_value);

        if (typeof (cur_value) == 'string') {
          target[attachname] = cur_value.trim();
        }
        else {
          target[attachname] = cur_value;
        }
        if (req && (!target[attachname] || incomplete)) {
          if (browser_select) {
            this[attachname].searchBox.validate(); // this should be whats done but it doesn't actually call the new validator
            this[attachname].searchBox._set('state', 'Error');
            this[attachname].focus = true;
          }
          success = 0;
        }
        else {
          this[attachname]._set('state', '');
        }
        if (target[attachname] != '') {
          target[attachname] = target[attachname] || undefined;
        }
        else if (target[attachname] == 'true') {
          target[attachname] = true;
        }
        else if (target[attachname] == 'false') {
          target[attachname] = false;
        }
      }, this);
      return (success);
    },

    onSuggestNameChange: function () {
      if (this.ref_genome_id.get('value') || this.ref_user_genomes_fasta.get('value') || this.ref_user_genomes_featuregroup.get('value')) {
        this.numref = 1;
      } else {
        this.numref = 0;
      }
      // console.log("change genome name, this.numref=", this.numref, "this.ref_genome_id.get('value')=", this.ref_genome_id.get('value'));
    },

    makeGenomeName: function () {
      var name = this.comp_genome_id.get('displayedValue');
      var maxName = 36;
      var display_name = name;
      if (name.length > maxName) {
        display_name = name.substr(0, (maxName / 2) - 2) + '...' + name.substr((name.length - (maxName / 2)) + 2);
      }

      return display_name;
    },

    makeFastaName: function () {
      var name = this.user_genomes_fasta.searchBox.get('displayedValue');
      var maxName = 36;
      var display_name = name;

      if (name.length > maxName) {
        display_name = name.substr(0, (maxName / 2) - 2) + '...' + name.substr((name.length - (maxName / 2)) + 2);
      }

      return display_name;
    },

    makeFeatureGroupName: function () {
      var name = this.user_genomes_featuregroup.searchBox.get('displayedValue');
      var maxName = 36;
      var display_name = name;
      // console.log("this.user_genomes_featuregroup name = " + this.name);

      if (name.length > maxName) {
        display_name = name.substr(0, (maxName / 2) - 2) + '...' + name.substr((name.length - (maxName / 2)) + 2);
      }

      return display_name;
    },

    makeGenomeGroupName: function (newGenomeIds) {
      var name = this[this.genomeGroupToAttachPt].searchBox.get('displayedValue');
      var maxName = 36;
      var display_name = name;
      if (name.length > maxName) {
        display_name = name.substr(0, (maxName / 2) - 2) + '...' + name.substr((name.length - (maxName / 2)) + 2);
      }

      return display_name;
    },

    increaseGenome: function (genomeType, newGenomeIds) {
      if (genomeType == 'genome' || genomeType == 'genome_group') {
        newGenomeIds.forEach(lang.hitch(this, function (id) {
          this.userGenomeList.push(id);
        }));
        this.addedGenomes = this.addedGenomes + newGenomeIds.length;
        this.numgenomes.set('value', Number(this.addedGenomes));
      } else {
        this.addedGenomes = this.addedGenomes + 1;
        this.numgenomes.set('value', Number(this.addedGenomes));
      }
      // console.log("increase this.userGenomeList = " + this.userGenomeList);
    },

    decreaseGenome: function (genomeType, newGenomeIds) {
      if (genomeType == 'genome' || genomeType == 'genome_group') {
        newGenomeIds.forEach(lang.hitch(this, function (id) {
          var idx = this.userGenomeList.indexOf(id);
          if (idx > -1) {
            this.userGenomeList.splice(idx, 1);
          }
        }));
        this.addedGenomes = this.addedGenomes - newGenomeIds.length;
        this.numgenomes.set('value', Number(this.addedGenomes));
      } else {
        this.addedGenomes = this.addedGenomes - 1;
        this.numgenomes.set('value', Number(this.addedGenomes));
      }
      // console.log("decrease this.userGenomeList = " + this.userGenomeList);
    },

    onAddGenome: function () {
      // console.log("Create New Row", domConstruct);
      var lrec = {};
      var chkPassed = this.ingestAttachPoints(this.genomeToAttachPt, lrec);
      // console.log("this.genomeToAttachPt = " + this.genomeToAttachPt);
      // console.log("chkPassed = " + chkPassed + " lrec = " + lrec);
      if (chkPassed && this.addedGenomes < this.maxGenomes) {
        var newGenomeIds = [lrec[this.genomeToAttachPt]];
        var tr = this.genomeTable.insertRow(0);
        var td = domConstruct.create('td', { 'class': 'textcol genomedata', innerHTML: '' }, tr);
        td.genomeRecord = lrec;
        td.innerHTML = "
" + this.makeGenomeName() + '
';
        domConstruct.create('td', { innerHTML: '' }, tr);
        var td2 = domConstruct.create('td', { innerHTML: "" }, tr);
        if (this.addedGenomes < this.startingRows) {
          this.genomeTable.deleteRow(-1);
        }
        var handle = on(td2, 'click', lang.hitch(this, function (evt) {
          // console.log("Delete Row");
          domConstruct.destroy(tr);
          this.decreaseGenome('genome', newGenomeIds);
          if (this.addedGenomes < this.startingRows) {
            var ntr = this.genomeTable.insertRow(-1);
            domConstruct.create('td', { innerHTML: "

" }, ntr);
            domConstruct.create('td', { innerHTML: "

" }, ntr);
            domConstruct.create('td', { innerHTML: "

" }, ntr);
          }
          handle.remove();
        }));
        this.increaseGenome('genome', newGenomeIds);
      }
      // console.log(lrec);
    },

    onAddFasta: function () {
      // console.log("Create New Row", domConstruct);
      var lrec = {};
      var chkPassed = this.ingestAttachPoints(this.fastaToAttachPt, lrec);
      // console.log("this.fastaToAttachPt = " + this.fastaToAttachPt);
      // console.log("chkPassed = " + chkPassed + " lrec = " + lrec);
      if (chkPassed && this.addedGenomes < this.maxGenomes) {
        var newGenomeIds = [lrec[this.fastaToAttachPt]];
        var tr = this.genomeTable.insertRow(0);
        var td = domConstruct.create('td', { 'class': 'textcol genomedata', innerHTML: '' }, tr);
        td.genomeRecord = lrec;
        td.innerHTML = "
" + this.makeFastaName() + '
';
        domConstruct.create('td', { innerHTML: '' }, tr);
        var td2 = domConstruct.create('td', { innerHTML: "" }, tr);
        if (this.addedGenomes < this.startingRows) {
          this.genomeTable.deleteRow(-1);
        }
        var handle = on(td2, 'click', lang.hitch(this, function (evt) {
          // console.log("Delete Row");
          domConstruct.destroy(tr);
          this.decreaseGenome('fasta', newGenomeIds);
          if (this.addedGenomes < this.startingRows) {
            var ntr = this.genomeTable.insertRow(-1);
            domConstruct.create('td', { innerHTML: "

" }, ntr);
            domConstruct.create('td', { innerHTML: "

" }, ntr);
            domConstruct.create('td', { innerHTML: "

" }, ntr);
          }
          handle.remove();
        }));
        this.increaseGenome('fasta', newGenomeIds);
      }
      // console.log(lrec);
    },

    onAddFeatureGroup: function () {
      console.log('Create New Row', domConstruct);
      var lrec = {};
      var chkPassed = this.ingestAttachPoints(this.featureGroupToAttachPt, lrec);
      // console.log("this.featureGroupToAttachPt = " + this.featureGroupToAttachPt);
      // console.log("chkPassed = " + chkPassed + " lrec = " + lrec);
      if (chkPassed && this.addedGenomes < this.maxGenomes) {
        var newGenomeIds = [lrec[this.featureGroupToAttachPt]];
        var tr = this.genomeTable.insertRow(0);
        var td = domConstruct.create('td', { 'class': 'textcol genomedata', innerHTML: '' }, tr);
        td.genomeRecord = lrec;
        td.innerHTML = "
" + this.makeFeatureGroupName() + '
';
        domConstruct.create('td', { innerHTML: '' }, tr);
        var td2 = domConstruct.create('td', { innerHTML: "" }, tr);
        if (this.addedGenomes < this.startingRows) {
          this.genomeTable.deleteRow(-1);
        }
        var handle = on(td2, 'click', lang.hitch(this, function (evt) {
          // console.log("Delete Row");
          domConstruct.destroy(tr);
          this.decreaseGenome('feature_group', newGenomeIds);
          if (this.addedGenomes < this.startingRows) {
            var ntr = this.genomeTable.insertRow(-1);
            domConstruct.create('td', { innerHTML: "

" }, ntr);
            domConstruct.create('td', { innerHTML: "

" }, ntr);
            domConstruct.create('td', { innerHTML: "

" }, ntr);
          }
          handle.remove();
        }));
        this.increaseGenome('feature_group', newGenomeIds);
      }
      // console.log(lrec);
    },

    // implement adding a genome group
    onAddGenomeGroup: function () {
      var lrec = {};
      var chkPassed = this.ingestAttachPoints(this.genomeGroupToAttachPt, lrec);
      // console.log("this.genomeGroupToAttachPt = " + this.genomeGroupToAttachPt);
      // console.log("chkPassed = " + chkPassed + " lrec = " + lrec);
      var path = lrec[this.genomeGroupToAttachPt];
      var newGenomeIds = [];
      when(WorkspaceManager.getObject(path), lang.hitch(this, function (res) {
        if (typeof res.data == 'string') {
          res.data = JSON.parse(res.data);
        }
        if (res && res.data && res.data.id_list) {
          if (res.data.id_list.genome_id) {
            newGenomeIds =  res.data.id_list.genome_id;
          }
        }
        // display a notice if adding new genome group exceeds maximum allowed number
        var count = this.addedGenomes + newGenomeIds.length;
        if (count > this.maxGenomes) {
          var msg = 'Sorry, you can only add up to ' + this.maxGenomes + ' genomes';
          msg += ' and you are trying to select ' + count + '.';
          new Dialog({ title: 'Notice', content: msg }).show();
        }
        // console.log("newGenomeIds = ", newGenomeIds);

        if (chkPassed && this.addedGenomes < this.maxGenomes
          && newGenomeIds.length > 0
          && count < this.maxGenomes)
        {
          var tr = this.genomeTable.insertRow(0);
          var td = domConstruct.create('td', { 'class': 'textcol genomedata', innerHTML: '' }, tr);
          td.genomeRecord = lrec;
          td.innerHTML = "
" + this.makeGenomeGroupName() + '
';
          domConstruct.create('td', { innerHTML: '' }, tr);
          var td2 = domConstruct.create('td', { innerHTML: "" }, tr);
          if (this.addedGenomes < this.startingRows) {
            this.genomeTable.deleteRow(-1);
          }
          var handle = on(td2, 'click', lang.hitch(this, function (evt) {
            // console.log("Delete Row");
            domConstruct.destroy(tr);
            this.decreaseGenome('genome_group', newGenomeIds);
            if (this.addedGenomes < this.startingRows) {
              var ntr = this.genomeTable.insertRow(-1);
              domConstruct.create('td', { innerHTML: "

" }, ntr);
              domConstruct.create('td', { innerHTML: "

" }, ntr);
              domConstruct.create('td', { innerHTML: "

" }, ntr);
            }
            handle.remove();
          }));
          this.increaseGenome('genome_group', newGenomeIds);
        }
      }));

      // console.log(lrec);
    },

    onSubmit: function (evt) {
      var _self = this;

      evt.preventDefault();
      evt.stopPropagation();
      if (this.validate()) {
        var values = this.getValues();
        // console.log("user_genomes ", values["user_genomes"]);
        // console.log("user_feature_groups ", values["user_feature_groups"]);
        // console.log("genome_ids ", values["genome_ids"]);
        // console.log("reference_genome_index ", values["reference_genome_index"]);
        var numUserGenome = 0;

        if (values.user_genomes) {
          numUserGenome += values.user_genomes.length;
        }
        if (values.user_feature_groups) {
          numUserGenome += values.user_feature_groups.length;
        }
        if (values.genome_ids) {
          numUserGenome += values.genome_ids.length;
        }

        if (numUserGenome > 1 && values.reference_genome_index > 0) {
          domClass.add(this.domNode, 'Working');
          domClass.remove(this.domNode, 'Error');
          domClass.remove(this.domNode, 'Submitted');

          if (window.App.noJobSubmission) {
            var dlg = new Dialog({
              title: 'Job Submission Params: ',
              content: '
' + JSON.stringify(values, null, 4) + '
'
            });
            dlg.startup();
            dlg.show();
            return;
          }
          this.submitButton.set('disabled', true);
          window.App.api.service('AppService.start_app', [this.applicationName, values]).then(function (results) {
            // console.log("Job Submission Results: ", results);
            domClass.remove(_self.domNode, 'Working');
            domClass.add(_self.domNode, 'Submitted');
            _self.submitButton.set('disabled', false);
            registry.byClass('p3.widget.WorkspaceFilenameValidationTextBox').forEach(function (obj) {
              obj.reset();
            });
          }, function (err) {
            // console.log("Error:", err)
            domClass.remove(_self.domNode, 'Working');
            domClass.add(_self.domNode, 'Error');
            _self.errorMessage.innerHTML = err;
          });
        } else {
          domClass.add(this.domNode, 'Error');
          // console.log("Form is incomplete");
        }

      } else {
        domClass.add(this.domNode, 'Error');
        // console.log("Form is incomplete");
      }
    },

    getValues: function () {
      var seqcomp_values = {};
      var values = this.inherited(arguments);
      var compGenomeList = query('.genomedata');
      var genomeIds = [];
      var userGenomes = [];
      var featureGroups = [];
      var refType = '';
      var refIndex = 0;

      if (values.ref_genome_id) {
        refType = 'ref_genome_id';
        genomeIds.push(values.ref_genome_id);
      }
      else if (values.ref_user_genomes_fasta) {
        refType = 'ref_user_genomes_fasta';
        userGenomes.push(values.ref_user_genomes_fasta);
      }
      else if (values.ref_user_genomes_featuregroup) {
        refType = 'ref_user_genomes_featuregroup';
        featureGroups.push(values.ref_user_genomes_featuregroup);
      }

      this.userGenomeList.forEach(lang.hitch(this, function (id) {
        genomeIds.push(id);
      }));

      compGenomeList.forEach(function (item) {
        if (item.genomeRecord.user_genomes_fasta) {
          userGenomes.push(item.genomeRecord.user_genomes_fasta);
        }
      });

      compGenomeList.forEach(function (item) {
        if (item.genomeRecord.user_genomes_featuregroup) {
          featureGroups.push(item.genomeRecord.user_genomes_featuregroup);
        }
      });

      // console.log("compGenomeList = " + compGenomeList);
      // console.log("ref genome = " + values["ref_genome_id"]);

      seqcomp_values.genome_ids = genomeIds;
      if (userGenomes.length > 0) {
        seqcomp_values.user_genomes = userGenomes;
      }

      if (featureGroups.length > 0) {
        seqcomp_values.user_feature_groups = featureGroups;
      }

      if (refType == 'ref_genome_id') {
        refIndex = 1;
      }
      else if (refType == 'ref_user_genomes_fasta') {
        refIndex = genomeIds.length + 1;
      }
      else if (refType == 'ref_user_genomes_featuregroup') {
        refIndex = genomeIds.length + userGenomes.length + 1;
      }

      seqcomp_values.reference_genome_index = refIndex;

      if (values.min_seq_cov) {
        seqcomp_values.min_seq_cov = values.min_seq_cov / 100;
      }
      if (values.max_e_val) {
        seqcomp_values.max_e_val = values.max_e_val;
      }
      if (values.min_ident) {
        seqcomp_values.min_ident = values.min_ident / 100;
      }

      seqcomp_values.output_path = values.output_path;
      seqcomp_values.output_file = values.output_file;

      return seqcomp_values;
    }

  });
});


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.postgresqlflexibleserver.fluent.models;

import com.azure.core.annotation.Fluent;
import com.azure.core.management.ProxyResource;
import com.azure.core.management.SystemData;
import com.azure.core.util.logging.ClientLogger;
import com.azure.resourcemanager.postgresqlflexibleserver.models.ConfigurationDataType;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;

/** Represents a Configuration. */
@Fluent
public final class ConfigurationInner extends ProxyResource {
    @JsonIgnore private final ClientLogger logger = new ClientLogger(ConfigurationInner.class);

    /*
     * The properties of a configuration.
     */
    @JsonProperty(value = "properties")
    private ConfigurationProperties innerProperties;

    /*
     * The system metadata relating to this resource.
     */
    @JsonProperty(value = "systemData", access = JsonProperty.Access.WRITE_ONLY)
    private SystemData systemData;

    /**
     * Get the innerProperties property: The properties of a configuration.
     *
     * @return the innerProperties value.
     */
    private ConfigurationProperties innerProperties() {
        return this.innerProperties;
    }

    /**
     * Get the systemData property: The system metadata relating to this resource.
     *
     * @return the systemData value.
     */
    public SystemData systemData() {
        return this.systemData;
    }

    /**
     * Get the value property: Value of the configuration.
     *
     * @return the value value.
     */
    public String value() {
        return this.innerProperties() == null ? null : this.innerProperties().value();
    }

    /**
     * Set the value property: Value of the configuration.
     *
     * @param value the value value to set.
     * @return the ConfigurationInner object itself.
     */
    public ConfigurationInner withValue(String value) {
        if (this.innerProperties() == null) {
            this.innerProperties = new ConfigurationProperties();
        }
        this.innerProperties().withValue(value);
        return this;
    }

    /**
     * Get the description property: Description of the configuration.
     *
     * @return the description value.
     */
    public String description() {
        return this.innerProperties() == null ? null : this.innerProperties().description();
    }

    /**
     * Get the defaultValue property: Default value of the configuration.
     *
     * @return the defaultValue value.
     */
    public String defaultValue() {
        return this.innerProperties() == null ? null : this.innerProperties().defaultValue();
    }

    /**
     * Get the dataType property: Data type of the configuration.
     *
     * @return the dataType value.
     */
    public ConfigurationDataType dataType() {
        return this.innerProperties() == null ? null : this.innerProperties().dataType();
    }

    /**
     * Get the allowedValues property: Allowed values of the configuration.
     *
     * @return the allowedValues value.
     */
    public String allowedValues() {
        return this.innerProperties() == null ? null : this.innerProperties().allowedValues();
    }

    /**
     * Get the source property: Source of the configuration.
     *
     * @return the source value.
     */
    public String source() {
        return this.innerProperties() == null ? null : this.innerProperties().source();
    }

    /**
     * Set the source property: Source of the configuration.
     *
     * @param source the source value to set.
     * @return the ConfigurationInner object itself.
     */
    public ConfigurationInner withSource(String source) {
        if (this.innerProperties() == null) {
            this.innerProperties = new ConfigurationProperties();
        }
        this.innerProperties().withSource(source);
        return this;
    }

    /**
     * Validates the instance.
     *
     * @throws IllegalArgumentException thrown if the instance is not valid.
     */
    public void validate() {
        if (innerProperties() != null) {
            innerProperties().validate();
        }
    }
}