text:
from __future__ import print_function, division, unicode_literals

import os
import yaml

from monty.serialization import loadfn

from pymatgen.core.composition import Composition
from pymatgen.core.periodic_table import Element
from pymatgen.io.vasp.inputs import Incar
from pymatgen.io.vasp.outputs import Vasprun

from mpinterfaces import MPR
import mpinterfaces.utils as utl
from mpinterfaces.mat2d.stability import relax

__author__ = "Michael Ashton"
__copyright__ = "Copyright 2017, Henniggroup"
__maintainer__ = "Michael Ashton"
__email__ = "ashtonmv@gmail.com"
__status__ = "Production"
__date__ = "March 3, 2017"

PACKAGE_PATH = os.path.dirname(__file__)
REFERENCE_MPIDS = loadfn(os.path.join(PACKAGE_PATH, 'reference_mpids.yaml'))
EXPERIMENTAL_OXIDE_DATA = loadfn(os.path.join(PACKAGE_PATH,
                                              'experimental_oxide_data.yaml'))
GAS_CORRECTIONS = loadfn(os.path.join(PACKAGE_PATH, 'gas_corrections.yaml'))

def get_experimental_formation_energies():
    """
    Read in the raw enthalpy and entropy energy data from
    Kubaschewski in experimental_oxide_data.yaml
    and interpret it into actual formation energies. This extra
    step is written out mostly just to make the methodology clear
    and reproducible.

    Returns:

    """
    data = EXPERIMENTAL_OXIDE_DATA
    oxygen_entropy = 38.48  # Entropy in atomic O, in cal/mol.degree
    formation_energies = {}
    for compound in data:
        composition = Composition(compound)
        element = [e for e in composition if e.symbol != 'O'][0]
        delta_H = data[compound]['delta_H']
        delta_S = (data[compound]['S_cmpd']
                   - (data[compound]['S_elt']*composition[element]
                      + oxygen_entropy*composition['O'])) * 298 / 1000
        # Convert kcal/mole to eV/formula unit
        formation_energies[element.symbol] = (delta_H - delta_S) / 22.06035

    return formation_energies

def relax_references(potcar_types, incar_dict, submit=True,
                     force_overwrite=False):
    """
    Set up calculation directories to calibrate
    the ion corrections to match a specified framework of INCAR
    parameters and potcar hashes.

    Args:
        potcar_types (list): list of all elements to calibrate,
            containing specifications for the kind of potential
            desired for each element, e.g. ['Na_pv', 'O']. If
            oxygen is not explicitly included in the list, 'O'
            is used.

        incar_dict (dict): a dictionary of input parameters
            and their values, e.g. {'ISMEAR': -5, 'NSW': 10}

        submit (bool): whether or not to submit each job
            after preparing it.

        force_overwrite (bool): Whether or not to overwrite files
            if an already converged vasprun.xml exists in the
            directory.
    """

    for element in potcar_types:
        if element.split('_')[0] == 'O':
            oxygen_potcar = element
            break
    else:
        oxygen_potcar = 'O'
        potcar_types.append('O')

    for element in potcar_types:
        elt = element.split('_')[0]

        # First, set up a relaxation for the pure element.
        if not os.path.isdir(elt):
            os.mkdir(elt)
        os.chdir(elt)
        s = MPR.get_structure_by_material_id(REFERENCE_MPIDS[elt]['element'])
        s.to('POSCAR', 'POSCAR')
        relax(dim=3, submit=submit, force_overwrite=force_overwrite)
        incar_dict.update({"MAGMOM": utl.get_magmom_string(s)})
        Incar.from_dict(incar_dict).write_file("INCAR")
        utl.write_potcar(types=[element])

        # Then set up a relaxation for its reference oxide.
        if elt not in ['O', 'S', 'F', 'Cl', 'Br', 'I', 'H']:
            if not os.path.isdir('oxide'):
                os.mkdir('oxide')
            os.chdir('oxide')
            s = MPR.get_structure_by_material_id(REFERENCE_MPIDS[elt]['oxide'])
            s.get_sorted_structure().to('POSCAR', 'POSCAR')
            relax(dim=3, submit=submit, force_overwrite=force_overwrite)
            incar_dict.update({"MAGMOM": utl.get_magmom_string(s)})
            Incar.from_dict(incar_dict).write_file("INCAR")
            utl.write_potcar(types=[element, oxygen_potcar])

            os.chdir('../')
        os.chdir('../')

def get_corrections(write_yaml=False):
    """
    Calculates and collects the corrections to be added for
    each reference element directory in the current working
    directory.

    Args:
        write_yaml (bool): whether or not to write the
            corrections to ion_corrections.yaml and the mu0
            values to end_members.yaml.

    Returns:
        dict: elements as keys and their corrections as values,
            in eV per atom, e.g. {'Mo': 0.135, 'S': -0.664}.
    """

    experimental_formation_energies = get_experimental_formation_energies()
    mu0, corrections = {}, {}
    special_cases = ['O', 'S', 'F', 'Cl', 'Br', 'I', 'H']

    elts = [elt for elt in os.listdir(os.getcwd())
            if os.path.isdir(elt) and elt not in special_cases]
    special_elts = [elt for elt in os.listdir(os.getcwd())
                    if os.path.isdir(elt) and elt in special_cases]

    # Add entropic correction for special elements (S * 298K)
    for elt in special_elts:
        os.chdir(elt)
        try:
            vasprun = Vasprun('vasprun.xml')
            composition = vasprun.final_structure.composition
            formula_and_factor = composition.get_integer_formula_and_factor()
            n_formula_units = composition.get_integer_formula_and_factor()[1]
            if '2' in formula_and_factor[0]:
                n_formula_units *= 2

            mu0[elt] = (round(vasprun.final_energy / n_formula_units
                              + GAS_CORRECTIONS['entropy'][elt], 3))
        except Exception as e:
            mu0[elt] = 'Element not finished'
        os.chdir('../')

    # Oxide correction based on L. Wang, T. Maxisch, and G. Ceder,
    # Phys. Rev. B 73, 195107 (2006). This correction is to get
    # solid oxide formation energies right.
    #mu0['O'] += GAS_CORRECTIONS['oxide']

    for elt in elts:
        EF_exp = experimental_formation_energies[elt]
        os.chdir(elt)
        try:
            vasprun = Vasprun('vasprun.xml')
            composition = vasprun.final_structure.composition
            mu0[elt] = round(vasprun.final_energy/composition[Element(elt)], 3)

            # Nitrogen needs an entropic gas phase correction too.
            if elt == 'N':
                mu0[elt] -= GAS_CORRECTIONS['entropy']['N']

        except Exception as _:
            corrections[elt] = 'Element not finished'

        os.chdir('oxide')
        try:
            vasprun = Vasprun('vasprun.xml')
            composition = vasprun.final_structure.composition
            n_formula_units = composition.get_integer_formula_and_factor()[1]

            EF_dft = (vasprun.final_energy
                      - mu0[elt]*composition[Element(elt)]
                      - mu0['O']*composition[Element('O')]) / n_formula_units

            corrections[elt] = round((EF_dft - EF_exp)
                                     / (composition[Element(elt)]/n_formula_units), 3)

        except Exception as e:
            print(e)
            # The relaxation didn't finish.
            if elt in corrections:
                corrections[elt] += ' and oxide not finished'
            else:
                corrections[elt] = 'Oxide not finished'

        os.chdir('../../')
    if write_yaml:
        with open('ion_corrections.yaml', 'w') as yam:
            yam.write('# Difference in formation energy between\n')
            yam.write('# DFT framework and experimental data\n')
            yam.write('# from Materials Thermochemistry\n')
            yam.write('# (Kubaschewski, Alcock)\n')
            yam.write('# All values are given in eV per atom.\n\n')
            yam.write(yaml.dump(corrections, default_flow_style=False))
        with open('chemical_potentials.yaml', 'w') as yam:
            yam.write('# chemical potentials of elemental phases to calculate')
            yam.write('\n')
            yam.write('# formation energies of all compounds. In eV/atom.\n\n')
            yam.write(yaml.dump(mu0, default_flow_style=False))

    return corrections


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>Uses of Class org.apache.poi.hssf.usermodel.HSSFExtendedColor (POI API Documentation)</title>
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

PREV

NEXT

FRAMES

NO FRAMES

All Classes

Uses of Class
org.apache.poi.hssf.usermodel.HSSFExtendedColor

Packages that use HSSFExtendedColor

Package
Description

org.apache.poi.hssf.usermodel

usermodel package maps HSSF low level strutures to familiar workbook/sheet model

Uses of HSSFExtendedColor in org.apache.poi.hssf.usermodel

Methods in org.apache.poi.hssf.usermodel that return HSSFExtendedColor

Modifier and Type
Method and Description

HSSFExtendedColor
HSSFCreationHelper.createExtendedColor()

HSSFExtendedColor
HSSFDataBarFormatting.getColor()

HSSFExtendedColor[]
HSSFColorScaleFormatting.getColors()

Methods in org.apache.poi.hssf.usermodel with parameters of type HSSFExtendedColor

Modifier and Type
Method and Description

HSSFConditionalFormattingRule
HSSFSheetConditionalFormatting.createConditionalFormattingRule(HSSFExtendedColor color)

Create a Databar conditional formatting rule.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

PREV

NEXT

FRAMES

NO FRAMES

All Classes

                Copyright 2016 The Apache Software Foundation or
        its licensors, as applicable.

redpajama_set_name: RedPajamaGithub


text:
package messages

import (
	"github.com/mcilloni/go-openbaton/catalogue"
)

type orMessage struct{}

func (orMessage) From() SenderType {
	return NFVO
}

type OrAllocateResources struct {
	orMessage

	VDUSet []*catalogue.VirtualDeploymentUnit `json:"vduSet,omitempty"`
}

func (OrAllocateResources) DefaultAction() catalogue.Action {
	return catalogue.ActionAllocateResources
}

type OrError struct {
	orMessage

	VNFR    *catalogue.VirtualNetworkFunctionRecord `json:"vnfr,omitempty"`
	Message string                                  `json:"message,omitempty"`
}

func (OrError) DefaultAction() catalogue.Action {
	return catalogue.ActionError
}

type OrGeneric struct {
	orMessage

	VNFR           *catalogue.VirtualNetworkFunctionRecord `json:"vnfr,omitempty"`
	VNFRDependency *catalogue.VNFRecordDependency          `json:"vnfrd,omitempty"`
}

func (OrGeneric) DefaultAction() catalogue.Action {
	return catalogue.NoActionSpecified
}

type OrGrantLifecycleOperation struct {
	orMessage

	GrantAllowed bool                                    `json:"grantAllowed"`
	VDUVIM       map[string]*catalogue.VIMInstance       `json:"vduVim,omitempty"`
	VNFR         *catalogue.VirtualNetworkFunctionRecord `json:"virtualNetworkFunctionRecord,omitempty"`
}

func (OrGrantLifecycleOperation) DefaultAction() catalogue.Action {
	return catalogue.ActionGrantOperation
}

type OrHealVNFRequest struct {
	orMessage

	VNFCInstance *catalogue.VNFCInstance                 `json:"vnfcInstance,omitempty"`
	VNFR         *catalogue.VirtualNetworkFunctionRecord `json:"virtualNetworkFunctionRecord,omitempty"`
	Cause        string                                  `json:"cause,omitempty"`
}

func (OrHealVNFRequest) DefaultAction() catalogue.Action {
	return catalogue.ActionHeal
}

type OrInstantiate struct {
	orMessage

	VNFD            *catalogue.VirtualNetworkFunctionDescriptor `json:"vnfd,omitempty"`
	VNFDFlavour     *catalogue.VNFDeploymentFlavour             `json:"vnfdf,omitempty"`
	VNFInstanceName string                                      `json:"vnfInstanceName,omitempty"`
	VLRs            []*catalogue.VirtualLinkRecord              `json:"vlrs,omitempty"`
	Extension       map[string]string                           `json:"extension,omitempty"`
	VIMInstances    map[string][]*catalogue.VIMInstance         `json:"vimInstances,omitempty"`
	VNFPackage      *catalogue.VNFPackage                       `json:"vnfPackage,omitempty"`
	Keys            []*catalogue.Key                            `json:"keys,omitempty"`
}

func (OrInstantiate) DefaultAction() catalogue.Action {
	return catalogue.ActionInstantiate
}

type OrScaling struct {
	orMessage

	Component    *catalogue.VNFComponent                 `json:"component,omitempty"`
	VNFCInstance *catalogue.VNFCInstance                 `json:"vnfcInstance,omitempty"`
	VIMInstance  *catalogue.VIMInstance                  `json:"vimInstance,omitempty"`
	VNFPackage   *catalogue.VNFPackage                   `json:"vnfPackage,omitempty"`
	VNFR         *catalogue.VirtualNetworkFunctionRecord `json:"virtualNetworkFunctionRecord,omitempty"`
	Dependency   *catalogue.VNFRecordDependency          `json:"dependency,omitempty"`
	Mode         string                                  `json:"mode,omitempty"`
	Extension    map[string]string                       `json:"extension,omitempty"`
}

func (OrScaling) DefaultAction() catalogue.Action {
	return catalogue.ActionScaling
}

type OrStartStop struct {
	orMessage

	VNFR           *catalogue.VirtualNetworkFunctionRecord `json:"virtualNetworkFunctionRecord,omitempty"`
	VNFCInstance   *catalogue.VNFCInstance                 `json:"vnfcInstance,omitempty"`
	VNFRDependency *catalogue.VNFRecordDependency          `json:"vnfrDependency,omitempty"`
}

func (OrStartStop) DefaultAction() catalogue.Action {
	return catalogue.ActionStart
}

type OrUpdate struct {
	orMessage

	Script *catalogue.Script                       `json:"script,omitempty"`
	VNFR   *catalogue.VirtualNetworkFunctionRecord `json:"vnfr,omitempty"`
}

func (OrUpdate) DefaultAction() catalogue.Action {
	return catalogue.ActionUpdate
}


text:
.container{
  #font-style: oblique;
}
footer {
  background-color: #f2dede;
}


text:
module SequelRails
  module Storage
    class Mysql2 < Mysql
    end
  end
end


text:
typedef struct {
  const char* content;
  int dill_handle;
  int status_code;
  int content_length;
} http_response_t;

void http_response_send(http_response_t* response);
void http_response_init(http_response_t* response, int socket);
void http_response_set_status(http_response_t* response, int status_code);
void http_response_set_content(http_response_t* response, const char* content, int content_length);
void http_response_send_file(http_response_t* response, const char* path);

#endif


text:
module HSNTP.Util.UDPClient (UDPClient(..), stdUDPClient,
                       runUDPClient, seconds, sockAddr)
    where

import Control.Exception
import Control.Monad
import Foreign
import Foreign.Ptr
import Network.Socket
import Prelude hiding(catch)

import HSNTP.Util.Misc
import HSNTP.Util.UDP

type Bufi = (Ptr Word8, Int)

data UDPClient a s = UDPClient { putFun :: Bufi -> IO (Int,s),
                                 getFun :: Bufi -> IO a,
                                 valFun :: s -> a -> a,
                                 retries:: Int,
                                 timeout:: Time,
                                 bufSize:: Int,
                                 destSA :: SockAddr
                               }

stdUDPClient :: UDPClient a1 a
stdUDPClient = UDPClient { putFun  = \_ -> return (0,undefined),
                           getFun  = \_ -> return undefined,
                           valFun  = const id,
                           retries = 1,
                           timeout = seconds 10,
                           bufSize = 512,
                           destSA  = undefined
                         }

decRetries :: UDPClient a s -> UDPClient a s
decRetries udpc = udpc { retries = retries udpc - 1 }

runUDPClient :: UDPClient a s -> IO a
runUDPClient udpc = runWithTO' (timeout udpc) (runUDPClient' udpc) `catch` exc udpc
    where
      exc :: UDPClient a s -> SomeException -> IO a
      exc udpc e = if retries udpc > 0
                     then runUDPClient $ decRetries udpc
                     else throw e

runUDPClient' :: UDPClient a s -> IO a
runUDPClient' udpc = allocaArray (bufSize udpc) in1
    where in1 ptr = bracket newSock sClose (in2 ptr)
          in2 ptr s = in3 ptr s
          in3 ptr s = do (l,st)   <- putFun udpc $ (ptr,bufSize udpc)
                         sendBufTo s ptr l (destSA udpc)
                         (rl,rsa) <- recvBufFrom s ptr (bufSize udpc)
                         when (rsa /= destSA udpc) $ fail "reply from wrong SockAddr"
                         val <- (getFun udpc) (ptr,rl)
                         return $ (valFun udpc) st val


text:
<?php

namespace Oro\Bundle\AttachmentBundle\Form\EventSubscriber;

use Symfony\Component\Form\FormError;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Validator\ConstraintViolation;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

use Oro\Bundle\AttachmentBundle\Entity\File;
use Oro\Bundle\AttachmentBundle\Entity\Attachment;
use Oro\Bundle\AttachmentBundle\Validator\ConfigFileValidator;

class FileSubscriber implements EventSubscriberInterface
{
    /** @var ConfigFileValidator */
    protected $validator;

    /**
     * @param ConfigFileValidator $validator
     */
    public function __construct(ConfigFileValidator $validator)
    {
        $this->validator = $validator;
    }

    /**
     * {@inheritdoc}
     */
    public static function getSubscribedEvents()
    {
        return [
            FormEvents::PRE_SET_DATA => 'preSetData',
            FormEvents::POST_SUBMIT  => 'postSubmit'
        ];
    }

    /**
     * Add checkbox to delete attach file and delete owner select
     *
     * @param FormEvent $event
     */
    public function preSetData(FormEvent $event)
    {
        $entity = $event->getData();
        $form   = $event->getForm();

        if (is_object($entity)
            && $entity->getId()
            && $entity->getFilename() !== null
            && $form->getConfig()->getOption(
                'allowDelete'
            )
        ) {
            $form->add(
                'emptyFile',
                'hidden',
                [
                    'required' => false,
                ]
            );
        }
        $form->remove('owner');
    }

    /**
     * Trigger attachment entity update
     *
     * @param FormEvent $event
     */
    public function postSubmit(FormEvent $event)
    {
        /** @var File $entity */
        $entity = $event->getData();
        $form   = $event->getForm();

        if (is_object($entity) && $entity->getFile() !== null) {
            $this->validate($form, $entity);
        }

        if (($form->has('emptyFile') && $form->get('emptyFile')->getData())
            || (is_object($entity) && $entity->getFile() !== null)
        ) {
            // trigger update in entity
            $entity->setUpdatedAt(new \DateTime('now', new \DateTimeZone('UTC')));
        }
    }

    /**
     * Validate attachment field
     *
     * @param FormInterface   $form
     * @param File|Attachment $entity
     */
    protected function validate(FormInterface $form, $entity)
    {
        $fieldName = $form->getName();

        if ($form->getParent()->getConfig()->getOption('parentEntityClass', null)) {
            $dataClass = $form->getParent()->getConfig()->getOption('parentEntityClass', null);
            $fieldName = '';
        } else {
            $dataClass = $form->getParent()
                ? $form->getParent()->getConfig()->getDataClass()
                : $form->getConfig()->getDataClass();
            if (!$dataClass) {
                $dataClass = $form->getParent()->getParent()->getConfig()->getDataClass();
            }
        }

        $violations = $this->validator->validate($entity->getFile(), $dataClass, $fieldName);

        if (!empty($violations)) {
            $fileField = $form->get('file');
            /** @var $violation ConstraintViolation */
            foreach ($violations as $violation) {
                $error = new FormError(
                    $violation->getMessage(),
                    $violation->getMessageTemplate(),
                    $violation->getMessageParameters()
                );
                $fileField->addError($error);
            }
        }
    }
}


text:
// <copyright file="TilePrototype.cs" company="Telerik Academy">All rights reserved.</copyright>
// <author>Team GameFifteen-1</author>
namespace GameFifteen.Models
{
    using GameFifteen.Models.Contracts;

    /// <summary>
    /// Prototype design pattern.
    /// </summary>
    public abstract class TilePrototype : GameMember, IGameMember
    {
        /// <summary>
        /// Clones a tile member wise.
        /// </summary>
        /// <returns>A member wise clone of the tile.</returns>
        public abstract Tile CloneMemberwise();

        /// <summary>
        /// Gets a text representation of the tile.
        /// </summary>
        /// <returns>A text representation of the tile.</returns>
        public abstract override string GetTextRepresentation();
    }
}


text:
import React, { Component } from 'react';
import { LeaderBoard } from './components/LeaderBoard';

class App extends Component {
  render() {
    return (
      <div>
        <LeaderBoard />
      </div>
    );
  }
}

export default App;


text:
package kr.debop4j.timeperiod;

import com.google.common.base.Objects;
import kr.debop4j.core.ValueObjectBase;
import kr.debop4j.timeperiod.tools.TimeSpec;
import kr.debop4j.timeperiod.tools.Times;
import lombok.Getter;
import org.joda.time.DateTime;

/**
 * {@link DateTime} 정보 중에 시간 정보를 뺀 일자 정보만을 가진다.
 *
 * @author 배성혁 sunghyouk.bae@gmail.com
 * @since 13. 5. 12. 오후 2:24
 */
public class Datepart extends ValueObjectBase implements Comparable<Datepart> {
    private static final long serialVersionUID = -2730296141281632596L;

    private static Datepart today() {
        return new Datepart(DateTime.now());
    }

    @Getter
    private DateTime datepart;

    /**
     * Instantiates a new Datepart.
     */
    public Datepart() {
        this.datepart = new DateTime(0).withTimeAtStartOfDay();
    }

    /**
     * Instantiates a new Datepart.
     *
     * @param moment the datetime
     */
    public Datepart(DateTime moment) {
        this.datepart = moment.withTimeAtStartOfDay();
    }

    /**
     * Instantiates a new Datepart.
     *
     * @param year the year
     */
    public Datepart(int year) {
        this(year, 1, 1);
    }

    /**
     * Instantiates a new Datepart.
     *
     * @param year        the year
     * @param monthOfYear the month of year
     */
    public Datepart(int year, int monthOfYear) {
        this(year, monthOfYear, 1);
    }

    /**
     * Instantiates a new Datepart.
     *
     * @param year        the year
     * @param monthOfYear the month of year
     * @param dayOfMonth  the day of month
     */
    public Datepart(int year, int monthOfYear, int dayOfMonth) {
        this.datepart = Times.asDate(year, monthOfYear, dayOfMonth);
    }

    /**
     * Gets year.
     *
     * @return the year
     */
    public int getYear() {
        return datepart.getYear();
    }

    /**
     * Gets month of year.
     *
     * @return the month of year
     */
    public int getMonthOfYear() {
        return datepart.getMonthOfYear();
    }

    /**
     * Gets day of month.
     *
     * @return the day of month
     */
    public int getDayOfMonth() {
        return datepart.getDayOfMonth();
    }

    /**
     * Gets date time.
     *
     * @param time the time
     * @return the date time
     */
    public DateTime getDateTime(Timepart time) {
        return datepart.plus(time.getMillis());
    }

    /**
     * Gets date time.
     *
     * @param hourOfDay      the hour of day
     * @param minuteOfHour   the minute of hour
     * @param secondOfMinute the second of minute
     * @return the date time
     */
    public DateTime getDateTime(int hourOfDay, int minuteOfHour, int secondOfMinute) {
        return getDateTime(hourOfDay, minuteOfHour, secondOfMinute, 0);
    }

    /**
     * Gets date time.
     *
     * @param hourOfDay      the hour of day
     * @param minuteOfHour   the minute of hour
     * @param secondOfMinute the second of minute
     * @param millisOfSecond the millis of second
     * @return the date time
     */
    public DateTime getDateTime(int hourOfDay, int minuteOfHour, int secondOfMinute, int millisOfSecond) {
        return getDateTime(new Timepart(hourOfDay, minuteOfHour, secondOfMinute, millisOfSecond));
    }

    @Override
    public int compareTo(Datepart o) {
        return hashCode() - o.hashCode();
    }

    @Override
    public int hashCode() {
        return (int) (datepart.getMillis() / TimeSpec.MillisPerDay);
    }

    @Override
    protected Objects.ToStringHelper buildStringHelper() {
        return super.buildStringHelper()
                .add("datepart", datepart);
    }
}


text:
package perso;

import interfaces.Sauvegardable;
import io.IO;

public class Caracteristiques implements Sauvegardable {
    public static final String PATH = "caract";
    private final int[] caract;

    public Caracteristiques(int vitalite, int force, int vitesse) {
	caract = new int[] {vitalite, vitalite, force, vitesse};
    }

    public Caracteristiques(int vie, int vitalite, int force, int vitesse) {
	caract = new int[] {vie, vitalite, force, vitesse};
    }

    public Caracteristiques(IO io) {
	this(io.nextShortInt(), io.nextShortInt(), io.nextShortInt(), io.nextShortInt());
    }

    public int getVie() {
	return get(0);
    }

    public int getVitalite() {
	return get(1);
    }

    public int getForce() {
	return get(2);
    }

    public int getVitesse() {
	return get(3);
    }

    public int get(int id) {
	return caract[id];
    }

    @Override
    public IO sauvegarder(IO io) {
	return io.addIntsPositifs(caract);
    }

    @Override
    public String toString() {
	String s = "";
	for(final int i : caract)
	    s += i + ", ";
	return s.substring(0, s.length() - 2);
    }

}


text:
class Gallery < ApplicationRecord
  has_many :pictures, as: :imageable, dependent: :destroy
  accepts_nested_attributes_for :pictures
end


text:
#region Copyright

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

#endregion
using System;
using System.IO;
using System.Web.Mvc;
using System.Web.Routing;
using DotNetNuke.Web.Mvc.Framework.ActionResults;
using Moq;
using NUnit.Framework;

namespace DotNetNuke.Tests.Web.Mvc.Helpers
{
    [TestFixture]
    public class DnnViewResultTests
    {
        [Test]
        public void ExecuteResult_Throws_With_Null_ControllerContext()
        {
            //Arrange
            var result = new DnnViewResult();

            //Act, Assert
            Assert.Throws<ArgumentNullException>(() => result.ExecuteResult(null, new StringWriter()));
        }

        [Test]
        public void ExecuteResult_Throws_With_Null_TextWriter()
        {
            //Arrange
            var result = new DnnViewResult();
            var context = MockHelper.CreateMockControllerContext();

            //Act, Assert
            Assert.Throws<ArgumentNullException>(() => result.ExecuteResult(context, null));
        }

        [Test]
        public void ExecuteResult_Throws_With_Empty_ViewName_And_No_Action()
        {
            //Arrange
            var result = new DnnViewResult();
            var context = MockHelper.CreateMockControllerContext();

            //Act, Assert
            Assert.Throws<InvalidOperationException>(() => result.ExecuteResult(context, new StringWriter()));
        }

        [Test]
        public void ExecuteResult_Calls_ViewEngine_FindView_If_View_Is_Null()
        {
            //Arrange
            var result = new DnnViewResult();

            var routeData = new RouteData();
            routeData.Values["controller"] = "Controller";
            routeData.Values["action"] = "Action";
            routeData.Values["id"] = "Id";
            var context = MockHelper.CreateMockControllerContext(routeData);

            var mockView = new Mock<IView>();
            var mockViewEngine = new Mock<IViewEngine>();
            mockViewEngine.Setup(v => v.FindView(It.IsAny<ControllerContext>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<bool>()))
                .Returns(new ViewEngineResult(mockView.Object, mockViewEngine.Object));
            result.ViewEngineCollection.Clear();
            result.ViewEngineCollection.Add(mockViewEngine.Object);

            //Act
            result.ExecuteResult(context, new StringWriter());

            //Assert
            Assert.AreSame(mockView.Object, result.View);
        }
    }
}


text:
<?php declare(strict_types=1);

namespace Altair\Structure;

use Altair\Structure\Contracts\CollectionInterface;
use Altair\Structure\Contracts\PriorityNodeInterface;
use IteratorAggregate;
use UnderflowException;

/**
 *
 * PriorityQueue.
 *
 * A PriorityQueue is very similar to a Queue. Values are pushed into the queue with an assigned priority, and the
 * value with the highest priority will always be at the front of the queue. Iterating over a PriorityQueue is
 * destructive, equivalent to successive pop operations until the queue is empty. Implemented using a max heap.
 *
 * @link https://medium.com/@rtheunissen/efficient-data-structures-for-php-7-9dda7af674cd#.gl62k1xqr
 */
class PriorityQueue implements IteratorAggregate, CollectionInterface
{
    use Traits\CollectionTrait;
    use Traits\SquaredCapacityTrait;

    /**
     * @var PriorityNodeInterface[]
     */
    protected $heap = [];

    protected $stamp = 0;

    /**
     * Initializes a new priority queue.
     *
     * @param array|null $heap
     * @param int|null $stamp
     */
    public function __construct($heap = [], $stamp = 0)
    {
        $this->heap = $heap ?? [];
        $this->stamp = $stamp ?? 0;
    }

    /**
     * {@inheritDoc}
     */
    public function copy()
    {
        return new PriorityQueue($this->heap, $this->capacity);
    }

    /**
     * {@inheritDoc}
     */
    public function count(): int
    {
        return count($this->heap);
    }

    /**
     * {@inheritDoc}
     */
    public function peek()
    {
        if ($this->isEmpty()) {
            throw new UnderflowException('Queue is empty');
        }

        return $this->heap[0]->value;
    }

    /**
     * Returns and removes the value with the highest priority in the queue.
     *
     * @return mixed
     */
    public function pop()
    {
        if ($this->isEmpty()) {
            throw new UnderflowException('Queue is empty');
        }

        // Last leaf of the heap to become the new root.
        $leaf = array_pop($this->heap);

        if (empty($this->heap)) {
            return $leaf->value;
        }

        // Cache the current root value to return before replacing with next.
        $value = $this->getRoot()->value;

        // Replace the root, then sift down.
        $this->setRoot($leaf);
        $this->siftDown(0);
        $this->adjustCapacity();

        return $value;
    }

    /**
     * Pushes a value into the queue, with a specified priority.
     *
     * @param mixed $value
     * @param int $priority
     */
    public function push($value, int $priority)
    {
        $this->adjustCapacity();

        // Add new leaf, then sift up to maintain heap,
        $this->heap[] = new PriorityNode($value, $priority, $this->stamp++);
        $this->siftUp(count($this->heap) - 1);
    }

    /**
     * {@inheritDoc}
     */
    public function toArray(): array
    {
        $heap = $this->heap;
        $array = [];

        while (!$this->isEmpty()) {
            $array[] = $this->pop();
        }

        $this->heap = $heap;

        return $array;
    }

    /**
     * Get iterator.
     */
    public function getIterator()
    {
        while (!$this->isEmpty()) {
            yield $this->pop();
        }
    }

    /**
     * Left.
     *
     * @param int $index
     *
     * @return int
     */
    protected function left(int $index): int
    {
        return ($index * 2) + 1;
    }

    /**
     * Right.
     *
     * @param int $index
     *
     * @return int
     */
    protected function right(int $index): int
    {
        return ($index * 2) + 2;
    }

    /**
     * Parent.
     *
     * @param int $index
     *
     * @return int
     */
    protected function parent(int $index): int
    {
        return (int)(($index - 1) / 2);
    }

    /**
     * Compare.
     *
     * @param int $a
     * @param int $b
     *
     * @return int
     */
    protected function compare(int $a, int $b)
    {
        $x = $this->heap[$a];
        $y = $this->heap[$b];

        // Compare priority, using insertion stamp as fallback.
        return ($x->priority <=> $y->priority) ?: ($y->stamp <=> $x->stamp);
    }

    /**
     * Swap.
     *
     * @param int $a
     * @param int $b
     */
    protected function swap(int $a, int $b)
    {
        $temp = $this->heap[$a];
        $this->heap[$a] = $this->heap[$b];
        $this->heap[$b] = $temp;
    }

    /**
     * Get Largest Leaf.
     *
     * @param int $parent
     *
     * @return int
     */
    protected function getLargestLeaf(int $parent)
    {
        $left = $this->left($parent);
        $right = $this->right($parent);

        if ($right < count($this->heap) && $this->compare($left, $right) < 0) {
            return $right;
        }

        return $left;
    }

    /**
     * Sift Up.
     *
     * @param int $leaf
     */
    protected function siftUp(int $leaf)
    {
        for (; $leaf > 0; $leaf = $parent) {
            $parent = $this->parent($leaf);

            // Done when parent priority is greater.
            if ($this->compare($leaf, $parent) < 0) {
                break;
            }

            $this->swap($parent, $leaf);
        }
    }

    /**
     * Set Root.
     *
     * @param PriorityNodeInterface $node
     */
    protected function setRoot(PriorityNodeInterface $node)
    {
        $this->heap[0] = $node;
    }

    /**
     * Get Root.
     *
     * @return PriorityNodeInterface
     */
    protected function getRoot(): PriorityNodeInterface
    {
        return $this->heap[0];
    }

    /**
     * Sift Down.
     *
     * @param int $node
     */
    private function siftDown(int $node)
    {
        $last = floor(count($this->heap) / 2);

        for ($parent = $node; $parent < $last; $parent = $leaf) {
            // Determine the largest leaf to potentially swap with the parent.
            $leaf = $this->getLargestLeaf($parent);

            // Done if the parent is not greater than its largest leaf
            if ($this->compare($parent, $leaf) > 0) {
                break;
            }

            $this->swap($parent, $leaf);
        }
    }
}


text:
<?php
require_once 'AbstractTest.php';

class ConcreteWithMyCustomExtensionTest extends AbstractTest
{
    public function testTwo()
    {
    }
}


text:
class CUI8Tracks::Mix
  include CUI8Tracks::Thing

  def user
    return @user if @user
    @user = CUI8Tracks::User.new(@data['user'])
    @user.session = self.session
    @user
  end

  def info
    %w{ name description user tag_list_cache restful_url plays_count liked_by_current_user}.each{ |key|
      value = case key
              when 'user'
                data[key]['slug']
              else
                data[key]
              end
      super(key => value)
    }
    notify "Playing mix #{self.name}", self.description
  end

  def id
    @data['id']
  end

  def each_track(&block)
    got = api.get("/sets/#{set.play_token}/play", {:mix_id => self.id})
    track = CUI8Tracks::Track.new(got['set']['track'])
    @track = track
    track.session = self.session
    track.mix = self
    yield track
    return if @skipped
    loop {
      got = api.get("/sets/#{set.play_token}/next", {:mix_id => self.id})
      break if got['set']['at_end']
      track = CUI8Tracks::Track.new(got['set']['track'])
      @track = track
      track.session = self.session
      yield track
      return if @skipped
    }
  end

  def skip
    @skipped = true
    @track.stop
  end

  %w{ toggle_like like unlike}.each{ |method|
    eval <<-EOS
      def #{method}
        api.post(path('#{method}'))
      end
    EOS
  }
end


text:
module Enjoy::News::Decorators
  module Categories
    extend ActiveSupport::Concern
  end
end


text:
package com.linuxtek.kona.app.sales.service;

import java.io.IOException;

import com.linuxtek.kona.app.sales.entity.KPurchase;
import com.linuxtek.kona.remote.service.KService;

public interface KGooglePlayService<PURCHASE extends KPurchase> extends KService {
    public static final String SERVICE_PATH = "rpc/KGooglePlayService";

	public PURCHASE getSubscription(Long appId, String packageName, String productId,
			String token) throws IOException;

	public PURCHASE getSubscription(Long productId, String token)
			throws IOException;

    public void cancelSubscription(Long appId, String packageName, String productId,
			String token) throws IOException;

	public void cancelSubscription(Long productId, String token)
			throws IOException;

	public PURCHASE getSubscription(Long accountId, Long productId) throws IOException;

	public void cancelSubscription(Long accountId, Long productId) throws IOException;

}


text: Horizontal Glass Panes


text:
import {
  Col,
  Label, ManagedTextInputField as Input,
  Text
} from '@tlon/indigo-react';
import _ from 'lodash';
import { Association, metadataEdit } from '@urbit/api';
import { Form, Formik } from 'formik';
import React from 'react';
import { uxToHex } from '~/logic/lib/util';
import { ColorInput } from '~/views/components/ColorInput';
import { FormError } from '~/views/components/FormError';
import { FormGroupChild } from '~/views/components/FormGroup';
import airlock from '~/logic/api';

interface FormSchema {
  title: string;
  description: string;
  color: string;
}

interface ChannelDetailsProps {
  association: Association;
}

export function ChannelDetails(props: ChannelDetailsProps) {
  const { association } = props;
  const { metadata } = association;
  const initialValues: FormSchema = {
    title: metadata?.title || '',
    description: metadata?.description || '',
    color: metadata?.color || '0x0'
  };

  const onSubmit = async (values: FormSchema, actions) => {
    values.color = uxToHex(values.color);
    const promises = _.compact(_.map(values, (value,k) => {
      return value !== initialValues[k]
        ? airlock.poke(metadataEdit(association, { [k]: value }))
        : null;
    }));
    await Promise.all(promises);
    actions.setStatus({ success: null });
  };

  return (
    <Formik initialValues={initialValues} onSubmit={onSubmit}>
      <Form style={{ display: 'contents' }}>
        <FormGroupChild id="details" />
        <Col mx={4} mb={4} flexShrink={0} gapY={4} maxWidth="512px">
          <Col mb={3}>
            <Text id="details" fontSize={2} fontWeight="bold">
              Channel Details
            </Text>
            <Label gray mt={2}>
              Set the title, description and colour of the channel
            </Label>
          </Col>
          <Input
            id="title"
            label="Title"
            caption="Change the title of this channel"
          />
          <Input
            id="description"
            label="Change description"
            caption="Change the description of this channel"
          />
          <ColorInput
            id="color"
            label="Color"
            caption="Change the color of this channel"
          />
          <FormError message="Failed to update settings" />
        </Col>
      </Form>
    </Formik>
  );
}


text:
from unittest import mock

import pytest

from django.urls import reverse
from model_bakery import baker

from rest_framework import status
from rest_framework.test import APITestCase

from test_utils.emg_fixtures import *  # noqa

@pytest.mark.django_db
class TestSampleAPI(object):

    def test_details(self, client, sample):
        url = reverse("emgapi_v1:samples-detail", args=["ERS01234"])
        response = client.get(url)
        assert response.status_code == status.HTTP_200_OK
        rsp = response.json()

        # Data
        assert len(rsp) == 1
        assert rsp["data"]["type"] == "samples"
        assert rsp["data"]["id"] == "ERS01234"
        _attr = rsp["data"]["attributes"]
        assert(len(_attr) == 17)
        assert _attr["accession"] == "ERS01234"
        assert _attr["biosample"] == "SAMS01234"
        assert _attr["sample-desc"] == "abcdefghijklmnoprstuvwyz"
        assert _attr["analysis-completed"] == "1970-01-01"
        assert _attr["collection-date"] == "1970-01-01"
        assert _attr["geo-loc-name"] == "Geo Location"
        assert not _attr["environment-biome"]
        assert _attr["environment-feature"] == "abcdef"
        assert _attr["environment-material"] == "abcdef"
        assert _attr["sample-name"] == "Example sample name ERS01234"
        assert _attr["sample-alias"] == "ERS01234"
        assert not _attr["host-tax-id"]
        assert _attr["species"] == "homo sapiense"
        assert _attr["latitude"] == 12.3456
        assert _attr["longitude"] == 456.456

    def test_public(self, client, sample, sample_private):
        url = reverse("emgapi_v1:samples-list")
        response = client.get(url)
        assert response.status_code == status.HTTP_200_OK
        rsp = response.json()

        # Meta
        assert rsp["meta"]["pagination"]["page"] == 1
        assert rsp["meta"]["pagination"]["pages"] == 1
        assert rsp["meta"]["pagination"]["count"] == 1

        # Data
        assert len(rsp["data"]) == 1

        d = rsp["data"][0]
        assert d["type"] == "samples"
        assert d["id"] == "ERS01234"
        assert d["attributes"]["accession"] == "ERS01234"

class MockSuccessfulEuropePMCResponse:
    status_code = 200

    @staticmethod
    def json():
        return [
            {
                'annotations': [
                    {
                        'prefix': 'Love is required whenever he's ',
                        'exact': 'sequenced',
                        'postfix': '. It comes just before the assembly.',
                        'type': 'LS',
                    }
                ]
            }
        ]

class MockUnsuccessfulEuropePMCResponse:
    status_code = 404

class TestSampleStudiesPublicationsAnnotationsAPI(APITestCase):

    @mock.patch('emgapi.third_party_metadata.requests.get')
    def test_sample_with_study_with_annotated_pub(self, mock_get):
        biome = baker.make(
            'emgapi.Biome',
            pk=1,
            biome_id=1,
            biome_name='bar',
            lft=0, rgt=1, depth=2,
            lineage='root:ghosts:ectoplasmic',
        )

        sample = baker.make(
            'emgapi.Sample',
            biome=biome,
            pk=1,
            accession='ERS00001',
            primary_accession='SAMS00001',
            is_private=False,
            species='Slimer',
            sample_name='Ectoplasm 1',
            sample_desc='ghostbusters',
            latitude=40.7,
            longitude=74.0,
            last_update='1970-01-01 00:00:00',
            analysis_completed='1970-01-01',
            collection_date='1970-01-01',
            environment_feature='gggbbb',
            environment_material='gggbbb',
            geo_loc_name='New York',
            sample_alias='ERS00001',
        )

        # Sample with no studies
        url = reverse('emgapi_v1:samples-studies-publications-annotations-existence', args=(sample.accession,))
        response = self.client.get(url)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        data = response.json()['data']
        self.assertTrue(data['query_possible'])
        self.assertEqual(len(data['study_has_annotations']), 0)

        # Sample with a publicationless study
        study1 = baker.make(
            'emgapi.Study',
            biome=biome,
            study_id=1,
            secondary_accession='SRP0001',
            centre_name='Columbia U',
            is_private=False,
            public_release_date=None,
            study_name='Ghostbusters',
            study_abstract='Present to rescue the planet recurrently',
            study_status='FINISHED',
            data_origination='HARVESTED',
            submission_account_id='User-123',
            result_directory='2017/05/SRP00001',
            last_update='1970-01-01 00:00:00',
            first_created='1970-01-01 00:00:00',
            project_id='PRJDB0001',
        )
        sample.studies.add(study1)
        response = self.client.get(url)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        data = response.json()['data']
        self.assertTrue(data['query_possible'])
        self.assertEqual(len(data['study_has_annotations']), 1)
        self.assertFalse(data['study_has_annotations'][study1.accession])

        # Sample with a study with a publication with no annotations
        pub1 = baker.make(
            'emgapi.Publication',
            pk=1,
            pubmed_id='001',
            pub_title='Ghostbusters',
            authors='Venkman, P; Spengler, E; Stantz, R'
        )
        study1.publications.add(pub1)
        mock_get.return_value = MockUnsuccessfulEuropePMCResponse()
        response = self.client.get(url)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        data = response.json()['data']
        self.assertTrue(data['query_possible'])
        self.assertEqual(len(data['study_has_annotations']), 1)
        self.assertFalse(data['study_has_annotations'][study1.accession])

        # Sample with a study with a publication with annotations
        mock_get.return_value = MockSuccessfulEuropePMCResponse()
        response = self.client.get(url)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        data = response.json()['data']
        self.assertTrue(data['query_possible'])
        self.assertEqual(len(data['study_has_annotations']), 1)
        self.assertTrue(data['study_has_annotations'][study1.accession])

        # Sample with a study with multiple pubs
        more_pubs = [
            baker.make(
                'emgapi.Publication',
                pk=pk,
                pubmed_id=pk,
                pub_title=f'{pk} ghosts and a funeral',
                authors='Venkman, P; Spengler, E; Stantz, R'
            )
            for pk in range(2, 5)
        ]
        for pub in more_pubs:
            study1.publications.add(pub)
        response = self.client.get(url)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        data = response.json()['data']
        self.assertTrue(data['query_possible'])
        self.assertEqual(len(data['study_has_annotations']), 1)
        self.assertTrue(all(data['study_has_annotations'].values()))

        # Sample with a study with too many publications for EPMC to query at once
        even_more_pubs = [
            baker.make(
                'emgapi.Publication',
                pk=pk,
                pubmed_id=pk,
                pub_title=f'{pk} ghosts and a funeral',
                authors='Venkman, P; Spengler, E; Stantz, R'
            )
            for pk in range(5, 10)
        ]
        for pub in even_more_pubs:
            study1.publications.add(pub)
        response = self.client.get(url)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        data = response.json()['data']
        self.assertFalse(data['query_possible'])

        # Sample with too many studies to query
        more_studies = [
            baker.make(
                'emgapi.Study',
                biome=biome,
                study_id=pk,
                secondary_accession=f'SRP000{pk}',
                centre_name='Columbia U',
                is_private=False,
                public_release_date=None,
                study_name='Ghostbusters',
                study_abstract='Present to rescue the planet recurrently',
                study_status='FINISHED',
                data_origination='HARVESTED',
                submission_account_id='User-123',
                result_directory='2017/05/SRP00001',
                last_update='1970-01-01 00:00:00',
                first_created='1970-01-01 00:00:00',
                project_id='PRJDB0001',
            )
            for pk in range(2, 10)
        ]
        for study in more_studies:
            sample.studies.add(study)
        response = self.client.get(url)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        data = response.json()['data']
        self.assertFalse(data['query_possible'])

class MockSuccessfulCDCHResponse:
    status_code = 200

    @staticmethod
    def json():
        return {
            'curations': [
                {
                    'attributePost': 'fruit',
                    'valuePost': 'banana',
                    "assertionEvidences": [
                        {
                            "label": "author statement"
                        }
                    ],
                    "updatedTimestamp": "2001-01-00T00:00:00.000+0000",
                }
            ],
            "totalAttributes": 1,
            "totalRecords": 1
        }

class MockUnsuccessfulCDCHResponse:
    status_code = 404

class TestSampleContextualDataClearingHouseMetadataAPI(APITestCase):

    @mock.patch('emgapi.third_party_metadata.requests.get')
    def test_sample_with_study_with_annotated_pub(self, mock_get):
        biome = baker.make(
            'emgapi.Biome',
            pk=1,
            biome_id=1,
            biome_name='bar',
            lft=0, rgt=1, depth=2,
            lineage='root:ghosts:ectoplasmic',
        )

        sample = baker.make(
            'emgapi.Sample',
            biome=biome,
            pk=1,
            accession='ERS00001',
            primary_accession='SAMS00001',
            is_private=False,
            species='Slimer',
            sample_name='Ectoplasm 1',
            sample_desc='ghostbusters',
            latitude=40.7,
            longitude=74.0,
            last_update='1970-01-01 00:00:00',
            analysis_completed='1970-01-01',
            collection_date='1970-01-01',
            environment_feature='gggbbb',
            environment_material='gggbbb',
            geo_loc_name='New York',
            sample_alias='ERS00001',
        )

        # Sample with no additional metadata
        mock_get.return_value = MockUnsuccessfulCDCHResponse()
        url = reverse('emgapi_v1:samples-contextual-data-clearing-house-metadata', args=(sample.accession,))
        response = self.client.get(url)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        data = response.json()['data']
        self.assertEqual(data, [])

        # Sample with additional metadata
        mock_get.return_value = MockSuccessfulCDCHResponse()
        response = self.client.get(url)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        data = response.json()['data']
        self.assertEqual(data, [
            {
                'attributePost': 'fruit',
                'valuePost': 'banana',
                "assertionEvidences": [
                    {
                        "label": "author statement"
                    }
                ],
                "updatedTimestamp": "2001-01-00T00:00:00.000+0000",
            }
        ])


text:
package io.fabric8.patch.management;

/**
 * A patch that can be installed, rolled back, simulated or examined.
 */
public class Patch {

    // static patch information - content of patch file
    private PatchData patchData;
    // dynamic patch information - patch tracked by patch management, not necessarly installed
    private ManagedPatch managedPatch;
    // information about installed patch
    private PatchResult result;

    public Patch() {
    }

    public Patch(PatchData patchData, ManagedPatch mp) {
        this.patchData = patchData;
        this.managedPatch = mp;
    }

    public boolean isInstalled() {
        return result != null;
    }

    public PatchData getPatchData() {
        return patchData;
    }

    public void setPatchData(PatchData patchData) {
        this.patchData = patchData;
    }

    public ManagedPatch getManagedPatch() {
        return managedPatch;
    }

    public void setManagedPatch(ManagedPatch managedPatch) {
        this.managedPatch = managedPatch;
    }

    public PatchResult getResult() {
        return result;
    }

    public void setResult(PatchResult result) {
        this.result = result;
    }

}


text:
package com.haulmont.cuba.core;

import com.haulmont.bali.db.QueryRunner;
import com.haulmont.cuba.core.app.events.AttributeChanges;
import com.haulmont.cuba.core.app.events.EntityChangedEvent;
import com.haulmont.cuba.core.entity.contracts.Id;
import com.haulmont.cuba.core.global.AppBeans;
import com.haulmont.cuba.core.global.DataManager;
import com.haulmont.cuba.core.global.Metadata;
import com.haulmont.cuba.testmodel.sales_1.OrderLine;
import com.haulmont.cuba.testmodel.sales_1.Product;
import com.haulmont.cuba.testsupport.TestContainer;
import org.junit.Before;
import org.junit.ClassRule;
import org.junit.Test;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.event.TransactionPhase;
import org.springframework.transaction.event.TransactionalEventListener;

import javax.inject.Inject;
import java.util.Collection;
import java.util.UUID;

import static org.junit.Assert.assertEquals;

public class DataManagerTransactionalUsageTest {

    @Component("test_SaleProcessor")
    public static class SaleProcessor {

        @Inject
        private TransactionalDataManager txDataManager;

        @Transactional
        public Id<OrderLine, UUID> sell(String productName, Integer quantity) {
            Product product = txDataManager.load(Product.class)
                    .query("select p from sales1$Product p where p.name = :name")
                    .parameter("name", productName)
                    .optional()
                    .orElseGet(() -> {
                        Product p = txDataManager.create(Product.class);
                        p.setName(productName);
                        p.setQuantity(100); // initial quantity of a new product
                        return txDataManager.save(p);
                    });

            OrderLine orderLine = txDataManager.create(OrderLine.class);
            orderLine.setProduct(product);
            orderLine.setQuantity(quantity);
            txDataManager.save(orderLine);

            return Id.of(orderLine);
        }

        public Id<OrderLine, UUID> sellSecureWithProgrammaticTx(String productName, Integer quantity) {
            TransactionalDataManager secureDm = txDataManager.secure();
            try (Transaction tx = secureDm.transactions().create()) {
                Product product = secureDm.load(Product.class)
                        .query("select p from sales1$Product p where p.name = :name")
                        .parameter("name", productName)
                        .optional()
                        .orElseGet(() -> {
                            Product p = txDataManager.create(Product.class);
                            p.setName(productName);
                            p.setQuantity(100); // initial quantity of a new product
                            return secureDm.save(p);
                        });

                OrderLine orderLine = txDataManager.create(OrderLine.class);
                orderLine.setProduct(product);
                orderLine.setQuantity(quantity);
                secureDm.save(orderLine);

                tx.commit();

                return Id.of(orderLine);
            }
        }
    }

    @Component("test_OrderLineChangedListener")
    public static class OrderLineChangedListener {

        @Inject
        private TransactionalDataManager txDataManager;

        @TransactionalEventListener(phase = TransactionPhase.BEFORE_COMMIT) // same as simple @EventListener
        protected void orderLineChanged(EntityChangedEvent<OrderLine, UUID> event) {
            AttributeChanges changes = event.getChanges();

            if (event.getType() == EntityChangedEvent.Type.DELETED) {
                Id<Product, UUID> productId = changes.getOldReferenceId("product");
                Integer oldQuantity = changes.getOldValue("quantity");

                Product product = txDataManager.load(productId).one();
                product.setQuantity(product.getQuantity() + oldQuantity);
                txDataManager.save(product);

            } else {
                OrderLine orderLine = txDataManager.load(event.getEntityId()).view("with-product").one();
                Product product = orderLine.getProduct();

                if (event.getType() == EntityChangedEvent.Type.UPDATED) {
                    if (changes.isChanged("product")) {
                        Id<Product, UUID> oldProductId = changes.getOldReferenceId("product");
                        if (oldProductId != null) {
                            Product oldProduct = txDataManager.load(oldProductId).one();
                            oldProduct.setQuantity(oldProduct.getQuantity() + orderLine.getQuantity());
                            txDataManager.save(oldProduct);
                        }

                        product.setQuantity(product.getQuantity() - orderLine.getQuantity());
                        txDataManager.save(product);

                    } else if (changes.isChanged("quantity")) {
                        product.setQuantity(product.getQuantity() - orderLine.getQuantity());
                        txDataManager.save(product);
                    }

                } else if (event.getType() == EntityChangedEvent.Type.CREATED) {
                    product.setQuantity(product.getQuantity() - orderLine.getQuantity());
                    txDataManager.save(product);
                }
            }
        }

        @TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT)
        protected void notifyAboutChanges(EntityChangedEvent<OrderLine, UUID> event) {
            System.out.println("Changed OrderLine: " + event);
        }
    }

    @ClassRule
    public static TestContainer cont = TestContainer.Common.INSTANCE;

    protected DataManager dataManager;
    private Persistence persistence;

    @Before
    public void setUp() throws Exception {
        dataManager = AppBeans.get(DataManager.class);
        persistence = cont.persistence();

        QueryRunner runner = new QueryRunner(persistence.getDataSource());
        runner.update("delete from SALES1_ORDER_LINE");
        runner.update("delete from SALES1_PRODUCT");
    }

    @Test
    public void test() {
        SaleProcessor processor = AppBeans.get("test_SaleProcessor");
        Id<OrderLine, UUID> orderLineId = processor.sell("abc", 10);

        Product product1 = dataManager.load(Product.class)
                .query("select p from sales1$Product p where p.name = :name")
                .parameter("name", "abc")
                .one();
        assertEquals(90, (int) product1.getQuantity());

        // change Product in OrderLIne

        Product product2 = dataManager.create(Product.class);
        product2.setName("def");
        product2.setQuantity(100);
        dataManager.commit(product2);

        OrderLine orderLine = dataManager.load(orderLineId).view("with-product").one();
        orderLine.setProduct(product2);
        dataManager.commit(orderLine);

        Product changedProduct1 = dataManager.load(Id.of(product1)).one();
        assertEquals(100, (int) changedProduct1.getQuantity());

        Product changedProduct2 = dataManager.load(Id.of(product2)).one();
        assertEquals(90, (int) changedProduct2.getQuantity());

        // remove OrderLine

        OrderLine orderLineToRemove = dataManager.load(orderLineId).view("with-product").one();
        dataManager.remove(orderLineToRemove);

        Product product21 = dataManager.load(Id.of(product2)).one();
        assertEquals(100, (int) product21.getQuantity());
    }

    @Test
    public void testSecureWithProgrammaticTx() {
        SaleProcessor processor = AppBeans.get("test_SaleProcessor");
        Id<OrderLine, UUID> orderLineId = processor.sellSecureWithProgrammaticTx("abc", 10);

        Product product1 = dataManager.load(Product.class)
                .query("select p from sales1$Product p where p.name = :name")
                .parameter("name", "abc")
                .one();
        assertEquals(90, (int) product1.getQuantity());

        Product product2 = dataManager.create(Product.class);
        product2.setName("def");
        product2.setQuantity(100);
        dataManager.commit(product2);

        OrderLine orderLine = dataManager.load(orderLineId).view("with-product").one();
        orderLine.setProduct(product2);
        dataManager.commit(orderLine);

        Product changedProduct1 = dataManager.load(Id.of(product1)).one();
        assertEquals(100, (int) changedProduct1.getQuantity());

        Product changedProduct2 = dataManager.load(Id.of(product2)).one();
        assertEquals(90, (int) changedProduct2.getQuantity());
    }
}


text:
All notable changes to this project will be documented in this file.
This project adheres to [Semantic Versioning](http://semver.org/).

## [Unreleased]
### Added
- Ignore PHP 7 scalar type hint errors (error code: "Squiz.Commenting.FunctionComment.ScalarTypeHintMissing").

### Changed
- The "@inheritDoc" tag is now supported (before only "{@inheritdoc}" was supported.

### Fixed
- Files, containing "e_" in the middle of filename were partially ignored.

## [1.0.0] - 2018-12-08
### Added
- Initial release (support PHP_CodeSniffer 1.x and 2.x).


text:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <title>User</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <link rel="stylesheet" href="../css/reset.css" type="text/css" media="screen" />
<link rel="stylesheet" href="../css/main.css" type="text/css" media="screen" />
<link rel="stylesheet" href="../css/github.css" type="text/css" media="screen" />

            Class
            User

                <

                    ActiveRecord::Base

app/models/user.rb

Schema Information

Table name: users

id                     :integer          not null, primary key
email                  :string(255)      default(""), not null
encrypted_password     :string(255)      default(""), not null
reset_password_token   :string(255)
reset_password_sent_at :datetime
remember_created_at    :datetime
sign_in_count          :integer          default(0)
current_sign_in_at     :datetime
last_sign_in_at        :datetime
current_sign_in_ip     :string(255)
last_sign_in_ip        :string(255)
created_at             :datetime         not null
updated_at             :datetime         not null
name                   :string(255)
admin                  :boolean          default(FALSE), not null
projects_limit         :integer          default(10)
skype                  :string(255)      default(""), not null
linkedin               :string(255)      default(""), not null
twitter                :string(255)      default(""), not null
authentication_token   :string(255)
dark_scheme            :boolean          default(FALSE), not null
theme_id               :integer          default(1), not null
bio                    :string(255)
blocked                :boolean          default(FALSE), not null
failed_attempts        :integer          default(0)
locked_at              :datetime
extern_uid             :string(255)
provider               :string(255)
username               :string(255)

Methods

C

                create_from_omniauth

F

                filter,

                find_for_ldap_auth,

                find_or_new_for_omniauth

G

                generate_password,

                gitlab_auth

N

                not_in_project

S

                search

W

                without_projects

Included Modules

              Account

Attributes

              [RW]

            force_random_password

Class Public methods

              create_from_omniauth(auth, ldap = false)

            Link

                Source:
                show

# File app/models/user.rb, line 108
def create_from_omniauth(auth, ldap = false)
  gitlab_auth.create_from_omniauth(auth, ldap)
end

              filter(filter_name)

            Link

                Source:
                show

# File app/models/user.rb, line 86
def filter filter_name
  case filter_name
  when "admins"; self.admins
  when "blocked"; self.blocked
  when "wop"; self.without_projects
  else
    self.active
  end
end

              find_for_ldap_auth(auth, signed_in_resource = nil)

            Link

                Source:
                show

# File app/models/user.rb, line 116
def find_for_ldap_auth(auth, signed_in_resource = nil)
  gitlab_auth.find_for_ldap_auth(auth, signed_in_resource)
end

              find_or_new_for_omniauth(auth)

            Link

                Source:
                show

# File app/models/user.rb, line 112
def find_or_new_for_omniauth(auth)
  gitlab_auth.find_or_new_for_omniauth(auth)
end

              gitlab_auth()

            Link

                Source:
                show

# File app/models/user.rb, line 120
def gitlab_auth
  Gitlab::Auth.new
end

              not_in_project(project)

            Link

                Source:
                show

# File app/models/user.rb, line 96
def not_in_project(project)
  if project.users.present?
    where("id not in (:ids)", ids: project.users.map(&:id) )
  else
    scoped
  end
end

              search(query)

            Link

                Source:
                show

# File app/models/user.rb, line 124
def search query
  where("name LIKE :query or email LIKE :query", query: "%#{query}%")
end

              without_projects()

            Link

                Source:
                show

# File app/models/user.rb, line 104
def without_projects
  where('id NOT IN (SELECT DISTINCT(user_id) FROM users_projects)')
end

Instance Public methods

              generate_password()

            Link

                Source:
                show

# File app/models/user.rb, line 129
def generate_password
  if self.force_random_password
    self.password = self.password_confirmation = Devise.friendly_token.first(8)
  end
end


text:
using System;

class MergeBitsFrom2ValuesAccordingToMask
{
    static void Main()
    {
        uint a = 144;
        uint b = 254;
        uint mask = 15;
        uint result = a ^ ((a ^ b) & mask);
        Console.WriteLine(Convert.ToString(a, 2));
        Console.WriteLine(Convert.ToString(b, 2));
        Console.WriteLine(Convert.ToString(mask, 2));
        Console.WriteLine(Convert.ToString(result, 2) + "  " + result);
    }
}


text:
import discord
import os

description = "Blacklist people that they aren't allowed to use this bot"

perm = 2

def set_list(blacklist):
    if not os.path.isdir("SAVES"):
        os.mkdir("SAVES")
    with open("SAVES/blacklist", "w") as f:
        for m in blacklist:
            f.write(m.id + "\n")

def get_list(server):
    blacklist = []
    if os.path.isfile("SAVES/blacklist"):
        with open("SAVES/blacklist") as f:
            for line in f.readlines():
                memb = discord.utils.get(server.members, id=line.replace("\n", ""))
                blacklist.append(memb)
    return blacklist

def check(member):
    return get_list(member.server).__contains__(member)

async def ex(message, client):
    blacklist = get_list(message.server)
    try:
        victim = message.mentions[0]
    except:
        out = "**BLACKLISTED MEMBERS**\n\n"
        for m in blacklist:
            out += ":white_small_square:   %s\n" % m.name
        await client.send_message(message.channel, embed=discord.Embed(description=out))
        return
    if blacklist.__contains__(victim):
        blacklist.remove(victim)
        await client.send_message(message.channel, embed=discord.Embed(color=discord.Color.orange(), description="%s removed %s from blacklist." % (message.author.mention, victim.mention)))
    else:
        blacklist.append(victim)
        await client.send_message(message.channel, embed=discord.Embed(color=discord.Color.green(), description="%s added %s to blacklist." % (message.author.mention, victim.mention)))
    set_list(blacklist)


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>Canon Chaos</title>

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

    <audio id="cannon-sound" src="assets/sound/bang.wav" type="audio/wav"></audio>
    <audio id="boop-sound" src="assets/sound/boop.wav" type="audio/wav"></audio>

0


text:
package site.hanschen.runwithyou.utils;

import org.apache.commons.codec.binary.Hex;
import org.apache.commons.codec.digest.DigestUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * @author HansChen
 */
public class MD5Utils {

    private MD5Utils() {
        /* cannot be instantiated */
        throw new UnsupportedOperationException("cannot be instantiated");
    }

    /**
     * 获得字符串md5值,注意,不要使用{@link DigestUtils#md5Hex(String)}方法直接返回字符串,会报NoSuchMethodError异常,因为android内置的类没有这个方法
     *
     * @param input 需要加密的字符串
     * @return 32位MD5值
     */
    public static String getMD5(String input) {
        return new String(Hex.encodeHex(DigestUtils.md5(input)));
    }

    /**
     * 获得文件md5值,注意,不要使用{@link DigestUtils#md5Hex(InputStream)}方法直接返回字符串,会报NoSuchMethodError异常,因为android内置的类没有这个方法
     *
     * @param file 需要加密的文件
     * @return 32位MD5值
     */
    public static String getMD5(File file) throws IOException {
        return new String(Hex.encodeHex(DigestUtils.md5(new FileInputStream(file))));
    }
}


text:
function fibbonacciNumbers(inputNumber) {
    if (inputNumber == 1) {
        return [1]
    }

    let fibbonnacciNumbers = [1, 1]
    let currentFibbonacciNumber = 2

    while (currentFibbonacciNumber < inputNumber) {
        let currentNumber = fibbonnacciNumbers[fibbonnacciNumbers.length - 1]
        let previousNumber = fibbonnacciNumbers[fibbonnacciNumbers.length - 2]
        fibbonnacciNumbers.push(currentNumber + previousNumber)
        currentFibbonacciNumber++
    }

    return fibbonnacciNumbers
}

console.log(fibbonacciNumbers(5))


text:
package com.almasb.civ6menu;

import javafx.scene.effect.DropShadow;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.scene.text.Text;

/**
 * @author Almas Baimagambetov (almaslvl@gmail.com)
 */
public class Civ6Title extends Pane {
    private Text text;

    public Civ6Title(String name) {
        String spread = "";
        for (char c : name.toCharArray()) {
            spread += c + " ";
        }

        text = new Text(spread);
        text.setFont(Font.loadFont(Civ6MenuApp.class.getResource("res/Penumbra-HalfSerif-Std_35114.ttf").toExternalForm(), 48));
        text.setFill(Color.WHITE);
        text.setEffect(new DropShadow(30, Color.BLACK));

        getChildren().addAll(text);
    }

    public double getTitleWidth() {
        return text.getLayoutBounds().getWidth();
    }

    public double getTitleHeight() {
        return text.getLayoutBounds().getHeight();
    }
}


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

    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
    <title>Statistics of PROPN in UD_Apurina-UFPA</title>
    <link rel="root" href=""/>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">
    <link rel="stylesheet" type="text/css" href="../../css/jquery-ui-redmond.css"/>
    <link rel="stylesheet" type="text/css" href="../../css/style.css"/>
    <link rel="stylesheet" type="text/css" href="../../css/style-vis.css"/>
    <link rel="stylesheet" type="text/css" href="../../css/hint.css"/>

          home

          edit page
          issue tracker

          <gcse:search></gcse:search>

        This page pertains to UD version 2.

            It appears that you have Javascript disabled.
            Please consider enabling Javascript for this page to see the visualizations.

Treebank Statistics: UD_Apurina-UFPA: POS Tags: PROPN

There are 1 PROPN lemmas (0%), 1 PROPN types (0%) and 1 PROPN tokens (0%).
Out of 15 observed tags, the rank of PROPN is: 14 in number of lemmas, 14 in number of types and 15 in number of tokens.

The 10 most frequent PROPN lemmas: Tapaua

The 10 most frequent PROPN types:  Tapaua

The 10 most frequent ambiguous lemmas:

The 10 most frequent ambiguous types:

Morphology

The form / lemma ratio of PROPN is 1.000000 (the average of all parts of speech is 1.201493).

The 1st highest number of forms (1) was observed with the lemma "Tapaua": Tapaua.

PROPN does not occur with any features.

Relations

PROPN nodes are attached to their parents using 1 different relations: <tt>obl:lmod</tt> (1; 100% instances)

Parents of PROPN nodes belong to 1 different parts of speech: <tt>VERB</tt> (1; 100% instances)

1 (100%) PROPN nodes are leaves.

The highest child degree of a PROPN node is 0.

© 2014–2021
            Universal Dependencies contributors.
            Site powered by Annodoc and brat
.


text: ${include 'custom/footer.html'}


text:
package modtweaker.mods.forestry.handlers;

import com.blamejared.mtlib.helpers.LogHelper;
import forestry.api.recipes.*;
import minetweaker.MineTweakerAPI;
import minetweaker.api.item.*;
import modtweaker.mods.forestry.*;
import modtweaker.mods.forestry.recipes.CentrifugeRecipe;
import net.minecraft.item.ItemStack;
import stanhebben.zenscript.annotations.*;

import java.util.*;

import static com.blamejared.mtlib.helpers.InputHelper.*;
import static com.blamejared.mtlib.helpers.StackHelper.matches;

@ZenClass("mods.forestry.Centrifuge")
public class Centrifuge {

	public static final String name = "Forestry Centrifuge";

	/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

	/**
	 * Adds recipe to Centrifuge
	 *
	 * @param output        recipe product
	 * @param ingredients   required ingredients
	 * @param packagingTime amount of ticks per crafting operation
	 */
	@ZenMethod
	public static void addRecipe(WeightedItemStack[] output, IItemStack ingredients, int packagingTime) {
		Map<ItemStack, Float> products = new HashMap<ItemStack, Float>();
		for(WeightedItemStack product : output) {
			products.put(toStack(product.getStack()), product.getChance());
		}
		MineTweakerAPI.apply(new Add(new CentrifugeRecipe(packagingTime, toStack(ingredients), products)));
	}

	private static class Add extends ForestryListAddition<ICentrifugeRecipe> {

		public Add(ICentrifugeRecipe recipe) {
			super(Centrifuge.name, ForestryHelper.centrifuge);
			recipes.add(recipe);
		}

		@Override
		protected String getRecipeInfo(ICentrifugeRecipe recipe) {
			return LogHelper.getStackDescription(recipe.getInput());
		}
	}

	/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

	/**
	 * Removes a recipe for the Centrifuge
	 *
	 * @param input type of item in input
	 */
	@ZenMethod
	public static void removeRecipe(IIngredient input) {
		List<ICentrifugeRecipe> recipes = new LinkedList<ICentrifugeRecipe>();

		for(ICentrifugeRecipe recipe : RecipeManagers.centrifugeManager.recipes()) {
			if(recipe != null && matches(input, toIItemStack(recipe.getInput()))) {
				recipes.add(recipe);
			}
		}

		if(!recipes.isEmpty()) {
			MineTweakerAPI.apply(new Remove(recipes));
		} else {
			LogHelper.logWarning(String.format("No %s Recipe found for %s. Command ignored!", Centrifuge.name, input.toString()));
		}
	}

	private static class Remove extends ForestryListRemoval<ICentrifugeRecipe, ICentrifugeManager> {

		public Remove(List<ICentrifugeRecipe> recipes) {
			super(Centrifuge.name, RecipeManagers.centrifugeManager, recipes);
		}

		@Override
		protected String getRecipeInfo(ICentrifugeRecipe recipe) {
			return LogHelper.getStackDescription(recipe.getInput());
		}
	}
}


text:
module Azure::BatchAI::Mgmt::V2018_05_01
  module Models
    #
    # pyTorch job settings.
    #
    class PyTorchSettings

      include MsRestAzure

      # @return [String] Python script file path. The python script to execute.
      attr_accessor :python_script_file_path

      # @return [String] Python interpreter path. The path to the Python
      # interpreter.
      attr_accessor :python_interpreter_path

      # @return [String] Command line arguments. Command line arguments that
      # need to be passed to the python script.
      attr_accessor :command_line_args

      # @return [Integer] Process count. Number of processes to launch for the
      # job execution. The default value for this property is equal to
      # nodeCount property
      attr_accessor :process_count

      # @return [String] Communication backend. Type of the communication
      # backend for distributed jobs. Valid values are 'TCP', 'Gloo' or 'MPI'.
      # Not required for non-distributed jobs.
      attr_accessor :communication_backend

      #
      # Mapper for PyTorchSettings class as Ruby Hash.
      # This will be used for serialization/deserialization.
      #
      def self.mapper()
        {
          client_side_validation: true,
          required: false,
          serialized_name: 'PyTorchSettings',
          type: {
            name: 'Composite',
            class_name: 'PyTorchSettings',
            model_properties: {
              python_script_file_path: {
                client_side_validation: true,
                required: true,
                serialized_name: 'pythonScriptFilePath',
                type: {
                  name: 'String'
                }
              },
              python_interpreter_path: {
                client_side_validation: true,
                required: false,
                serialized_name: 'pythonInterpreterPath',
                type: {
                  name: 'String'
                }
              },
              command_line_args: {
                client_side_validation: true,
                required: false,
                serialized_name: 'commandLineArgs',
                type: {
                  name: 'String'
                }
              },
              process_count: {
                client_side_validation: true,
                required: false,
                serialized_name: 'processCount',
                type: {
                  name: 'Number'
                }
              },
              communication_backend: {
                client_side_validation: true,
                required: false,
                serialized_name: 'communicationBackend',
                type: {
                  name: 'String'
                }
              }
            }
          }
        }
      end
    end
  end
end


text:
namespace TCS.Model
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    using System.ComponentModel.DataAnnotations.Schema;
    using System.Data.Entity.Spatial;

    [Table("SensorData")]
    public partial class SensorData
    {
        public SensorData()
        {
            LocationStatus = new HashSet<LocationStatu>();
            LocationStatusHistories = new HashSet<LocationStatusHistory>();
            SensorDataId = Guid.NewGuid().ToString();
        }

        public string SensorDataId { get; set; }

        public DateTime Time { get; set; }

        [Required]
        [StringLength(128)]
        public string SensorId { get; set; }

        public virtual ICollection<LocationStatu> LocationStatus { get; set; }

        public virtual ICollection<LocationStatusHistory> LocationStatusHistories { get; set; }

        public virtual Sensor Sensor { get; set; }
    }
}


text:
package configuration

import (
	log "github.com/Sirupsen/logrus"
	"github.com/spf13/viper"
)

// Configuration keys
// 		- BoltdbName
// 		- Debug
// 		- DefaultEnvironment
// 		- DefaultTask
// 		- EnableAutomerge
// 		- Port
// 		- AppHost
//--------------------------------

func setConfigLocation() {
	viper.SetConfigName(ConfigName)
	for _, i := range ConfigPaths {
		viper.AddConfigPath(i)
	}
}

func LoadSettingsFromFile() {
	viper.SetConfigType(ConfigType)
	setConfigLocation()

	// Set defaults
	viper.SetDefault("Port", Port)
	viper.SetDefault("EnableAutomerge", EnableAutomerge)
	viper.SetDefault("Debug", Debug)
	viper.SetDefault("DefaultEnvironment", DefaultEnvironment)
	viper.SetDefault("DefaultTask", DefaultTask)
	viper.SetDefault("BoltdbName", BoltdbName)

	// Load configuration
	err := viper.ReadInConfig()
	if err != nil {
		log.Warning("Configuration not found, loading defaults")
	}

	// set log level
	if viper.GetBool("Debug") {
		log.SetLevel(log.DebugLevel)
	} else {
		log.SetLevel(log.InfoLevel)
	}

	log.Debugf("Loaded setting values: %v", viper.AllSettings())
	log.Info("Settings loaded")
}


text:
package nayuki.huffmancoding;

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

/**
 * A canonical Huffman code. Immutable. Code length 0 means no code.
 */
/*
 * A canonical Huffman code only describes the code length of each symbol. The codes can be reconstructed from this information. In this implementation, symbols with lower code lengths, breaking ties by lower symbols, are assigned lexicographically lower codes.
 * Example:
 *   Code lengths (canonical code):
 *     Symbol A: 1
 *     Symbol B: 3
 *     Symbol C: 0 (no code)
 *     Symbol D: 2
 *     Symbol E: 3
 *   Huffman codes (generated from canonical code):
 *     Symbol A: 0
 *     Symbol B: 110
 *     Symbol C: None
 *     Symbol D: 10
 *     Symbol E: 111
 */
public final class CanonicalCode {

    private int[] codeLengths;

    // The constructor does not check that the array of code lengths results in a complete Huffman tree, being neither underfilled nor overfilled.
    public CanonicalCode(int[] codeLengths) {
        if (codeLengths == null)
            throw new NullPointerException("Argument is null");
        this.codeLengths = codeLengths.clone();
        for (int x : codeLengths) {
            if (x < 0)
                throw new IllegalArgumentException("Illegal code length");
        }
    }

    // Builds a canonical code from the given code tree.
    public CanonicalCode(CodeTree tree, int symbolLimit) {
        codeLengths = new int[symbolLimit];
        buildCodeLengths(tree.root, 0);
    }

    private void buildCodeLengths(Node node, int depth) {
        if (node instanceof InternalNode) {
            InternalNode internalNode = (InternalNode)node;
            buildCodeLengths(internalNode.leftChild , depth + 1);
            buildCodeLengths(internalNode.rightChild, depth + 1);
        } else if (node instanceof Leaf) {
            int symbol = ((Leaf)node).symbol;
            if (codeLengths[symbol] != 0)
                throw new AssertionError("Symbol has more than one code");  // Because CodeTree has a checked constraint that disallows a symbol in multiple leaves
            if (symbol >= codeLengths.length)
                throw new IllegalArgumentException("Symbol exceeds symbol limit");
            codeLengths[symbol] = depth;
        } else {
            throw new AssertionError("Illegal node type");
        }
    }

    public int getSymbolLimit() {
        return codeLengths.length;
    }

    public int getCodeLength(int symbol) {
        if (symbol < 0 || symbol >= codeLengths.length)
            throw new IllegalArgumentException("Symbol out of range");
        return codeLengths[symbol];
    }

    public CodeTree toCodeTree() {
        List<Node> nodes = new ArrayList<Node>();
        for (int i = max(codeLengths); i >= 1; i--) {  // Descend through positive code lengths
            List<Node> newNodes = new ArrayList<Node>();

            // Add leaves for symbols with code length i
            for (int j = 0; j < codeLengths.length; j++) {
                if (codeLengths[j] == i)
                    newNodes.add(new Leaf(j));
            }

            // Merge nodes from the previous deeper layer
            for (int j = 0; j < nodes.size(); j += 2)
                newNodes.add(new InternalNode(nodes.get(j), nodes.get(j + 1)));

            nodes = newNodes;
            if (nodes.size() % 2 != 0)
                throw new IllegalStateException("This canonical code does not represent a Huffman code tree");
        }

        if (nodes.size() != 2)
            throw new IllegalStateException("This canonical code does not represent a Huffman code tree");
        return new CodeTree(new InternalNode(nodes.get(0), nodes.get(1)), codeLengths.length);
    }

    private static int max(int[] array) {
        int result = array[0];
        for (int x : array)
            result = Math.max(x, result);
        return result;
    }

}


text:
class SpreeBlogit::Parsers::MarkdownParser

  require "nokogiri"
  require "spree_blogit/renderers"

  # A String containing the content to be parsed
  attr_reader :content

  def initialize(content)
    @content = content
  end

  # The parsed content
  #
  # Returns an HTML safe String
  def parsed
    ensure_pygments_is_installed if SpreeBlogit::configuration.highlight_code_syntax
    markdown.render(content).html_safe
  end

  private

  # The Redcarpet renderer to use
  def renderer
    if SpreeBlogit::configuration.highlight_code_syntax
      SpreeBlogit::Renderers.choose_highlight_renderer
    else
      Redcarpet::Render::HTML
    end
  end

  # The Redcarpet Markdown handler
  def markdown
    @markdown ||= Redcarpet::Markdown.new(renderer,
      SpreeBlogit.configuration.redcarpet_options)
  end

  # Ensures pygments is installed
  #
  # Raises StandardError if pygments is not available on this machine
  def ensure_pygments_is_installed
    warning = <<-WARNING
[blogit] The pygmentize command could not be found in your load path!
         Please either do one of the following:

         $ sudo easy_install Pygments # to install it

         or

         set config.highlight_code_syntax to false in your blogit.rb config file.

WARNING
    raise warning unless which(:pygmentize)
  end

  # Check if an executable exists in the load path
  #
  # Returns nil if no executable is found
  def which(cmd)
    exts = ENV['PATHEXT'] ? ENV['PATHEXT'].split(';') : ['']
    ENV['PATH'].split(File::PATH_SEPARATOR).each do |path|
      exts.each do |ext|
        exe = File.join(path, "#{cmd}#{ext}")
        return exe if File.executable? exe
      end
    end
    return nil
  end

end


text:
RepoSync
========

A tool for syncing code between different types of repositories