text:
using namespace hilti;
using namespace passes;

InstructionNormalizer::InstructionNormalizer() : Pass<>("hilti::InstructionNormalizer", true)
{
}

bool InstructionNormalizer::run(shared_ptr<hilti::Node> module)
{
    return processAllPostOrder(module);
}

shared_ptr<expression::Variable> InstructionNormalizer::_addLocal(shared_ptr<statement::Block> block, const string& hint, shared_ptr<Type> type, bool force_name, const Location& l)
{
    auto cnt = 0;
    string name;

    if ( force_name )
        name = hint;

    else {
        do {
            name = util::fmt("__%s_%p_%d", hint, block.get(), ++cnt);
        } while ( _names.find(name) != _names.end() );
    }

    _names.insert(name);

    auto id = std::make_shared<ID>(name, l);
    auto var = std::make_shared<variable::Local>(id, type, nullptr, l);
    auto decl = std::make_shared<declaration::Variable>(id, var, l);
    block->addDeclaration(decl);

    block->scope()->insert(id, std::make_shared<expression::Variable>(var));

    return std::make_shared<expression::Variable>(var, l);
}

std::pair<shared_ptr<statement::Block>, shared_ptr<Expression>> InstructionNormalizer::_addBlock(shared_ptr<statement::Block> parent, const string& hint, bool dont_add_yet, const Location& l)
{
    auto cnt = 0;

    string name;

    do {
        name = util::fmt("@__%s_%d", hint, ++cnt);
    } while ( _names.find(name) != _names.end() );

    _names.insert(name);

    auto id = std::make_shared<ID>(name, l);

    auto child = std::make_shared<statement::Block>(nullptr, id, l);
    auto expr = builder::label::create(name, l);

    parent->scope()->insert(id, std::make_shared<expression::Block>(child));

    if ( ! dont_add_yet )
        parent->addStatement(child);

    child->scope()->setParent(parent->scope());

    return std::make_pair(child, expr);
}

void InstructionNormalizer::_addInstruction(shared_ptr<statement::Block> block,
                            shared_ptr<Expression> target,
                            shared_ptr<Instruction> ins,
                            shared_ptr<Expression> op1,
                            shared_ptr<Expression> op2,
                            shared_ptr<Expression> op3,
                            const Location& l)
{
    hilti::instruction::Operands ops = { target, op1, op2, op3 };
    auto instr = std::make_shared<statement::instruction::Unresolved>(ins, ops, l);
    block->addStatement(instr);
}

void InstructionNormalizer::visit(Module* f)
{
}

void InstructionNormalizer::visit(declaration::Function* f)
{
    _names.clear();
}

void InstructionNormalizer::visit(statement::ForEach* s)
{
    shared_ptr<type::Reference> r = ast::as<type::Reference>(s->sequence()->type());
    shared_ptr<Type> t = r ? r->argType() : s->sequence()->type();
    auto iterable = ast::as<type::trait::Iterable>(t);

    if ( ! iterable )
        internalError(s, ::util::fmt("InstructionNormalizer/ForEach: %s is not iterable", t->render()));

    auto parent = current<statement::Block>();
    assert(parent);

    auto nblock = std::make_shared<statement::Block>(nullptr);
    nblock->scope()->setParent(parent->scope());

    auto var = _addLocal(nblock, s->id()->name(), iterable->elementType());
    auto end = _addLocal(nblock, "end",  iterable->iterType());
    auto iter = _addLocal(nblock, "iter", iterable->iterType());
    auto cmp = _addLocal(nblock, "cmp", std::make_shared<type::Bool>());
    auto container = _addLocal(nblock, "iterable", s->sequence()->type());

    auto entry = _addBlock(nblock, "loop_entry");
    auto cond = _addBlock(nblock, "loop_cond");
    auto deref = _addBlock(nblock, "loop_deref");
    auto body = _addBlock(nblock, "loop_body");
    auto next = _addBlock(nblock, "loop_next");
    auto cont = _addBlock(nblock, "loop_end");

    IDReplacer replacer;
    replacer.run(s->body(), std::make_shared<ID>(statement::foreach::IDLoopBreak), cont.first->id());
    replacer.run(s->body(), std::make_shared<ID>(statement::foreach::IDLoopNext), next.first->id());
    replacer.run(s->body(), s->id(), var->variable()->id());

    _addInstruction(entry.first, container, instruction::operator_::Assign, s->sequence());
    _addInstruction(entry.first, iter, instruction::operator_::Begin, container);
    _addInstruction(entry.first, end,  instruction::operator_::End, container);
    _addInstruction(entry.first, nullptr, instruction::flow::Jump, cond.second);

    _addInstruction(cond.first, cmp, instruction::operator_::Equal, iter, end);
    _addInstruction(cond.first, nullptr, instruction::flow::IfElse, cmp, cont.second, deref.second);

    _addInstruction(deref.first, var, instruction::operator_::Deref, iter);
    _addInstruction(deref.first, nullptr, instruction::flow::Jump, body.second);

    auto b = s->body();
    b->removeFromParents();

    body.first->addStatement(b);
    b->scope()->setParent(body.first->scope());

    _addInstruction(next.first, iter, instruction::operator_::Incr, iter);
    _addInstruction(next.first, nullptr, instruction::flow::Jump, cond.second);

    s->replace(nblock);
}

void InstructionNormalizer::visit(statement::Try* s)
{
    auto parent = current<statement::Block>();
    assert(parent);

    auto nblock = std::make_shared<statement::Block>(nullptr);
    nblock->scope()->setParent(parent->scope());

    auto cblocks = std::make_shared<statement::Block>(nullptr, nullptr);
    cblocks->scope()->setParent(nblock->scope());

    auto cont = _addBlock(nblock, "catch_cont", true);

    for ( auto i = s->catches().rbegin(); i != s->catches().rend(); i++ ) {
        auto c = *i;

        auto cblock = _addBlock(nblock, "catch", true);

        if ( c->type() ) {
            auto var = _addLocal(cblock.first, c->id()->name(), c->type(), true);
            _addInstruction(cblock.first, var, instruction::exception::__GetAndClear);
        }

        else
            _addInstruction(cblock.first, nullptr, instruction::exception::__Clear);

        c->block()->removeFromParents();
        cblock.first->addStatement(c->block());

        _addInstruction(cblock.first, nullptr, instruction::flow::Jump, cont.second);

        shared_ptr<Expression> type = nullptr;

        if ( c->type() ) {
            auto rtype = ast::tryCast<type::Reference>(c->type());

            if ( ! rtype ) {
                error(c->type(), "catch value must be of ref<exception> type");
                return;
            }

            type = builder::type::create(rtype->argType());
        }

        _addInstruction(nblock, nullptr, instruction::exception::__BeginHandler, cblock.second, type);
        cblocks->addStatement(cblock.first);
    }

    s->block()->removeFromParents();
    nblock->addStatement(s->block());

    for ( auto c : s->catches() )
        _addInstruction(nblock, nullptr, instruction::exception::__EndHandler);

    _addInstruction(nblock, nullptr, instruction::flow::Jump, cont.second);

    nblock->addStatement(cblocks);
    nblock->addStatement(cont.first);

    s->replace(nblock);
}


text:
// Copyright (c) 2012 Ecma International.  All rights reserved.
// Ecma International makes this code available under the terms and conditions set
// forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the
// "Use Terms").   Any redistribution of this code must retain the above
// copyright and this notice and otherwise comply with the Use Terms.

/*---
es5id: 11.13.2-1-s
description: >
    Strict Mode - ReferenceError is thrown if the
    LeftHandSideExpression of a Compound Assignment operator(*=)
    evaluates to an unresolvable reference
flags: [onlyStrict]
includes: [runTestCase.js]
---*/

function testcase() {
        "use strict";
        try {
            eval("_11_13_2_1 *= 1;");
            return false;
        } catch (e) {
            return e instanceof ReferenceError;
        }
    }
runTestCase(testcase);

redpajama_set_name: RedPajamaGithub


text:
"""
TResNet: High Performance GPU-Dedicated Architecture
https://arxiv.org/pdf/2003.13630.pdf

Original model: https://github.com/mrT23/TResNet

"""
from collections import OrderedDict

import torch
import torch.nn as nn

from .helpers import build_model_with_cfg
from .layers import SpaceToDepthModule, BlurPool2d, InplaceAbn, ClassifierHead, SEModule
from .registry import register_model

__all__ = ['tresnet_m', 'tresnet_l', 'tresnet_xl']

def _cfg(url='', **kwargs):
    return {
        'url': url, 'num_classes': 1000, 'input_size': (3, 224, 224), 'pool_size': (7, 7),
        'crop_pct': 0.875, 'interpolation': 'bilinear',
        'mean': (0., 0., 0.), 'std': (1., 1., 1.),
        'first_conv': 'body.conv1.0', 'classifier': 'head.fc',
        **kwargs
    }

default_cfgs = {
    'tresnet_m': _cfg(
        url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-tresnet/tresnet_m_1k_miil_83_1-d236afcb.pth'),
    'tresnet_m_miil_in21k': _cfg(
        url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-tresnet/tresnet_m_miil_in21k-901b6ed4.pth', num_classes=11221),
    'tresnet_l': _cfg(
        url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-tresnet/tresnet_l_81_5-235b486c.pth'),
    'tresnet_xl': _cfg(
        url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-tresnet/tresnet_xl_82_0-a2d51b00.pth'),
    'tresnet_m_448': _cfg(
        input_size=(3, 448, 448), pool_size=(14, 14),
        url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-tresnet/tresnet_m_448-bc359d10.pth'),
    'tresnet_l_448': _cfg(
        input_size=(3, 448, 448), pool_size=(14, 14),
        url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-tresnet/tresnet_l_448-940d0cd1.pth'),
    'tresnet_xl_448': _cfg(
        input_size=(3, 448, 448), pool_size=(14, 14),
        url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-tresnet/tresnet_xl_448-8c1815de.pth'),

    'tresnet_v2_l': _cfg(
        url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-tresnet/tresnet_l_v2_83_9-f36e4445.pth'),
}

def IABN2Float(module: nn.Module) -> nn.Module:
    """If `module` is IABN don't use half precision."""
    if isinstance(module, InplaceAbn):
        module.float()
    for child in module.children():
        IABN2Float(child)
    return module

def conv2d_iabn(ni, nf, stride, kernel_size=3, groups=1, act_layer="leaky_relu", act_param=1e-2):
    return nn.Sequential(
        nn.Conv2d(
            ni, nf, kernel_size=kernel_size, stride=stride, padding=kernel_size // 2, groups=groups, bias=False),
        InplaceAbn(nf, act_layer=act_layer, act_param=act_param)
    )

class BasicBlock(nn.Module):
    expansion = 1

    def __init__(self, inplanes, planes, stride=1, downsample=None, use_se=True, aa_layer=None):
        super(BasicBlock, self).__init__()
        if stride == 1:
            self.conv1 = conv2d_iabn(inplanes, planes, stride=1, act_param=1e-3)
        else:
            if aa_layer is None:
                self.conv1 = conv2d_iabn(inplanes, planes, stride=2, act_param=1e-3)
            else:
                self.conv1 = nn.Sequential(
                    conv2d_iabn(inplanes, planes, stride=1, act_param=1e-3),
                    aa_layer(channels=planes, filt_size=3, stride=2))

        self.conv2 = conv2d_iabn(planes, planes, stride=1, act_layer="identity")
        self.relu = nn.ReLU(inplace=True)
        self.downsample = downsample
        self.stride = stride
        rd_chs = max(planes * self.expansion // 4, 64)
        self.se = SEModule(planes * self.expansion, rd_channels=rd_chs) if use_se else None

    def forward(self, x):
        if self.downsample is not None:
            shortcut = self.downsample(x)
        else:
            shortcut = x

        out = self.conv1(x)
        out = self.conv2(out)

        if self.se is not None:
            out = self.se(out)

        out = out + shortcut
        out = self.relu(out)
        return out

class Bottleneck(nn.Module):
    expansion = 4

    def __init__(
            self, inplanes, planes, stride=1, downsample=None, use_se=True,
            act_layer="leaky_relu", aa_layer=None):
        super(Bottleneck, self).__init__()
        self.conv1 = conv2d_iabn(
            inplanes, planes, kernel_size=1, stride=1, act_layer=act_layer, act_param=1e-3)
        if stride == 1:
            self.conv2 = conv2d_iabn(
                planes, planes, kernel_size=3, stride=1, act_layer=act_layer, act_param=1e-3)
        else:
            if aa_layer is None:
                self.conv2 = conv2d_iabn(
                    planes, planes, kernel_size=3, stride=2, act_layer=act_layer, act_param=1e-3)
            else:
                self.conv2 = nn.Sequential(
                    conv2d_iabn(planes, planes, kernel_size=3, stride=1, act_layer=act_layer, act_param=1e-3),
                    aa_layer(channels=planes, filt_size=3, stride=2))

        reduction_chs = max(planes * self.expansion // 8, 64)
        self.se = SEModule(planes, rd_channels=reduction_chs) if use_se else None

        self.conv3 = conv2d_iabn(
            planes, planes * self.expansion, kernel_size=1, stride=1, act_layer="identity")

        self.act = nn.ReLU(inplace=True)
        self.downsample = downsample
        self.stride = stride

    def forward(self, x):
        if self.downsample is not None:
            shortcut = self.downsample(x)
        else:
            shortcut = x

        out = self.conv1(x)
        out = self.conv2(out)
        if self.se is not None:
            out = self.se(out)
        out = self.conv3(out)
        out = out + shortcut  # no inplace
        out = self.act(out)

        return out

class TResNet(nn.Module):
    def __init__(
            self,
            layers,
            in_chans=3,
            num_classes=1000,
            width_factor=1.0,
            v2=False,
            global_pool='fast',
            drop_rate=0.,
    ):
        self.num_classes = num_classes
        self.drop_rate = drop_rate
        super(TResNet, self).__init__()

        aa_layer = BlurPool2d

        # TResnet stages
        self.inplanes = int(64 * width_factor)
        self.planes = int(64 * width_factor)
        if v2:
            self.inplanes = self.inplanes // 8 * 8
            self.planes = self.planes // 8 * 8

        conv1 = conv2d_iabn(in_chans * 16, self.planes, stride=1, kernel_size=3)
        layer1 = self._make_layer(
            Bottleneck if v2 else BasicBlock, self.planes, layers[0], stride=1, use_se=True, aa_layer=aa_layer)
        layer2 = self._make_layer(
            Bottleneck if v2 else BasicBlock, self.planes * 2, layers[1], stride=2, use_se=True, aa_layer=aa_layer)
        layer3 = self._make_layer(
            Bottleneck, self.planes * 4, layers[2], stride=2, use_se=True, aa_layer=aa_layer)
        layer4 = self._make_layer(
            Bottleneck, self.planes * 8, layers[3], stride=2, use_se=False, aa_layer=aa_layer)

        # body
        self.body = nn.Sequential(OrderedDict([
            ('SpaceToDepth', SpaceToDepthModule()),
            ('conv1', conv1),
            ('layer1', layer1),
            ('layer2', layer2),
            ('layer3', layer3),
            ('layer4', layer4)]))

        self.feature_info = [
            dict(num_chs=self.planes, reduction=2, module=''),  # Not with S2D?
            dict(num_chs=self.planes * (Bottleneck.expansion if v2 else 1), reduction=4, module='body.layer1'),
            dict(num_chs=self.planes * 2 * (Bottleneck.expansion if v2 else 1), reduction=8, module='body.layer2'),
            dict(num_chs=self.planes * 4 * Bottleneck.expansion, reduction=16, module='body.layer3'),
            dict(num_chs=self.planes * 8 * Bottleneck.expansion, reduction=32, module='body.layer4'),
        ]

        # head
        self.num_features = (self.planes * 8) * Bottleneck.expansion
        self.head = ClassifierHead(self.num_features, num_classes, pool_type=global_pool, drop_rate=drop_rate)

        # model initialization
        for m in self.modules():
            if isinstance(m, nn.Conv2d):
                nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='leaky_relu')
            elif isinstance(m, nn.BatchNorm2d) or isinstance(m, InplaceAbn):
                nn.init.constant_(m.weight, 1)
                nn.init.constant_(m.bias, 0)

        # residual connections special initialization
        for m in self.modules():
            if isinstance(m, BasicBlock):
                m.conv2[1].weight = nn.Parameter(torch.zeros_like(m.conv2[1].weight))  # BN to zero
            if isinstance(m, Bottleneck):
                m.conv3[1].weight = nn.Parameter(torch.zeros_like(m.conv3[1].weight))  # BN to zero
            if isinstance(m, nn.Linear):
                m.weight.data.normal_(0, 0.01)

    def _make_layer(self, block, planes, blocks, stride=1, use_se=True, aa_layer=None):
        downsample = None
        if stride != 1 or self.inplanes != planes * block.expansion:
            layers = []
            if stride == 2:
                # avg pooling before 1x1 conv
                layers.append(nn.AvgPool2d(kernel_size=2, stride=2, ceil_mode=True, count_include_pad=False))
            layers += [conv2d_iabn(
                self.inplanes, planes * block.expansion, kernel_size=1, stride=1, act_layer="identity")]
            downsample = nn.Sequential(*layers)

        layers = []
        layers.append(block(
            self.inplanes, planes, stride, downsample, use_se=use_se, aa_layer=aa_layer))
        self.inplanes = planes * block.expansion
        for i in range(1, blocks):
            layers.append(
                block(self.inplanes, planes, use_se=use_se, aa_layer=aa_layer))
        return nn.Sequential(*layers)

    @torch.jit.ignore
    def group_matcher(self, coarse=False):
        matcher = dict(stem=r'^body\.conv1', blocks=r'^body\.layer(\d+)' if coarse else r'^body\.layer(\d+)\.(\d+)')
        return matcher

    @torch.jit.ignore
    def set_grad_checkpointing(self, enable=True):
        assert not enable, 'gradient checkpointing not supported'

    @torch.jit.ignore
    def get_classifier(self):
        return self.head.fc

    def reset_classifier(self, num_classes, global_pool='fast'):
        self.head = ClassifierHead(
            self.num_features, num_classes, pool_type=global_pool, drop_rate=self.drop_rate)

    def forward_features(self, x):
        return self.body(x)

    def forward_head(self, x, pre_logits: bool = False):
        return x if pre_logits else self.head(x)

    def forward(self, x):
        x = self.forward_features(x)
        x = self.forward_head(x)
        return x

def _create_tresnet(variant, pretrained=False, **kwargs):
    return build_model_with_cfg(
        TResNet, variant, pretrained,
        feature_cfg=dict(out_indices=(1, 2, 3, 4), flatten_sequential=True),
        **kwargs)

@register_model
def tresnet_m(pretrained=False, **kwargs):
    model_kwargs = dict(layers=[3, 4, 11, 3], **kwargs)
    return _create_tresnet('tresnet_m', pretrained=pretrained, **model_kwargs)

@register_model
def tresnet_m_miil_in21k(pretrained=False, **kwargs):
    model_kwargs = dict(layers=[3, 4, 11, 3], **kwargs)
    return _create_tresnet('tresnet_m_miil_in21k', pretrained=pretrained, **model_kwargs)

@register_model
def tresnet_l(pretrained=False, **kwargs):
    model_kwargs = dict(layers=[4, 5, 18, 3], width_factor=1.2, **kwargs)
    return _create_tresnet('tresnet_l', pretrained=pretrained, **model_kwargs)

@register_model
def tresnet_v2_l(pretrained=False, **kwargs):
    model_kwargs = dict(layers=[3, 4, 23, 3], width_factor=1.0, v2=True, **kwargs)
    return _create_tresnet('tresnet_v2_l', pretrained=pretrained, **model_kwargs)

@register_model
def tresnet_xl(pretrained=False, **kwargs):
    model_kwargs = dict(layers=[4, 5, 24, 3], width_factor=1.3, **kwargs)
    return _create_tresnet('tresnet_xl', pretrained=pretrained, **model_kwargs)

@register_model
def tresnet_m_448(pretrained=False, **kwargs):
    model_kwargs = dict(layers=[3, 4, 11, 3], **kwargs)
    return _create_tresnet('tresnet_m_448', pretrained=pretrained, **model_kwargs)

@register_model
def tresnet_l_448(pretrained=False, **kwargs):
    model_kwargs = dict(layers=[4, 5, 18, 3], width_factor=1.2, **kwargs)
    return _create_tresnet('tresnet_l_448', pretrained=pretrained, **model_kwargs)

@register_model
def tresnet_xl_448(pretrained=False, **kwargs):
    model_kwargs = dict(layers=[4, 5, 24, 3], width_factor=1.3, **kwargs)
    return _create_tresnet('tresnet_xl_448', pretrained=pretrained, **model_kwargs)


text:
@interface BasicTableView : UITableView<BasicViewProtocol>

@property (readwrite) BOOL refreshEnabled;

@property (readwrite) BOOL loadingMoreEnabled;

@property (strong,nonatomic) UIRefreshControl *refreshControl;

@end


text:
package com.payneteasy.superfly.web.security;

import org.springframework.security.access.annotation.Secured;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;

public class SecurityUtils {
    public static boolean isUserInRole(String aRole) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (null == authentication) {
            return false;
        }
        Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
        if (authentication.getPrincipal() == null || authorities == null) {
            return false;
        }

        for (GrantedAuthority authority : authorities) {
            if (aRole.equals(authority.getAuthority())) {
                return true;
            }
        }

        return false;
    }

    public static String[] getRoles() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (null == authentication) {
            return null;
        }
        Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
        if (authentication.getPrincipal() == null || authorities == null) {
            return null;
        }

        String[] roles = new String[authorities.size()];
        int i = 0;
        for (GrantedAuthority authority : authorities) {
            roles[i] = authority.getAuthority();
            i++;
        }

        return roles;
    }

    public static String getUsername() {
        Object obj = SecurityContextHolder.getContext().getAuthentication().getPrincipal();

        String username;
        if (obj instanceof UserDetails) {
            username = ((UserDetails) obj).getUsername();
        } else {
            username = obj.toString();
        }
        return username;
    }

    @SuppressWarnings({ "rawtypes", "unchecked" })
    public static boolean isComponentVisible(Class aComponentClass) {
        if (aComponentClass.isAnnotationPresent(Secured.class)) {
            Secured securedAnnotation = (Secured) aComponentClass.getAnnotation(Secured.class);
            String[] roles = securedAnnotation.value();
            if (roles != null && roles.length > 0) {
                for (String role : roles) {
                    if (isUserInRole(role)) {
                        return true;
                    }
                }
                return false;
            } else {
                throw new RuntimeException("Page " + aComponentClass.getName() + " has no roles in Secured annotation");
            }

        } else {
            throw new RuntimeException("Page " + aComponentClass.getName() + " has no Secured annotation");
        }
    }

    public static boolean isTempPassword() {
        return isUserInRole("ROLE_ACTION_TEMP_PASSWORD");
    }
}


text:
import numpy as np
import torch
import torch.nn as nn
import progressbar
import time
import copy

def initialization(init_method, W, is_tensor=True):
    """ Initializes the provided tensor.

    Parameters:
    -----------

    * init_method : str (default = 'glorot_uniform')
        Initialization method to use. Here are the possible options:
            * 'glorot_uniform': Glorot/Xavier uniform initializer,
                Glorot & Bengio, AISTATS 2010
                http://jmlr.org/proceedings/papers/v9/glorot10a/glorot10a.pdf
            * 'he_uniform': He uniform variance scaling initializer
               He et al., http://arxiv.org/abs/1502.01852
            * 'uniform': Initializing tensors with uniform (-1, 1) distribution
            * 'glorot_normal': Glorot normal initializer,
            * 'he_normal': He normal initializer.
            * 'normal': Initializing tensors with standard normal distribution
            * 'ones': Initializing tensors to 1
            * 'zeros': Initializing tensors to 0
            * 'orthogonal': Initializing tensors with an orthogonal matrix,

    * W: torch.Tensor
        Corresponds to the Torch tensor

      """

    # Checking the dimensions
    is_one_dim = False

    # Checking if the parameters is a tensor, if not transform it into one
    if not is_tensor:
        W = torch.FloatTensor(W)

    # Creating a column vector if one dimensional tensor
    if len(W.shape)==1:
        is_one_dim = True
        W = torch.reshape(W, (1, -1))

    # Initializing the weights
    if init_method.lower() == 'uniform':
        W = nn.init.uniform_(W)

    elif init_method.lower() == 'normal':
        W = nn.init.normal_(W)

    elif init_method.lower().startswith('one'):
        W = nn.init.ones_(W)

    elif init_method.lower().startswith('zero'):
        W = nn.init.zeros_(W)

    elif init_method.lower().startswith('ortho'):
        W = nn.init.orthogonal_(W)

    elif init_method.lower().startswith('glorot') or \
    init_method.lower().startswith('xav'):

        if init_method.lower().endswith('uniform'):
            W = nn.init.xavier_uniform_(W)
        elif init_method.lower().endswith('normal'):
            W = nn.init.xavier_normal_(W)

    elif init_method.lower().startswith('he') or \
    init_method.lower().startswith('kaiming'):

        if init_method.lower().endswith('uniform'):
            W = nn.init.kaiming_uniform_(W)
        elif init_method.lower().endswith('normal'):
            W = nn.init.kaiming_normal_(W)

    else:
        error = " {} isn't implemented".format(init_method)
        raise NotImplementedError(error)

    # Returning a PyTorch tensor
    if is_tensor:
        if is_one_dim:
            return torch.nn.Parameter(W.flatten())
        else:
            return torch.nn.Parameter(W)

    # Returning a Numpy array
    else:
        if is_one_dim:
            return W.data.numpy().flatten()
        else:
            return W.data.numpy()

def optimize(loss_function, model, optimizer_str, lr=1e-4, nb_epochs=1000,
               verbose = True, num_workers = 0, **kargs):
    """
    Providing the schema of the iterative method for optimizing a
    differentiable objective function for models that use gradient centric
    schemas (a.k.a order 1 optimization)

    Parameters:
    -----------
        * loss_function: function
            Loss function of the model

        * model: torch object
            Actual model to optimize

        * optimizer_str: str
            Defines the type of optimizer to use. Here are the possible options:
                - adadelta
                - adagrad
                - adam
                - adamax
                - rmsprop
                - sparseadam
                - sgd

        * lr: float (default=1e-4)
            learning reate used in the optimization

        * nb_epochs: int (default=1000)
            The number of iterations in the optimization

        * verbose: bool (default=True)
            Whether or not producing detailed logging about the modeling
    """

    # Choosing an optimizer
    W = model.parameters()
    if optimizer_str.lower() == 'adadelta':
        optimizer = torch.optim.Adadelta(W, lr=lr)

    elif optimizer_str.lower() == 'adagrad':
        optimizer = torch.optim.Adagrad(W, lr=lr)

    elif optimizer_str.lower() == 'adam':
        optimizer = torch.optim.Adam(W, lr=lr)

    elif optimizer_str.lower() == 'adamax':
        optimizer = torch.optim.Adamax(W, lr=lr)

    elif optimizer_str.lower() == 'rmsprop':
        optimizer = torch.optim.RMSprop(W, lr=lr)

    elif optimizer_str.lower() == 'sparseadam':
        optimizer = torch.optim.SparseAdam(W, lr=lr)

    elif optimizer_str.lower() == 'sgd':
        optimizer = torch.optim.SGD(W, lr=lr)

    elif optimizer_str.lower() == 'lbfgs':
        optimizer = torch.optim.LBFGS(W, lr=lr)

    elif optimizer_str.lower() == 'rprop':
        optimizer = torch.optim.Rprop(W, lr=lr)

    else:
        error = "{} optimizer isn't implemented".format(optimizer_str)
        raise NotImplementedError(error)

    # Initializing the Progress Bar
    loss_values = []
    if verbose:
        widgets = [ '% Completion: ', progressbar.Percentage(),
                   progressbar.Bar('*'), '']
        bar = progressbar.ProgressBar(maxval=nb_epochs, widgets=widgets)
        bar.start()

    # Updating the weights at each training epoch
    temp_model = None
    for epoch in range(nb_epochs):

        # Backward pass and optimization
        def closure():
            optimizer.zero_grad()
            loss = loss_function(model, **kargs)
            loss.backward()
            return loss

        if 'lbfgs' in optimizer_str.lower() :
            optimizer.step(closure)
        else:
            optimizer.step()
        loss = closure()
        loss_value = loss.item()

        # Printing error message if the gradient didn't explode
        if np.isnan(loss_value) or np.isinf(loss_value):
            error = "The gradient exploded... "
            error += "You should reduce the learning"
            error += "rate (lr) of your optimizer"
            if verbose:
                widgets[-1] = error
            else:
                print(error)
            break

        # Otherwise, printing value of loss function
        else:
            temp_model = copy.deepcopy(model)
            loss_values.append( loss_value )
            if verbose:
                widgets[-1] = "Loss: {:6.2f}".format( loss_value )

        # Updating the progressbar
        if verbose:
            bar.update( epoch + 1 )

    # Terminating the progressbar
    if verbose:
        bar.finish()

    # Finilazing the model
    if temp_model is not None:
        temp_model = temp_model.eval()
        model = copy.deepcopy(temp_model)
    else:
        raise ValueError(error)

    return model, loss_values


text:
'use strict';

const Boom = require('@hapi/boom');

module.exports = (settings, h) => {
  if (settings.cookie.clearInvalid) {
    h.unstate(settings.cookieName);
  }

  return Boom.unauthorized('Invalid cookie.');
};


text:
ARG UPSTREAM_REPO
ARG UPSTREAM_TAG
FROM ${UPSTREAM_REPO:-uselagoon}/mariadb:${UPSTREAM_TAG:-latest}

ARG LAGOON_VERSION
ENV LAGOON_VERSION=$LAGOON_VERSION

ENV MARIADB_DATABASE=keycloak \
    MARIADB_USER=keycloak \
    MARIADB_PASSWORD=keycloak \
    MARIADB_CHARSET=utf8 \
    MARIADB_COLLATION=utf8_general_ci


text:
<?php

/**
 * Slim View
 *
 * The View is responsible for rendering and/or displaying a template.
 * It is recommended that you subclass View and re-implement the
 * `View::render` method to use a custom templating engine such as
 * Smarty, Twig, Mustache, etc. It is important that `View::render`
 * `return` the final template output. Do not `echo` the output.
 *
 * @package Slim
 * @author  Josh Lockhart <info@joshlockhart.com>
 * @since   Version 1.0
 */
class Slim_View {

    /**
     * @var array Key-value array of data available to the template
     */
    protected $data = array();

    /**
     * @var string Absolute or relative path to the templates directory
     */
    protected $templatesDirectory;

    /**
     * Constructor
     *
     * This is empty but may be overridden in a subclass
     */
    public function __construct() {}

    /**
     * Get data
     * @param   string              $key
     * @return  array|mixed|null    All View data if no $key, value of datum
     *                              if $key, or NULL if $key but datum
     *                              does not exist.
     */
    public function getData( $key = null ) {
        if ( !is_null($key) ) {
            return isset($this->data[$key]) ? $this->data[$key] : null;
        } else {
            return $this->data;
        }
    }

    /**
     * Set data
     *
     * This method is overloaded to accept two different method signatures.
     * You may use this to set a specific key with a specfic value,
     * or you may use this to set all data to a specific array.
     *
     * USAGE:
     *
     * View::setData('color', 'red');
     * View::setData(array('color' => 'red', 'number' => 1));
     *
     * @param   string|array
     * @param   mixed                       Optional. Only use if first argument is a string.
     * @return  void
     * @throws  InvalidArgumentException    If incorrect method signature
     */
    public function setData() {
        $args = func_get_args();
        if ( count($args) === 1 && is_array($args[0]) ) {
            $this->data = $args[0];
        } else if ( count($args) === 2 ) {
            $this->data[(string)$args[0]] = $args[1];
        } else {
            throw new InvalidArgumentException('Cannot set View data with provided arguments. Usage: `View::setData( $key, $value );` or `View::setData([ key => value, ... ]);`');
        }
    }

    /**
     * Append data to existing View data
     * @param   array $data
     * @return  void
     */
    public function appendData( array $data ) {
        $this->data = array_merge($this->data, $data);
    }

    /**
     * Get templates directory
     * @return string|null Path to templates directory without trailing slash
     */
    public function getTemplatesDirectory() {
        return $this->templatesDirectory;
    }

    /**
     * Set templates directory
     * @param   string $dir
     * @return  void
     * @throws  RuntimeException If directory is not a directory or does not exist
     */
    public function setTemplatesDirectory( $dir ) {
        if ( !is_dir($dir) ) {
            throw new RuntimeException('Cannot set View templates directory to: ' . $dir . '. Directory does not exist.');
        }
        $this->templatesDirectory = rtrim($dir, '/');
    }

    /**
     * Display template
     *
     * This method echoes the rendered template to the current output buffer
     *
     * @param   string $template Path to template file relative to templates directoy
     * @return  void
     */
    public function display( $template ) {
        echo $this->render($template);
    }

    /**
     * Render template
     * @param   string $template    Path to template file relative to templates directory
     * @return  string              Rendered template
     * @throws  RuntimeException    If template does not exist
     */
    public function render( $template ) {
        extract($this->data);
        $templatePath = $this->getTemplatesDirectory() . '/' . ltrim($template, '/');
        if ( !file_exists($templatePath) ) {
            throw new RuntimeException('View cannot render template `' . $templatePath . '`. Template does not exist.');
        }
        ob_start();
        require $templatePath;
        return ob_get_clean();
    }

}


text:
package org.apache.bookkeeper.stream.server;

import java.net.UnknownHostException;
import org.apache.bookkeeper.common.component.LifecycleComponent;
import org.apache.bookkeeper.server.component.ServerLifecycleComponent;
import org.apache.bookkeeper.server.conf.BookieConfiguration;
import org.apache.bookkeeper.stats.StatsLogger;
import org.apache.bookkeeper.stream.server.conf.StorageServerConfiguration;
import org.apache.commons.configuration.ConfigurationException;

/**
 * This is a {@link ServerLifecycleComponent} to allow run stream storage component as part of bookie server.
 */
public class StreamStorageLifecycleComponent extends ServerLifecycleComponent {

    private final LifecycleComponent streamStorage;

    public StreamStorageLifecycleComponent(BookieConfiguration conf, StatsLogger statsLogger)
            throws UnknownHostException, ConfigurationException {
        super("stream-storage", conf, statsLogger);

        StorageServerConfiguration ssConf = StorageServerConfiguration.of(conf.getUnderlyingConf());

        this.streamStorage = StorageServer.buildStorageServer(
            conf.getUnderlyingConf(),
            ssConf.getGrpcPort(),
            false,
            statsLogger.scope("stream"));
    }

    @Override
    protected void doStart() {
        this.streamStorage.start();
    }

    @Override
    protected void doStop() {
        this.streamStorage.stop();
    }

    @Override
    protected void doClose() {
        this.streamStorage.close();
    }
}


text:
package org.zaproxy.zap.extension.soap.spider;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.parosproxy.paros.Constant;
import org.parosproxy.paros.control.Control;
import org.parosproxy.paros.extension.Extension;
import org.parosproxy.paros.extension.ExtensionAdaptor;
import org.parosproxy.paros.extension.ExtensionHook;
import org.zaproxy.addon.spider.ExtensionSpider2;
import org.zaproxy.addon.spider.parser.SpiderParser;
import org.zaproxy.zap.extension.soap.ExtensionImportWSDL;

public class ExtensionSoapSpider extends ExtensionAdaptor {

    private static final List<Class<? extends Extension>> DEPENDENCIES =
            Collections.unmodifiableList(
                    Arrays.asList(ExtensionSpider2.class, ExtensionImportWSDL.class));

    private SpiderParser spiderParser;

    @Override
    public String getUIName() {
        return Constant.messages.getString("soap.spider.name");
    }

    @Override
    public String getDescription() {
        return Constant.messages.getString("soap.spider.desc");
    }

    @Override
    public List<Class<? extends Extension>> getDependencies() {
        return DEPENDENCIES;
    }

    @Override
    public void hook(ExtensionHook extensionHook) {
        spiderParser = new WsdlSpider(getExtension(ExtensionImportWSDL.class).getParser());
        getExtension(ExtensionSpider2.class).addCustomParser(spiderParser);
    }

    private static <T extends Extension> T getExtension(Class<T> clazz) {
        return Control.getSingleton().getExtensionLoader().getExtension(clazz);
    }

    @Override
    public boolean canUnload() {
        return true;
    }

    @Override
    public void unload() {
        getExtension(ExtensionSpider2.class).removeCustomParser(spiderParser);
    }
}


text:
namespace MassTransit.Tests.Saga.Messages
{
    using System;

    [Serializable]
	public class CompleteSimpleSaga :
		SimpleSagaMessageBase
	{
		public CompleteSimpleSaga()
		{
		}

		public CompleteSimpleSaga(Guid correlationId)
			:
				base(correlationId)
		{
		}
	}
}


text:
title: Font Sizes
page_title: Font Sizes | UI for ASP.NET AJAX Documentation
description: Font Sizes
slug: sharepoint/2010/radeditor-web-part/dropdowns/font-sizes
tags: font,sizes
published: True
position: 1
---

# Font Sizes

![](images/DropDowns003.png)

## Adding Font Sizes

You can populate the **FontSizes** dropdown by modifying the **ToolsFile.xml / ListToolsFile.xml** files, located in the following folder:

_/Program Files/Common Files/Microsoft Shared/web server extensions/wpresources/RadEditorSharePoint/6.x.x.0__1f131a624888eeed/Resources/_

**For example:**

````XML
<root>
    <tools name="MainToolbar" enabled="true">
        <tool name="FontSize" />
    </tools>
    <fontSizes>
        <item>1</item>
        <item>3</item>
        <item>5</item>
     </fontSizes>
</root>
````

If you want to apply font sizes in pixels (px) or in points (pt) then use the [Real Font Size]({%slug sharepoint/2010/radeditor-web-part/dropdowns/real-font-sizes%}) dropdown.


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <title>Interactive Canvas Sample</title>

    <link rel="shortcut icon" type="image/x-icon" href="data:image/x-icon;,">

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


text:
require "helper"
require "generators/minitest/model/model_generator"

class TestModelGenerator < GeneratorTest

  def test_model_generator
    assert_output(/create  test\/models\/user_test.rb/m) do
      Minitest::Generators::ModelGenerator.start ["user", "--no-spec"]
    end
    assert File.exists? "test/models/user_test.rb"
    contents = File.read "test/models/user_test.rb"
    assert_match(/class UserTest/m, contents)
  end

  def test_namespaced_model_generator
    assert_output(/create  test\/models\/admin\/user_test.rb/m) do
      Minitest::Generators::ModelGenerator.start ["admin/user", "--no-spec"]
    end
    assert File.exists? "test/models/admin/user_test.rb"
    contents = File.read "test/models/admin/user_test.rb"
    assert_match(/class Admin::UserTest/m, contents)
  end

  def test_module_namespaced_model_generator
    assert_nil Rails::Generators.namespace
    Rails::Generators.namespace = TestApp

    assert_output(/create  test\/models\/test_app\/user_test.rb/m) do
      Minitest::Generators::ModelGenerator.start ["user", "--no-spec"]
    end
    assert File.exists? "test/models/test_app/user_test.rb"
    contents = File.read "test/models/test_app/user_test.rb"
    assert_match(/module TestApp/m, contents)
    assert_match(/class UserTest/m, contents)
  ensure
    # Restore default namespace
    Rails::Generators.namespace = nil
  end if Rails::Generators.respond_to? :namespace

  def test_model_generator_spec
    assert_output(/create  test\/models\/user_test.rb/m) do
      Minitest::Generators::ModelGenerator.start ["user"]
    end
    assert File.exists? "test/models/user_test.rb"
    # assert File.exists? "test/fixtures/users.yml"
    contents = File.read "test/models/user_test.rb"
    assert_match(/describe User do/m, contents)
  end

  def test_namespaced_model_generator_spec
    assert_output(/create  test\/models\/admin\/user_test.rb/m) do
      Minitest::Generators::ModelGenerator.start ["admin/user"]
    end
    assert File.exists? "test/models/admin/user_test.rb"
    contents = File.read "test/models/admin/user_test.rb"
    assert_match(/describe Admin::User do/m, contents)
  end

  def test_model_generator_fixture
    assert_output(/create  test\/fixtures\/users.yml/m) do
      Minitest::Generators::ModelGenerator.start ["user", "--no-spec"]
    end
    assert File.exists? "test/fixtures/users.yml"
  end

  def test_namespaced_model_generator_fixture
    assert_output(/create  test\/fixtures\/admin\/users.yml/m) do
      Minitest::Generators::ModelGenerator.start ["admin/user", "--no-spec"]
    end
    assert File.exists? "test/fixtures/admin/users.yml"
  end

  def test_model_generator_skip_fixture
    out, _ = capture_io do
      Minitest::Generators::ModelGenerator.start ["user", "--skip-fixture"]
    end
    refute_match(/create  test\/fixtures\/users.yml/m, out)
    refute File.exists? "test/fixtures/users.yml"
  end
end


text:
#pragma once

#include "../../Container/HashMap.h"
#include "../../Core/Timer.h"
#include "../../GraphicsAPI/ConstantBuffer.h"
#include "../../GraphicsAPI/OpenGL/OGLShaderProgram.h"
#include "../../GraphicsAPI/Texture2D.h"
#include "../../Math/Color.h"

#if defined(IOS) || defined(TVOS)
#if URHO3D_GLES3
#include <OpenGLES/ES3/gl.h>
#include <OpenGLES/ES3/glext.h>
#else
#include <OpenGLES/ES2/gl.h>
#include <OpenGLES/ES2/glext.h>
#define URHO3D_GLES2
#endif
#elif defined(__ANDROID__) || defined (__arm__) || defined(__aarch64__) || defined (__EMSCRIPTEN__)
#if URHO3D_GLES3
#include <GLES3/gl3.h>
#ifndef __EMSCRIPTEN__
#include <GLES3/gl3ext.h>
#else
#include <GLES3/gl2ext.h>
#endif
#else
#include <GLES2/gl2.h>
#include <GLES2/gl2ext.h>
#define URHO3D_GLES2
#endif
#else
#include <GLEW/glew.h>
#endif

#ifndef GL_COMPRESSED_RGBA_S3TC_DXT1_EXT
#define GL_COMPRESSED_RGBA_S3TC_DXT1_EXT 0x83f1
#endif
#ifndef GL_COMPRESSED_RGBA_S3TC_DXT3_EXT
#define GL_COMPRESSED_RGBA_S3TC_DXT3_EXT 0x83f2
#endif
#ifndef GL_COMPRESSED_RGBA_S3TC_DXT5_EXT
#define GL_COMPRESSED_RGBA_S3TC_DXT5_EXT 0x83f3
#endif
#ifndef GL_ETC1_RGB8_OES
#define GL_ETC1_RGB8_OES 0x8d64
#endif
#ifndef GL_ETC2_RGB8_OES
#define GL_ETC2_RGB8_OES 0x9274
#endif
#ifndef GL_ETC2_RGBA8_OES
#define GL_ETC2_RGBA8_OES 0x9278
#endif
#ifndef GL_DEPTH_COMPONENT24_OES
#define GL_DEPTH_COMPONENT24_OES 0x81A6
#endif
#ifndef GL_DEPTH24_STENCIL8_OES
#define GL_DEPTH24_STENCIL8_OES 0x88F0
#endif
#ifndef COMPRESSED_RGB_PVRTC_4BPPV1_IMG
#define COMPRESSED_RGB_PVRTC_4BPPV1_IMG 0x8c00
#endif
#ifndef COMPRESSED_RGB_PVRTC_2BPPV1_IMG
#define COMPRESSED_RGB_PVRTC_2BPPV1_IMG 0x8c01
#endif
#ifndef COMPRESSED_RGBA_PVRTC_4BPPV1_IMG
#define COMPRESSED_RGBA_PVRTC_4BPPV1_IMG 0x8c02
#endif
#ifndef COMPRESSED_RGBA_PVRTC_2BPPV1_IMG
#define COMPRESSED_RGBA_PVRTC_2BPPV1_IMG 0x8c03
#endif

using SDL_GLContext = void *;

namespace Urho3D
{

class Context;

using ConstantBufferMap = HashMap<unsigned, SharedPtr<ConstantBuffer>>;
using ShaderProgramMap_OGL = HashMap<Pair<ShaderVariation*, ShaderVariation*>, SharedPtr<ShaderProgram_OGL>>;

/// Cached state of a frame buffer object.
struct FrameBufferObject
{
    /// Frame buffer handle.
    unsigned fbo_{};
    /// Bound color attachment textures.
    RenderSurface* colorAttachments_[MAX_RENDERTARGETS]{};
    /// Bound depth/stencil attachment.
    RenderSurface* depthAttachment_{};
    /// Read buffer bits.
    unsigned readBuffers_{M_MAX_UNSIGNED};
    /// Draw buffer bits.
    unsigned drawBuffers_{M_MAX_UNSIGNED};
};

/// %Graphics subsystem implementation. Holds API-specific objects.
class URHO3D_API GraphicsImpl_OGL
{
    friend class Graphics;

public:
    /// Construct.
    GraphicsImpl_OGL() = default;

    /// Return the GL Context.
    const SDL_GLContext& GetGLContext() { return context_; }

private:
    /// SDL OpenGL context.
    SDL_GLContext context_{};
    /// iOS/tvOS system framebuffer handle.
    unsigned systemFBO_{};
    /// Active texture unit.
    unsigned activeTexture_{};
    /// Enabled vertex attributes bitmask.
    unsigned enabledVertexAttributes_{};
    /// Vertex attributes bitmask used by the current shader program.
    unsigned usedVertexAttributes_{};
    /// Vertex attribute instancing bitmask for keeping track of divisors.
    unsigned instancingVertexAttributes_{};
    /// Current mapping of vertex attribute locations by semantic. The map is owned by the shader program, so care must be taken to switch a null shader program when it's destroyed.
    const HashMap<Pair<i8, i8>, unsigned>* vertexAttributes_{};
    /// Currently bound frame buffer object.
    unsigned boundFBO_{};
    /// Currently bound vertex buffer object.
    unsigned boundVBO_{};
    /// Currently bound uniform buffer object.
    unsigned boundUBO_{};
    /// Read frame buffer for multisampled texture resolves.
    unsigned resolveSrcFBO_{};
    /// Write frame buffer for multisampled texture resolves.
    unsigned resolveDestFBO_{};
    /// Current pixel format.
    int pixelFormat_{};
    /// Map for FBO's per resolution and format.
    HashMap<hash64, FrameBufferObject> frameBuffers_;
    /// OpenGL texture types in use.
    unsigned textureTypes_[MAX_TEXTURE_UNITS]{};
    /// Constant buffer search map.
    ConstantBufferMap allConstantBuffers_;
    /// Currently bound constant buffers.
    ConstantBuffer* constantBuffers_[MAX_SHADER_PARAMETER_GROUPS * 2]{};
    /// Dirty constant buffers.
    Vector<ConstantBuffer*> dirtyConstantBuffers_;
    /// Last used instance data offset.
    unsigned lastInstanceOffset_{};
    /// Map for additional depth textures, to emulate Direct3D9 ability to mix render texture and backbuffer rendering.
    HashMap<unsigned, SharedPtr<Texture2D>> depthTextures_;
    /// Shader program in use.
    ShaderProgram_OGL* shaderProgram_{};
    /// Linked shader programs.
    ShaderProgramMap_OGL shaderPrograms_;
    /// Need FBO commit flag.
    bool fboDirty_{};
    /// Need vertex attribute pointer update flag.
    bool vertexBuffersDirty_{};
    /// sRGB write mode flag.
    bool sRGBWrite_{};
};

}


text:
[MDN](https://developer.mozilla.org/en-US/docs/Web/HTML/Element)
## meta

## XHTML, doctype


text:
'use strict'

module.exports = function(packageJson) {
  var result = []
  var bundled = packageJson.bundledDependencies || packageJson.bundleDependencies;
  if (!bundled || !Array.isArray(bundled)) bundled = [];

  function process(obj, type) {
    obj && typeof obj === 'object' && Object.keys(obj).forEach(function(package_) {
      result.push({
        package: package_,
        version: obj[package_],
        type: type,
        bundled: bundled.indexOf(package_) !== -1
      })
    })
  }

  process(packageJson.dependencies, 'dependency')
  process(packageJson.devDependencies, 'dev')
  process(packageJson.optionalDependencies, 'optional')

  // Find all the dependencies that are only bundled, and we don't know their
  // type nor version number (this would only happen in malformed package.json's,
  // but I'm pretty sure it happens).
  bundled.forEach(function(bundle) {
    if (!result.some(function(r) { return r.package === bundle })) {
      result.push({
        package: bundle,
        bundled: true
      })
    }
  })

  return result
}


text:
package it.cnr.isti.vir.features;

/**
 * @author Fabrizio Falchi
 *
 *	Extends IByteValues
 *  Values returned by objects implementing this interface have been obtained
 *  multiplying by 255 and subctrating 128 because.
 *
 */
public interface IFloatByteValues extends IArrayValues {

	public byte[] getValues();
}


text:
<?php

namespace Sonata\CoreBundle\Command;

use Doctrine\ORM\Mapping\ClassMetadata;
use Gaufrette\Adapter\Local as LocalAdapter;
use Gaufrette\Filesystem;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;

/**
 * Return useful data on the database schema.
 *
 * Class SonataDoctrineUtils
 */
class SonataDumpDoctrineMetaCommand extends ContainerAwareCommand
{
    /**
     * @var array
     */
    protected $metadata;

    /**
     * {@inheritdoc}
     */
    protected function configure()
    {
        $this
            ->setName('sonata:core:dump-doctrine-metadata')
            ->setDefinition(array(
                new InputOption(
                    'entity-name', 'E', InputOption::VALUE_OPTIONAL,
                    'If entity-name is set, dump will only contain the specified entity and all its extended classes.', null
                ),
                new InputOption(
                    'regex', 'r', InputOption::VALUE_OPTIONAL,
                    'If regex is set, dump will only contain entities which name match the pattern.', null
                ),
                new InputOption(
                    'filename', 'f', InputOption::VALUE_OPTIONAL,
                    'If filename is specified, result will be dumped into this file under json format.', null
                ),
            ))
            ->setDescription(
                'Get information on the current Doctrine\'s schema'
            );
    }

    /**
     * {@inheritdoc}
     */
    protected function initialize(InputInterface $input, OutputInterface $output)
    {
        $output->writeln('Initialising Doctrine metadata.');
        $manager = $this->getContainer()->get('doctrine')->getManager();
        $metadata = $manager->getMetadataFactory()->getAllMetadata();

        $allowedMeta = $this->filterMetadata($metadata, $input, $output);

        /** @var ClassMetadata $meta */
        foreach ($allowedMeta as $meta) {
            $this->metadata[$meta->getName()] = $this->normalizeDoctrineORMMeta($meta);
        }
    }

    /**
     * {@inheritdoc}
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        if (!$this->metadata) {
            $output->writeln('<error>No meta was found</error>');

            return 1;
        }

        $this->dumpMetadata($this->metadata, $input, $output);

        return 0;
    }

    /**
     * Display the list of entities handled by Doctrine and their fields.
     *
     * @param array           $metadata
     * @param InputInterface  $input
     * @param OutputInterface $output
     */
    private function dumpMetadata(array $metadata, InputInterface $input, OutputInterface $output)
    {
        foreach ($metadata as $name => $meta) {
            $output->writeln(sprintf('<info>%s</info>', $name));

            foreach ($meta['fields'] as $fieldName => $columnName) {
                $output->writeln(sprintf('  <comment>></comment> %s <info>=></info> %s', $fieldName, $columnName));
            }
        }
        $output->writeln('---------------');
        $output->writeln('----  END  ----');
        $output->writeln('---------------');
        $output->writeln('');

        if ($input->getOption('filename')) {
            $directory = dirname($input->getOption('filename'));
            $filename = basename($input->getOption('filename'));

            if (empty($directory) || $directory === '.') {
                $directory = getcwd();
            }

            $adapter = new LocalAdapter($directory, true);
            $fileSystem = new Filesystem($adapter);
            $success = $fileSystem->write($filename, json_encode($metadata), true);

            if ($success) {
                $output->writeLn(sprintf('<info>File %s/%s successfully created</info>', $directory, $filename));
            } else {
                $output->writeLn(sprintf('<error>File %s/%s could not be created</error>', $directory, $filename));
            }
        }
    }

    /**
     * @param array           $metadata
     * @param InputInterface  $input
     * @param OutputInterface $output
     *
     * @return array
     */
    private function filterMetadata(array $metadata, InputInterface $input, OutputInterface $output)
    {
        $baseEntity = $input->getOption('entity-name');
        $regex = $input->getOption('regex');

        if ($baseEntity) {
            $allowedMeta = array_filter(
                $metadata,
                function ($meta) use ($baseEntity) {
                    /* @var \Doctrine\ORM\Mapping\ClassMetadata $meta */
                    return $meta->rootEntityName === $baseEntity;
                }
            );
        } elseif ($regex) {
            $allowedMeta = array_filter(
                $metadata,
                function ($meta) use ($regex) {
                    /* @var \Doctrine\ORM\Mapping\ClassMetadata $meta */
                    return preg_match($regex, $meta->rootEntityName);
                }
            );
        } else {
            $allowedMeta = $metadata;
        }

        return $allowedMeta;
    }

    /**
     * @param ClassMetadata $meta
     *
     * @return array
     */
    private function normalizeDoctrineORMMeta(ClassMetadata $meta)
    {
        $normalizedMeta = array();
        $fieldMappings = $meta->fieldMappings;

        $normalizedMeta['table'] = $meta->table['name'];

        foreach ($fieldMappings as $field) {
            $normalizedMeta['fields'][$field['fieldName']] = isset($field['columnName']) ? $field['columnName'] : null;
        }

        return $normalizedMeta;
    }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css">
    <link rel="stylesheet" href="style.css" >

Copy existing bootstrap modal

            When button is clicked, existing bootstrap modal in dom is shown.
            It won't be removed from dom on close, due to removeOnClose: false option, so next time button is clicked it will again be shown.

        <textarea class="code" style="width: 99%; height: 250px" readonly>
<button type="button"
        data-as='{
        "click": {
            "bs.modal.copy": {
                "from": "#bs_modal_id",
                "to": "new_modal"
            }
        }
    }'
>Copy modal</button>

...

        </textarea>

            <button type="button"
                data-as='{
                    "click": {
                        "bs.modal.copy": {
                            "from": "#bs_modal_id",
                            "to": "new_modal",
                            "title": "New title",
                            "body": "New modal body text"
                        }
                    }
                }'
            >Copy modal</button>

                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

Pre-loaded model

This modal was in the page when it was loaded.

                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>


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">

<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<meta name="copyright" content="(C) Copyright 2005" />
<meta name="DC.rights.owner" content="(C) Copyright 2005" />
<meta content="public" name="security" />
<meta content="index,follow" name="Robots" />
<meta http-equiv="PICS-Label" content='(PICS-1.1 "http://www.icra.org/ratingsv02.html" l gen true r (cz 1 lz 1 nz 1 oz 1 vz 1) "http://www.rsac.org/ratingsv01.html" l gen true r (n 0 s 0 v 0 l 0) "http://www.classify.org/safesurf/" l gen true r (SS~~000 1))' />
<meta content="task" name="DC.Type" />
<meta name="DC.Title" content="Using the logDevice=logDirectoryPath attribute" />
<meta name="abstract" content="To specify a non-default location for the log directory, set the logDevice=logDirectoryPath attribute on the database connection URL." />
<meta name="description" content="To specify a non-default location for the log directory, set the logDevice=logDirectoryPath attribute on the database connection URL." />
<meta content="logDevice, service.properties file, setting logDevice in" name="DC.subject" />
<meta content="logDevice, service.properties file, setting logDevice in" name="keywords" />
<meta scheme="URI" name="DC.Relation" content="cadminlog98.html" />
<meta scheme="URI" name="DC.Relation" content="radminlog800241.html" />
<meta scheme="URI" name="DC.Relation" content="radminlog800279.html" />
<meta scheme="URI" name="DC.Relation" content="cadminlog800315.html" />
<meta content="XHTML" name="DC.Format" />
<meta content="tadminlog800206" name="DC.Identifier" />
<meta content="en-us" name="DC.Language" />
<link href="commonltr.css" type="text/css" rel="stylesheet" />
<title>Using the logDevice=logDirectoryPath attribute</title>

Using the logDevice=logDirectoryPath attribute

To specify a non-default location for the log directory, set
the <samp class="codeph">logDevice=logDirectoryPath</samp> attribute on the database connection
URL.

This attribute is meaningful when you are creating a database or
when you are restoring a database using roll-forward recovery. You can specify
<samp class="codeph">logDevice=logDirectoryPath</samp> as either an absolute path or
as a path that is relative to the directory where the JVM is executed.

Setting <samp class="codeph">logDevice=logDirectoryPath</samp> on
the database connection URL when you create the database adds an entry to the
<samp class="codeph">service.properties</samp> file. If you ever move the log manually, you
will need to alter the entry in <samp class="codeph">service.properties</samp>. If you move
the log back to the default location, remove the <samp class="codeph">logDevice</samp>
entry from the <samp class="codeph">service.properties</samp> file.

To check the log location for an existing database, you can retrieve
the <samp class="codeph">logDevice=logDirectoryPath</samp> attribute as a database
property by using the following statement:

VALUES SYSCS_UTIL.SYSCS_GET_DATABASE_PROPERTY('logDevice')

For more information, see
Roll-forward recovery in this manual and
"logDevice=logDirectoryPath attribute" in the
Derby Reference Manual.

Parent topic: Logging on a separate device

Related concepts

Issues for logging in a non-default location

Related reference

Example of creating a log in a non-default location

Example of moving a log manually


text:
#include "tensorflow/compiler/xla/service/gpu/tests/gpu_codegen_test.h"
#include "absl/memory/memory.h"
#include "tensorflow/compiler/xla/legacy_flags/debug_options_flags.h"
#include "tensorflow/compiler/xla/service/gpu/gpu_executable.h"
#include "tensorflow/compiler/xla/tests/filecheck.h"
#include "tensorflow/core/platform/logging.h"

namespace xla {
namespace gpu {

std::unique_ptr<HloModule> GpuCodegenTest::CreateNewModuleWithFTZ(bool ftz) {
  HloModuleConfig config;
  auto debug_options = legacy_flags::GetDebugOptionsFromFlags();
  debug_options.set_xla_gpu_ftz(ftz);
  debug_options.set_xla_gpu_max_kernel_unroll_factor(1);
  // TODO(b/38354253): Change tests to use Parameters instead of Constants.
  debug_options.add_xla_disable_hlo_passes("constant_folding");
  config.set_debug_options(debug_options);

  return absl::make_unique<HloModule>(TestName(), config);
}

void GpuCodegenTest::CompileAndVerifyPtx(std::unique_ptr<HloModule> hlo_module,
                                         const string& pattern) {
  std::unique_ptr<Executable> executable =
      std::move(CompileToExecutable(std::move(hlo_module)).ValueOrDie());
  string ptx_str(static_cast<GpuExecutable*>(executable.get())->ptx());
  StatusOr<bool> filecheck_result = RunFileCheck(ptx_str, pattern);
  ASSERT_TRUE(filecheck_result.ok());
  EXPECT_TRUE(filecheck_result.ValueOrDie());
}

}  // namespace gpu
}  // namespace xla


text:
package gov.hhs.fha.nhinc.docsubmission.nhin.deferred.response.proxy11;

import gov.hhs.fha.nhinc.aspect.NwhinInvocationEvent;
import gov.hhs.fha.nhinc.common.nhinccommon.AssertionType;
import gov.hhs.fha.nhinc.common.nhinccommon.NhinTargetSystemType;
import gov.hhs.fha.nhinc.connectmgr.ConnectionManagerException;
import gov.hhs.fha.nhinc.docsubmission.MessageGeneratorUtils;
import gov.hhs.fha.nhinc.docsubmission.aspect.DeferredResponseDescriptionBuilder;
import gov.hhs.fha.nhinc.docsubmission.nhin.deferred.response.proxy11.service.NhinDocSubmissionDeferredResponseServicePortDescriptor;
import gov.hhs.fha.nhinc.messaging.client.CONNECTClient;
import gov.hhs.fha.nhinc.messaging.client.CONNECTClientFactory;
import gov.hhs.fha.nhinc.messaging.service.port.ServicePortDescriptor;
import gov.hhs.fha.nhinc.nhinclib.NhincConstants;
import gov.hhs.fha.nhinc.nhinclib.NhincConstants.GATEWAY_API_LEVEL;
import gov.hhs.fha.nhinc.webserviceproxy.WebServiceProxyHelper;
import gov.hhs.healthit.nhin.XDRAcknowledgementType;
import ihe.iti.xdr._2007.XDRDeferredResponsePortType;

import oasis.names.tc.ebxml_regrep.xsd.rs._3.RegistryResponseType;

import org.apache.log4j.Logger;

/**
 *
 * @author JHOPPESC
 */
public class NhinDocSubmissionDeferredResponseProxyWebServiceSecuredImpl implements
        NhinDocSubmissionDeferredResponseProxy {
    private static final Logger LOG = Logger.getLogger(NhinDocSubmissionDeferredResponseProxyWebServiceSecuredImpl.class);

    private WebServiceProxyHelper oProxyHelper = null;

    public NhinDocSubmissionDeferredResponseProxyWebServiceSecuredImpl() {
        oProxyHelper = createWebServiceProxyHelper();
    }

    protected WebServiceProxyHelper createWebServiceProxyHelper() {
        return new WebServiceProxyHelper();
    }

    protected MessageGeneratorUtils getMessageGeneratorUtils() {
        return MessageGeneratorUtils.getInstance();
    }

    protected CONNECTClient<XDRDeferredResponsePortType> getCONNECTClientSecured(
            ServicePortDescriptor<XDRDeferredResponsePortType> portDescriptor, String url, AssertionType assertion,
              String target, String serviceName) {

        CONNECTClient<XDRDeferredResponsePortType> client = CONNECTClientFactory.getInstance().getCONNECTClientSecured(portDescriptor, assertion, url, target,
                serviceName);
        return client;
    }

    @NwhinInvocationEvent(beforeBuilder = DeferredResponseDescriptionBuilder.class,
            afterReturningBuilder = DeferredResponseDescriptionBuilder.class,
            serviceType = "Document Submission Deferred Response", version = "")
    public XDRAcknowledgementType provideAndRegisterDocumentSetBDeferredResponse11(RegistryResponseType request,
            AssertionType assertion, NhinTargetSystemType target) {
        LOG.debug("Begin provideAndRegisterDocumentSetBDeferredResponse");
        XDRAcknowledgementType response = null;
        try {
            String url = getUrl(target);

            if (request == null) {
                LOG.error("Message was null");
            } else {
                ServicePortDescriptor<XDRDeferredResponsePortType> portDescriptor = new NhinDocSubmissionDeferredResponseServicePortDescriptor();
                CONNECTClient<XDRDeferredResponsePortType> client = getCONNECTClientSecured(portDescriptor, url,
                        assertion, target.getHomeCommunity().getHomeCommunityId(),
                        NhincConstants.NHINC_XDR_RESPONSE_SERVICE_NAME);
                client.enableMtom();

                response = (XDRAcknowledgementType) client.invokePort(XDRDeferredResponsePortType.class,
                        "provideAndRegisterDocumentSetBDeferredResponse", request);
            }
        } catch (Exception ex) {
            LOG.error("Error calling provideAndRegisterDocumentSetBDeferredResponse: " + ex.getMessage(), ex);
            response = getMessageGeneratorUtils().createRegistryErrorXDRAcknowledgementType(ex.getMessage());
        }

        LOG.debug("End provideAndRegisterDocumentSetBDeferredResponse");
        return response;
    }

    /**
     * @return
     * @throws Exception
     * @throws ConnectionManagerException
     * @throws IllegalArgumentException
     */
    protected String getUrl(NhinTargetSystemType target) throws IllegalArgumentException, ConnectionManagerException, Exception {
        return oProxyHelper.getUrlFromTargetSystemByGatewayAPILevel(target,
                NhincConstants.NHINC_XDR_RESPONSE_SERVICE_NAME, GATEWAY_API_LEVEL.LEVEL_g0);
    }

}


text:
package com.mobidevelop.maps.editor.events;

import com.mobidevelop.maps.MapProperties;

public class MapPropertiesChangeEvent extends ChangeEvent<MapProperties> {

	private String property;

	public String getProperty() {
		return property;
	}

	public void setProperty(String property) {
		this.property = property;
	}

	public MapPropertiesChangeEvent() {
		super();
	}

	public MapPropertiesChangeEvent(MapProperties properties) {
		super(properties);
	}

	public MapPropertiesChangeEvent(MapProperties properties, String property) {
		super(properties);
		this.property = property;
	}

	@Override
	public void reset() {
		super.reset();
		setProperty(null);
	}

}


text:
<?php namespace App\Http\Controllers;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Http\Requests\SettingFormRequest;
use App\Setting;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Response;
use Illuminate\Support\Facades\Session;

class SettingsController extends Controller {

    private $settings;

    public function __construct(Setting $settings) {
        $this->middleware('auth');
        $this->settings = $settings->firstOrNew([]);
    }

	/**
	 * Display a listing of the resource.
	 *
	 * @return Response
	 */
	public function index()
	{
		//
	}

    public function edit()
    {
        $settings = $this->settings;
        return view('settings.edit', compact('settings'));
    }

    public function update(SettingFormRequest $request)
    {
        $this->settings->fill($request->input())->save();
        Session::flash('message_success', 'Site settings updated.');
        return Redirect::route('settings_edit');
    }

}


text:
from social_core.backends.google import GoogleOAuth2

from ...site import AuthenticationBackends
from . import BaseBackend

class CustomGoogleOAuth2(BaseBackend, GoogleOAuth2):
    DB_NAME = AuthenticationBackends.GOOGLE


text:
import ClientConfig from '../config/client-config.js';
import DomHelper from './dom-helper.js';

const ENTER_KEYCODE = 13;
const SPACE_BAR_KEYCODE = 32;
const UP_ARROW_KEYCODE = 38;
const DOWN_ARROW_KEYCODE = 40;

/**
 * Handles all requests related to the display of the game, not including the canvas
 */
export default class GameView {
    constructor(backgroundImageUploadCallback, botChangeCallback, foodChangeCallback, imageUploadCallback,
        joinGameCallback, keyDownCallback, muteAudioCallback, playerColorChangeCallback, playerNameUpdatedCallback,
        spectateGameCallback, speedChangeCallback, startLengthChangeCallback, toggleGridLinesCallback) {
        this.isChangingName = false;
        this.backgroundImageUploadCallback = backgroundImageUploadCallback;
        this.imageUploadCallback = imageUploadCallback;
        this.joinGameCallback = joinGameCallback;
        this.keyDownCallback = keyDownCallback;
        this.muteAudioCallback = muteAudioCallback;
        this.playerNameUpdatedCallback = playerNameUpdatedCallback;
        this.spectateGameCallback = spectateGameCallback;
        this._initEventHandling(botChangeCallback, foodChangeCallback, muteAudioCallback, playerColorChangeCallback,
            speedChangeCallback, startLengthChangeCallback, toggleGridLinesCallback);
    }

    ready() {
        // Show everything when ready
        DomHelper.showAllContent();
    }

    setKillMessageWithTimer(message) {
        DomHelper.setKillMessagesDivText(message);
        if (this.killMessagesTimeout) {
            clearTimeout(this.killMessagesTimeout);
        }
        this.killMessagesTimeout = setTimeout(DomHelper.clearKillMessagesDivText.bind(DomHelper),
            ClientConfig.TIME_TO_SHOW_KILL_MESSAGE_IN_MS);
    }

    setMuteStatus(isMuted) {
        let text;
        if (isMuted) {
            text = 'Unmute';
        } else {
            text = 'Mute';
        }
        DomHelper.setToggleSoundButtonText(text);
    }

    showFoodAmount(foodAmount) {
        DomHelper.setCurrentFoodAmountLabelText(foodAmount);
    }

    showKillMessage(killerName, victimName, killerColor, victimColor, victimLength) {
        this.setKillMessageWithTimer(`<span style='color: ${killerColor}'>${killerName}</span> killed ` +
            `<span style='color: ${victimColor}'>${victimName}</span>` +
            ` and grew by <span style='color: ${killerColor}'>${victimLength}</span>`);
    }

    showKilledEachOtherMessage(victimSummaries) {
        let victims = '';
        for (const victimSummary of victimSummaries) {
            victims += `<span style='color: ${victimSummary.color}'>${victimSummary.name}</span> `;
        }
        this.setKillMessageWithTimer(`${victims} have killed each other`);
    }

    showRanIntoWallMessage(playerName, playerColor) {
        this.setKillMessageWithTimer(`<span style='color: ${playerColor}'>${playerName}</span> ran into a wall`);
    }

    showSuicideMessage(victimName, victimColor) {
        this.setKillMessageWithTimer(`<span style='color: ${victimColor}'>${victimName}</span> committed suicide`);
    }

    showNotification(notification, playerColor) {
        const notificationDiv = DomHelper.getNotificationsDiv();
        const formattedNotification = `<div><span class='time-label'>${new Date().toLocaleTimeString()} - </span>` +
            `<span style='color: ${playerColor}'>${notification}<span/></div>`;
        notificationDiv.innerHTML = formattedNotification + notificationDiv.innerHTML;
    }

    showNumberOfBots(numberOfBots) {
        DomHelper.setCurrentNumberOfBotsLabelText(numberOfBots);
    }

    showPlayerStats(playerStats) {
        let formattedScores = '
' +
            'Name' +
            'Score' +
            'High' +
            'Kills' +
            'Deaths
';
        for (const playerStat of playerStats) {
            let playerImageElement = '';
            if (playerStat.base64Image) {
                playerImageElement = `<img src=${playerStat.base64Image} class='player-stats-image'></img>`;
            }
            formattedScores += `<div class='player-stats-content'><span class='image'>${playerImageElement}</span>` +
                `<span class='name' style='color: ${playerStat.color}'>${playerStat.name}</span>` +
                `<span class='stat'>${playerStat.score}</span>` +
                `<span class='stat'>${playerStat.highScore}</span>` +
                `<span class='stat'>${playerStat.kills}</span>` +
                `<span class='stat'>${playerStat.deaths}</span></div>`;
        }
        DomHelper.setPlayerStatsDivText(formattedScores);
    }

    showSpeed(speed) {
        DomHelper.setCurrentSpeedLabelText(speed);
    }

    showStartLength(startLength) {
        DomHelper.setCurrentStartLengthLabelText(startLength);
    }

    updatePlayerName(playerName, playerColor) {
        DomHelper.setPlayerNameElementValue(playerName);
        if (playerColor) {
            DomHelper.setPlayerNameElementColor(playerColor);
        }
    }

    /*******************
     *  Event handling *
     *******************/

    _handleChangeNameButtonClick() {
        if (this.isChangingName) {
            this._saveNewPlayerName();
        } else {
            DomHelper.setChangeNameButtonText('Save');
            DomHelper.setPlayerNameElementReadOnly(false);
            DomHelper.getPlayerNameElement().select();
            this.isChangingName = true;
        }
    }

    _handleKeyDown(e) {
        // Prevent keyboard scrolling default behavior
        if ((e.keyCode === UP_ARROW_KEYCODE || e.keyCode === DOWN_ARROW_KEYCODE) ||
             (e.keyCode === SPACE_BAR_KEYCODE && e.target === DomHelper.getBody())) {
            e.preventDefault();
        }

        // When changing names, save new name on enter
        if (e.keyCode === ENTER_KEYCODE && this.isChangingName) {
            this._saveNewPlayerName();
            DomHelper.blurActiveElement();
            return;
        }

        if (!this.isChangingName) {
            this.keyDownCallback(e.keyCode);
        }
    }

    _handleBackgroundImageUpload() {
        const uploadedBackgroundImageAsFile = DomHelper.getBackgroundImageUploadElement().files[0];
        if (uploadedBackgroundImageAsFile) {
            // Convert file to image
            const image = new Image();
            const self = this;
            image.onload = () => {
                self.backgroundImageUploadCallback(image, uploadedBackgroundImageAsFile.type);
            };
            image.src = URL.createObjectURL(uploadedBackgroundImageAsFile);
        }
    }

    _handleImageUpload() {
        const uploadedImageAsFile = DomHelper.getImageUploadElement().files[0];
        if (uploadedImageAsFile) {
            // Convert file to image
            const image = new Image();
            const self = this;
            image.onload = () => {
                self.imageUploadCallback(image, uploadedImageAsFile.type);
            };
            image.src = URL.createObjectURL(uploadedImageAsFile);
        }
    }

    _handlePlayOrWatchButtonClick() {
        const command = DomHelper.getPlayOrWatchButton().textContent;
        if (command === 'Play') {
            DomHelper.setPlayOrWatchButtonText('Watch');
            this.joinGameCallback();
        } else {
            DomHelper.setPlayOrWatchButtonText('Play');
            this.spectateGameCallback();
        }
    }

    _saveNewPlayerName() {
        const playerName = DomHelper.getPlayerNameElement().value;
        if (playerName && playerName.trim().length > 0 && playerName.length <= ClientConfig.MAX_NAME_LENGTH) {
            this.playerNameUpdatedCallback(playerName);
            DomHelper.setChangeNameButtonText('Change Name');
            DomHelper.setPlayerNameElementReadOnly(true);
            this.isChangingName = false;
            DomHelper.hideInvalidPlayerNameLabel();
        } else {
            DomHelper.showInvalidPlayerNameLabel();
        }
    }

    _initEventHandling(botChangeCallback, foodChangeCallback, muteAudioCallback, playerColorChangeCallback, speedChangeCallback,
        startLengthChangeCallback, toggleGridLinesCallback) {
        // Player controls
        DomHelper.getChangeColorButton().addEventListener('click', playerColorChangeCallback);
        DomHelper.getChangeNameButton().addEventListener('click', this._handleChangeNameButtonClick.bind(this));
        DomHelper.getPlayerNameElement().addEventListener('blur', this._saveNewPlayerName.bind(this));
        DomHelper.getImageUploadElement().addEventListener('change', this._handleImageUpload.bind(this));
        DomHelper.getClearUploadedImageButton().addEventListener('click', this.imageUploadCallback);
        DomHelper.getBackgroundImageUploadElement().addEventListener('change', this._handleBackgroundImageUpload.bind(this));
        DomHelper.getClearUploadedBackgroundImageButton().addEventListener('click', this.backgroundImageUploadCallback);
        DomHelper.getPlayOrWatchButton().addEventListener('click', this._handlePlayOrWatchButtonClick.bind(this));
        DomHelper.getToggleGridLinesButton().addEventListener('click', toggleGridLinesCallback);
        DomHelper.getToggleSoundButton().addEventListener('click', muteAudioCallback);
        DomHelper.getFullScreenButton().addEventListener('click', DomHelper.toggleFullScreenMode);
        window.addEventListener('keydown', this._handleKeyDown.bind(this), true);

        // Admin controls
        DomHelper.getIncreaseBotsButton().addEventListener('click',
            botChangeCallback.bind(this, ClientConfig.INCREMENT_CHANGE.INCREASE));
        DomHelper.getDecreaseBotsButton().addEventListener('click',
            botChangeCallback.bind(this, ClientConfig.INCREMENT_CHANGE.DECREASE));
        DomHelper.getResetBotsButton().addEventListener('click',
            botChangeCallback.bind(this, ClientConfig.INCREMENT_CHANGE.RESET));
        DomHelper.getIncreaseFoodButton().addEventListener('click',
            foodChangeCallback.bind(this, ClientConfig.INCREMENT_CHANGE.INCREASE));
        DomHelper.getDecreaseFoodButton().addEventListener('click',
            foodChangeCallback.bind(this, ClientConfig.INCREMENT_CHANGE.DECREASE));
        DomHelper.getResetFoodButton().addEventListener('click',
            foodChangeCallback.bind(this, ClientConfig.INCREMENT_CHANGE.RESET));
        DomHelper.getIncreaseSpeedButton().addEventListener('click',
            speedChangeCallback.bind(this, ClientConfig.INCREMENT_CHANGE.INCREASE));
        DomHelper.getDecreaseSpeedButton().addEventListener('click',
            speedChangeCallback.bind(this, ClientConfig.INCREMENT_CHANGE.DECREASE));
        DomHelper.getResetSpeedButton().addEventListener('click',
            speedChangeCallback.bind(this, ClientConfig.INCREMENT_CHANGE.RESET));
        DomHelper.getIncreaseStartLengthButton().addEventListener('click',
            startLengthChangeCallback.bind(this, ClientConfig.INCREMENT_CHANGE.INCREASE));
        DomHelper.getDecreaseStartLengthButton().addEventListener('click',
            startLengthChangeCallback.bind(this, ClientConfig.INCREMENT_CHANGE.DECREASE));
        DomHelper.getResetStartLengthButton().addEventListener('click',
            startLengthChangeCallback.bind(this, ClientConfig.INCREMENT_CHANGE.RESET));
    }
}


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>Kawaii Airlines</title>
    <link rel="stylesheet" href="assets/components/bootstrap-3.3.1/css/bootstrap.css">

    <?php require "system/db_controller.php"; ?>

            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar"
                    aria-expanded="false" aria-controls="navbar">
                Toggle navigation

            </button>
            Kawaii Airlines

Home

Booking

Flights

Logi sisse

Register

<form class="form-horizontal">

            Aeg
            Kohtade Arv
            Lennu id

            <?= $lennud["kuup2ev"]; ?>
            <?= $lennud["kohtade_arv"]; ?>
            <?= $lennud["id"]; ?>

</form>


text:
package iurii.job.interview.topcoder.srm503;

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

/**
 * The Grid Kingdom lies on a plane. There are N cities and M villages in the Grid Kingdom, each is a point on the plane. The i-th city is located at coordinates (cityX[i], cityY[i]) and the i-th village is located at coordinates (villageX[i], villageY[i]). Initially, there are no roads in the kingdom, so no village is initially connected to any city.  To improve this, the king has ordered that each village shall be connected to a city by a system of roads. The scheme for building the roads is as follows:  While there exists a village that is not connected to any city:
 * Pick one unconnected village (each has an equal probability of being chosen), call it V.
 * Select a point, X, which is nearest to V, in terms of Euclidean Distance, and is either a city or a village-that-is-already-connected-to-a-city. If multiple such points are equally near, pick any of the nearest points with equal probability.
 * Construct a road from V to X. The length of this road is equal to the Euclidean Distance between points V and X. V is now connected to a city.
 * <p>
 * You are the king's advisor (for the day) and are in charge of applying the scheme above such that the total length of the constructed roads is minimum. Return this total length.
 * #Return the expected total length of all the roads that will be constructed after all villages are connected to a city.
 */
public class KingdomXCitiesandVillages {

    public static void main(String[] args) {
        System.out.println(new KingdomXCitiesandVillages().determineLength(new int[]{1, 2}, new int[]{1, 1}, new int[]{1, 2}, new int[]{2, 2}));
    }

    public double determineLength(int[] cityX, int[] cityY, int[] villageX, int[] villageY) {
        List<Point> notConnectedVillages = new ArrayList<Point>();
        for (int i = 0; i < villageX.length; i++) {
            Point village = new Point();
            village.x = villageX[i];
            village.y = villageY[i];
            notConnectedVillages.add(village);
        }
        List<Point> distances = new ArrayList<Point>();
        for (int i = 0; i < cityX.length; i++) {
            Point city = new Point();
            city.x = cityX[i];
            city.y = cityY[i];
            distances.add(city);
        }
        return addVillage(notConnectedVillages, distances, villageX.length);
    }

    private double addVillage(
            List<Point> notConnectedVillages,
            List<Point> distances,
            int size) {
        double minTotalDistance = Integer.MAX_VALUE;
        for (int villageIndex = 0; villageIndex < size; villageIndex++) {
            Point village = notConnectedVillages.get(villageIndex);
            notConnectedVillages.remove(villageIndex);
            recalculateDistances(distances, village);
            Collections.sort(distances);
            double minDistance = distances.get(0).distance;
            distances.add(village);
            if (size != 1) {
                minDistance += addVillage(notConnectedVillages, distances, size - 1);
            }
            notConnectedVillages.add(village);
            distances.remove(village);
            if (minTotalDistance > minDistance) {
                minTotalDistance = minDistance;
            }
        }
        return minTotalDistance;
    }

    private void recalculateDistances(List<Point> distances, Point village) {
        for (Point distance : distances) {
            distance.distance = Math.sqrt((distance.x - village.x) * (distance.x - village.x) + (distance.y - village.y) * (distance.y - village.y));
        }
    }
}

class Point implements Comparable<Point> {
    int x;
    int y;
    double distance;

    public int compareTo(Point other) {
        if (distance - other.distance > 0) {
            return 1;
        } else if (distance - other.distance < 0) {
            return -1;
        } else {
            return 0;
        }
    }
}


text:
<!DOCTYPE html>

    <meta http-equiv="refresh" content="0;URL=struct.U0.html">

Redirecting to struct.U0.html...


text:
package jp.gr.java_conf.jyukon.detabu.stub;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.support.v4.app.NotificationCompat;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.widget.RemoteViews;

import com.google.android.glass.timeline.LiveCard;

import javax.inject.Inject;

import jp.gr.java_conf.jyukon.detabu.ILiveCard;
import jp.gr.java_conf.jyukon.detabu.R;

public class LiveCardImpl implements ILiveCard {
    @Inject NotificationManager mNotificationManager;
    private RemoteViews mRemoteViews;
    private Context mContext;
    private PendingIntent mPendingIntent;
    private boolean published;

    public LiveCardImpl(Context context, String id) {
        mContext = context;
    }

    @Override
    public ILiveCard setDirectRenderingEnabled(boolean enable) {
        return this;
    }

    @Override
    public SurfaceHolder getSurfaceHolder() {
        return new DummySurfaceHolder();
    }

    @Override
    public ILiveCard setAction(PendingIntent pendingIntent) {
        mPendingIntent = pendingIntent;
        return this;
    }

    @Override
    public void publish() {
        Notification notification = new NotificationCompat.Builder(mContext).setContent(mRemoteViews).setContentIntent(mPendingIntent).setSmallIcon(R.drawable.icon).build();
        mNotificationManager.notify(0, notification);
        published = true;
    }

    @Override
    public boolean isPublished() {
        return published;
    }

    @Override
    public void unpublish() {
        published = false;
    }

    static class DummySurfaceHolder implements SurfaceHolder {

        @Override
        public void addCallback(Callback callback) {}

        @Override
        public void removeCallback(Callback callback) {}

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

        @Override
        public void setType(int i) {}

        @Override
        public void setFixedSize(int i, int i2) {}

        @Override
        public void setSizeFromLayout() {}

        @Override
        public void setFormat(int i) {}

        @Override
        public void setKeepScreenOn(boolean b) {}

        @Override
        public Canvas lockCanvas() {
            return null;
        }

        @Override
        public Canvas lockCanvas(Rect rect) {
            return null;
        }

        @Override
        public void unlockCanvasAndPost(Canvas canvas) {}

        @Override
        public Rect getSurfaceFrame() {
            return null;
        }

        @Override
        public Surface getSurface() {
            return null;
        }
    }
}


text:
typedef void (*entry_func) (void) __attribute__ ((noreturn));
extern entry_func entry_addr;
static void bsd_boot_entry (void)
{
  stop ();
}
void bsd_boot (void)
{
  entry_addr = (entry_func) bsd_boot_entry;
  (*entry_addr) ();
}


text:
CREATE KEYSPACE nobel
WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 2};

-- create table
CREATE TABLE nobel.laureates
(
  laureateid int,
  firstname text,
  surname text,
  borncountrycode text,
  borncity text,
  year int,
  category text,
  PRIMARY KEY (borncountrycode, laureateid)
);

COPY nobel.laureates (year, category, laureateid, firstname, surname, borncountrycode, borncity)
FROM 'nobel-laureates.csv';


text:
'use strict';

var expect = require('chai').expect;
var test_node_windows_link = require('../');


text:
import copy
import json
import logging
import time

from .params import ParameterCollection, Parameter

logger = logging.getLogger(__name__)

class TaskBase(type):
    """Parameter metaclass, used to register parameter classes for lookup by name."""

    _tasks_by_name = {}

    def __new__(cls, name, bases, attrs):
        new_class = super(TaskBase, cls).__new__(cls, name, bases, attrs)

        name = getattr(new_class, 'name', None)
        if name:
            cls._tasks_by_name[new_class.name] = new_class

        setattr(new_class, '_tasks_by_name', cls._tasks_by_name)

        return new_class

class Task(metaclass=TaskBase):
    """A discrete task with defined inputs and outputs. Extended to implement specific functionality."""

    name = ''
    inputs = []  # A list of `Parameter` objects defining accepted inputs for this task
    outputs = []  # A list of `Parameter` objects defining expected outputs for this task
    allow_extra_args = False  # If true, task may be called with kwargs not defined in `inputs`

    def __init__(self):
        self.inputs = copy.copy(self.inputs)
        self.outputs = copy.copy(self.outputs)

    def __call__(self, **kwargs):
        """
        Performs parameter validation and calls `self.execute()` with cleaned parameters. Always returns a
        `ParameterCollection` object representing the task output(s).
        """

        call_kwargs = self.validate_inputs(kwargs)

        if self.name:
            logger.info('Starting task {0}...'.format(self.name))
        start = time.time()
        try:
            ret = self.execute(**call_kwargs)
        except:
            if self.name:
                logger.exception('Task {0} failed.'.format(self.name))
            raise
        if self.name:
            logger.info('Task {0} finished in {1:.3f} seconds'.format(self.name, time.time() - start))

        if isinstance(ret, ParameterCollection):
            outputs = ret
        else:
            outputs = ParameterCollection(self.outputs)
            if self.outputs:
                outputs[self.outputs[0].name] = ret

        return outputs

    def validate_inputs(self, inputs):
        params = ParameterCollection(self.inputs)
        call_kwargs = {}

        for k, v in inputs.items():
            try:
                params[k] = v
            except KeyError:
                if self.allow_extra_args:
                    call_kwargs[k] = v
                else:
                    raise TypeError('Unrecognized parameter: {}'.format(k))

        if not params.is_complete:
            missing_parameters = set(x.name for x in self.inputs if x.required).difference(set(inputs.keys()))
            raise TypeError('Missing required parameters: {}'.format(tuple(missing_parameters)))

        call_kwargs.update(params.format_args())
        return call_kwargs

    @classmethod
    def by_name(cls, name):
        return cls._tasks_by_name.get(name)

    def execute(self, **kwargs):
        """
        This should be implemented by child classes to perform the actual work of the task. Arguments should match
        input parameters for this task. Likewise, returned value(s) should match the output parameters.
        """

        raise NotImplementedError

class WorkflowNode(object):
    """
    Used by `Workflow` to represent a single node (a unique id, a task, and input mappings) in the workflow.
    """

    def __init__(self, node_id, task, inputs):
        self.id = node_id
        self.task = task
        self.inputs = inputs

        self.completed = False
        self.outputs = None

    def add_input(self, name, source, value):
        self.inputs[name] = (source, value)

class Workflow(Task):
    """A specialized task to manage the processing of many inter-related tasks."""

    def __init__(self, name=None, description=None):
        """Constructs the workflow from a dictionary structure."""

        super(Workflow, self).__init__()

        self.name = name
        self.description = description

        self.nodes_by_id = {}
        self.dependents_by_node_id = {}
        self.output_mapping = {}  # {<workflow output param name>: (<node id>, <task output param name>), ...}

    def _execute_node(self, node, workflow_inputs):
        task_inputs = {}

        for name, (source, value) in node.inputs.items():
            if source == 'input':
                if value in workflow_inputs:
                    task_inputs[name] = workflow_inputs[value]
            elif source == 'dependency':
                dependency = self.nodes_by_id[value[0]]

                if not dependency.completed:
                    self._execute_node(dependency, workflow_inputs)

                if value[1] in dependency.outputs:
                    task_inputs[name] = dependency.outputs[value[1]]

                dependents = self.dependents_by_node_id[dependency.id]
                dependents.remove(node.id)
                if not dependents:
                    dependency.outputs = None  # Allow release of outputs which are no longer needed
            elif source == 'literal':
                task_inputs[name] = value
            else:
                raise ValueError('Invalid input source: {0}'.format(source))

        node.outputs = node.task(**task_inputs).format_args()
        node.completed = True

    def execute(self, **kwargs):
        outputs = ParameterCollection(self.outputs)

        for param, (node_id, name) in self.output_mapping.items():
            node = self.nodes_by_id[node_id]

            if not node.completed:
                self._execute_node(node, kwargs)

            outputs[param] = node.outputs[name]

        for node in self.nodes_by_id.values():
            node.outputs = None
            node.completed = False

        return outputs

    def add_node(self, node_id, task, inputs):
        """
        Adds a node to the workflow.

        :param node_id: A unique identifier for the new node.
        :param task: The task to run.
        :param inputs: A mapping of inputs from workflow inputs, or outputs from other nodes. The format should be
            `{input_name: (source, value), ...}` where `input_name` is the parameter name for the task input, source is
            "input" or "dependency" and `value` is either the workflow input name (if source is "input") or a 2-tuple
            with a node id and an output parameter name from that node's task to map to the input.
        """

        if node_id in self.nodes_by_id:
            raise ValueError('The node {0} already exists in this workflow.'.format(node_id))

        node = WorkflowNode(node_id, task, inputs)
        self.nodes_by_id[node_id] = node

        for source, value in inputs.values():
            if source == 'dependency':
                dependents = self.dependents_by_node_id.get(value[0], set())
                dependents.add(node_id)
                self.dependents_by_node_id[value[0]] = dependents

    def map_output(self, node_id, node_output_name, parameter_name):
        """
        Maps the output from a node to a workflow output.

        :param node_id: The id of the node to map from.
        :param node_output_name: The output parameter name for the node task to map to the workflow output.
        :param parameter_name: The workflow output parameter name.
        """

        self.output_mapping[parameter_name] = (node_id, node_output_name)

        dependents = self.dependents_by_node_id.get(node_id, set())
        dependents.add('output_{}'.format(parameter_name))
        self.dependents_by_node_id[node_id] = dependents

    def to_json(self, indent=None):
        """Serialize this workflow to JSON"""

        inputs = ParameterCollection(self.inputs)

        d = {
            'meta': {
                'name': self.name,
                'description': self.description
            },
            'inputs': [],
            'workflow': [],
            'outputs': [{'name': k, 'node': v} for k, v in self.output_mapping.items()]
        }

        for parameter in self.inputs:
            input_info = {
                'name': parameter.name,
                'type': parameter.id
            }

            args, kwargs = parameter.serialize_args()
            args = list(args)
            args.pop(0)  # 'name' is already taken care of
            kwargs.pop('required', None)  # 'required' is assumed True for workflow inputs
            if args or kwargs:
                input_info['args'] = [args, kwargs]

            d['inputs'].append(input_info)

        for node in sorted(self.nodes_by_id.values(), key=lambda x: x.id):
            task_name = node.task.name
            if not task_name:
                raise ValueError('The task {0} does not have a name and therefore cannot be serialized.'.format(
                    node.task.__class__.__name__)
                )

            node_inputs = {}
            for input_name, (source, value) in node.inputs.items():
                input_info = {'source': source}

                if source == 'input':
                    input_info['input'] = inputs.by_name[value].name
                else:
                    input_info['node'] = value

                node_inputs[input_name] = input_info

            d['workflow'].append({
                'id': node.id,
                'task': task_name,
                'inputs': node_inputs
            })

        return json.dumps(d, indent=indent)

    @classmethod
    def from_json(cls, text):
        """Return a new workflow, deserialized from a JSON string"""

        d = json.loads(text)

        meta = d.get('meta', {})
        workflow = cls(name=meta.get('name'), description=meta.get('description'))

        for workflow_input in d.get('inputs', []):
            parameter_cls = Parameter.by_id(workflow_input['type'])

            args = [workflow_input['name']]
            kwargs = {'required': True}
            if workflow_input.get('args'):
                args = workflow_input['args'][0] + args
                kwargs.update(workflow_input['args'][1])
                args, kwargs = parameter_cls.deserialize_args(args, kwargs)

            workflow.inputs.append(parameter_cls(*args, **kwargs))

        for node in d.get('workflow', []):
            node_inputs = {}
            for k, v in node.get('inputs', {}).items():
                node_inputs[k] = (v['source'], v.get('input') or v.get('node'))

            workflow.add_node(node['id'], Task.by_name(node['task'])(), node_inputs)

        for output in d.get('outputs', []):
            node = output['node']
            node_parameters = ParameterCollection(workflow.nodes_by_id[node[0]].task.outputs)

            # Add parameter to workflow output
            output_param = copy.copy(node_parameters.by_name[node[1]])
            output_param.name = output['name']
            workflow.outputs.append(output_param)

            workflow.map_output(node[0], node[1], output['name'])

        return workflow